<template>
  <div class="token-list-wrapper-fa">
    <FilterBtns></FilterBtns>
    <div class="token-list-wrapper">
      <t-table
        row-key="index"
        hover
        :onRowClick="handleRowClick"
        :row-class-name="getRowClassName"
        :sort="sort"
        :headerAffixedTop="TableScroll"
        @sort-change="sortChange"
        :data="resultData.list"
        :loading="loading"
        table-layout="auto"
        :columns="columns"
        id="table-height-auto"
      >
        <template #index="{ row }">
          <span>{{ row.index + 100 * (pageNum - 1) }}</span>
        </template>
        <template #Pool>
          <span>{{ $t('TableList.pool') + HeadTokenType }}</span>
        </template>
        <template #pb="{ row }">
          <span>{{ Judgment() + row.pb }}</span>
        </template>
        <template #tn="{ row }">
          <div class="name-block">
            <div class="tn">{{ row.tn }}</div>
            <div class="symbol">{{ row.sy }}/{{ row.ps }}</div>
          </div>
        </template>
        <template #operation="{ row }">
          <JumpOther :tb="row.tbname" type="detail" content="K Line">
            <template #svg> <KLink class="k-link"></KLink> </template
          ></JumpOther>
        </template>
        <template #media="{ row }">
          <JumpOther :tb="row.tbname" type="analysis" content="analysis">
            <template #svg>
              <analysisSvg class="to-analysis"></analysisSvg>
            </template>
          </JumpOther>
        </template>
        <template #sortIcon>
          <SortSvg></SortSvg>
        </template>
      </t-table>
      <div class="page-footer">
        <CustPagination
          :pageNum="pageNum"
          :total="resultData.total"
          :continues="8"
          @pageChange="onCurrentChange"
        ></CustPagination>
      </div>
    </div>
  </div>
</template>
<script setup lang="tsx">
import { parsePercent, parseCoinAmount, parseNumberToK } from '@/utils/tool';
import { useI18n } from 'vue-i18n';
import CustPagination from './CustPagination.vue';
import request from '@/utils/request';
import { filterChainObj } from '@/constants/UnifiedManagementChain';
import JumpOther from './JumpOther.vue';
import KLink from '/public/images/svg/table/k_link.svg';
import analysisSvg from '/public/images/svg/table/media.svg';
import SortSvg from '/public/images/svg/table/sort.svg';
import UpSvg from '/public/images/svg/table/up.svg';
import DownSvg from '/public/images/svg/table/down.svg';
import { webLogo } from '@/constants/logo';
import FilterBtns from './FilterBtn';
const route = useRoute();
// 当前链
const chain = useChain();
const loading = ref(false);
// 筛选条件
const GlbFilter = useCurFilter();
//
const HeadTokenType = useTableHeadToken();
const ChainObj = ref();
if (route.params.chain) {
  let Obj = filterChainObj('name', route.params.chain);
  if (Obj) {
    ChainObj.value = Obj;
    chain.value = Obj.value;
    HeadTokenType.value = ChainObj.value.Currency[0];
  }
} else {
  ChainObj.value = filterChainObj('value', chain.value);
}

useHead({
  title: `Dexfilter | ${ChainObj.value.name ?? 'ETH'}`,
  link: [webLogo],
  meta: [
    {
      name: 'description',
      content:
        'DexFilter是一个链上过滤器，它对链上的所有数据进行统计、监控。可以通过过滤功能过滤出相应的链上项目。每个资金池都做了数据分析，深入分析资金池的涨跌趋势，方便用户做出判断，也方便用户查看资金池是否为貔貅。',
    },
  ],
});
const { t } = useI18n();
const pageNum = ref(1);
if (route.params.page) {
  if (typeof parseInt(route.params.page) === 'number')
    pageNum.value = parseInt(route.params.page);
  GlbFilter.value.page = parseInt(route.params.page);
}

// 预渲染的数据
const PreRenderList = UsePreRenderList();
const resultData = reactive(PreRenderList.value);
// 右侧数据
const RightInfo = useCurrentRightInfo();

// 通知表格变化
const getTableList = () => {
  try {
    loading.value = true;
    request
      .get(`/v1/${chain.value}/index`, {
        params: GlbFilter.value,
      })
      .then((result: any) => {
        if (result.list.length) {
          TableFilter(result);
          loading.value = false;
          if (process.client) {
            closeInterVal();
            // 开启定时器
            Intervalfun();
          }
          // 通知右侧请求接口
          RightInfo.value.token = result.list[0].token;
          RightInfo.value.tb = result.list[0].tbname;
          RightInfo.value.r24h = result.list[0].r24h;
        }
      });
  } catch (e) {
    loading.value = false;
    if (process.client) {
      closeInterVal();
    }
  }
};
const ChangeTable = useChangeTable();
watch(
  () => ChangeTable.value,
  (v) => {
    getTableList();
  }
);
// 表格数据过滤方法
const TableFilter = (result: any) => {
  if ('list' in result) {
    result.list.forEach((item, index) => {
      item.index = index + 1;
      item.up = '$' + parseCoinAmount(item.up);
      // 加上$符号后，无法排序，故加上原始vn
      item.oldVn = item.vn;
      item.vn = '$' + parseNumberToK(item.vn);
      // 旧pb
      item.oldPb = item.pb;
      item.pb = parseNumberToK(item.pb);
      item.r5m = parseFloat(item.r5m).toFixed(3);
      item.r1h = parseFloat(item.r1h).toFixed(3);
      item.r4h = parseFloat(item.r4h).toFixed(3);
      item.r24h = parseFloat(item.r24h).toFixed(3);
      // txn
    });
    resultData.list = result.list;
    resultData.total = result.dataCount;
  } else {
    resultData.list = [];
  }
};

// 预取数据
// const { refresh } = await useLazyFetch(
//   () => `http://156.247.9.93:9501/v1${chain.value}/index`,
//   {
//     params: GlbFilter.value,
//     onResponse({ request, response, options }) {
//       try {
//         loading.value = false;
//         if (response._data.data) {
//           TableFilter(toRaw(response._data.data));
//         }
//       } catch (e) {
//         resultData.list = [];
//         console.log(e);
//       }
//       return response._data;
//     },
//     onRequestError({ error }) {
//       console.log(error);
//     },
//   }
// );
// 当前选中的行数
const CurLineIndex = ref(0);
function next() {
  loading.value = true;
  refresh();
}
watch(
  () => chain.value,
  (v) => {
    CurLineIndex.value = 0;
    pageNum.value = 1;
    // 修改title
    ChainObj.value = filterChainObj('value', chain.value);
    // 请求数据
    getTableList();
  }
);
// 判断是否需要加$
const Judgment = () => {
  if (HeadTokenType.value === 'USDT') {
    return '$';
  } else {
    return '';
  }
};

// 添加行类名
const getRowClassName = ({ row, rowIndex }) => {
  if (rowIndex === CurLineIndex.value) return 'custom-third-class-name';
  return '';
};
// tbName---流动池折线图传递参数
const handleRowClick = ({ index, row }) => {
  CurLineIndex.value = index;
  // 提交到右侧
  RightInfo.value.token = row.token;
  RightInfo.value.tb = row.tbname;
  RightInfo.value.r24h = row.r24h.toString();
};
// 表格数据轮询
let listInterval: any = null;
// 监听是否切出页面
const listenerWindow = (fn: any) => {
  document.addEventListener('visibilitychange', fn);
};
// 取消监听
const closeListener = (fn: any) => {
  document.removeEventListener('visibilitychange', fn);
};
// 关闭定时器
const closeInterVal = () => {
  if (listInterval) {
    clearInterval(listInterval);
  }
};
// 有数据，开启定时器
const Intervalfun = () => {
  listInterval = setInterval(() => {
    getTableList();
  }, 10000);
};
// 窗口关闭和打开要执行的方法
const windowOpenFn = (e: any) => {
  // ==visible代表在当前窗口
  let isExist = e.target.visibilityState;
  if (isExist === 'visible') {
    // 先关再开
    closeInterVal();
    Intervalfun();
  } else {
    // 离开页面
    closeInterVal();
  }
};
// 表头吸顶
const TableScroll = ref(null);
onMounted(() => {
  // 开启屏幕监听
  listenerWindow(windowOpenFn);
  // 开启定时器
  // 先关再开
  closeInterVal();
  Intervalfun();
  // 给右侧提供第一条数据
  if (resultData.list.length) {
    RightInfo.value.token = resultData.list[0].token;
    RightInfo.value.tb = resultData.list[0].tbname;
    RightInfo.value.r24h = resultData.list[0].r24h;
  }
  loading.value = false;
  TableScroll.value = {
    offsetTop: -1,
    zIndex: 10,
    container: '#layout-scroll',
  };
});

onUnmounted(() => {
  closeListener(windowOpenFn);
  closeInterVal();
});

const onCurrentChange = (v) => {
  pageNum.value = v;
  GlbFilter.value.page = v;
  // next();
};
const sort = ref({});
const sortChange = (v, options) => {
  sort.value = v;
  resultData.list = options.currentDataSource;
};
const riseFailLabel = (h, { col, row }) => {
  let className = '';
  let prefix = '';
  if (row[col.colKey] > 0) {
    className = 'up';
    prefix = '+';
  } else if (row[col.colKey] < 0) {
    className = 'down';
    prefix = '';
  }
  return (
    <span class={[className, 'custom-r-time-td']}>
      {className == 'up' ? <UpSvg></UpSvg> : ''}
      {className == 'down' ? <DownSvg></DownSvg> : ''}
      {prefix}
      {parsePercent(row[col.colKey])}
    </span>
  );
};
const riseFailLabel2 = (h, { col, row }) => {
  return <span class="custom-Indicators-td">{row[col.colKey]}</span>;
};
const columns = computed(() => {
  return [
    {
      title: t('TableList.tokenbase'),
      align: 'center',
      className: 'custom-before-line',
      children: [
        {
          colKey: 'index',
          width: 'auto',
          title: '#',
        },
        {
          colKey: 'tn',
          title: t('TableList.token'),
        },
      ],
    },
    {
      title: t('TableList.basic'),
      align: 'center',
      className: 'custom-before-line',
      children: [
        {
          colKey: 'up',
          title: t('TableList.price'),
          align: 'center',
          cell: riseFailLabel2,
        },
        {
          colKey: 'pb',
          title: 'Pool',
          sortType: 'all',
          align: 'center',
          cell: riseFailLabel2,
          sorter: (a, b) => parseFloat(a.oldPb) - parseFloat(b.oldPb),
        },
        {
          colKey: 'vn',
          title: t('TableList.volume'),
          sortType: 'all',
          cell: riseFailLabel2,
          sorter: (a, b) => parseFloat(a.oldVn) - parseFloat(b.oldVn),
          align: 'center',
        },
        {
          colKey: 'txn',
          title: t('TableList.txns'),
          sortType: 'all',
          cell: riseFailLabel2,
          sorter: (a, b) => a.txn - b.txn,
          align: 'center',
        },
      ],
    },
    {
      title: t('TableList.priceChange'),
      align: 'center',
      className: 'custom-before-line',
      children: [
        {
          colKey: 'r5m',
          title: t('TableList.time1'),
          cell: riseFailLabel,
          sortType: 'all',
          sorter: (a, b) => a.r5m - b.r5m,
          align: 'center',
        },
        {
          colKey: 'r1h',
          title: t('TableList.time2'),
          cell: riseFailLabel,
          sortType: 'all',
          sorter: (a, b) => a.r1h - b.r1h,
          align: 'center',
        },
        {
          colKey: 'r4h',
          title: t('TableList.time3'),
          cell: riseFailLabel,
          sortType: 'all',
          sorter: (a, b) => a.r4h - b.r4h,
          align: 'center',
        },
        {
          colKey: 'r24h',
          title: t('TableList.time4'),
          cell: riseFailLabel,
          sortType: 'all',
          sorter: (a, b) => a.r24h - b.r24h,
          align: 'center',
        },
      ],
    },
    {
      title: t('TableList.others'),
      align: 'center',
      className: 'custom-before-line',
      children: [
        {
          colKey: 'operation',
          title: t('TableList.k_line'),
          align: 'center',
        },
        {
          colKey: 'media',
          title: t('TableList.mediaData'),
          align: 'center',
        },
      ],
    },
  ];
});
</script>
<style lang="less">
@import '@/style/variables.less';
@import '@/style/line.less';
.token-list-wrapper-fa {
  margin-top: 8px;
  background: var(--td--right-back-color-2);
  border-radius: @border-radius;
  .token-list-wrapper {
    #table-height-auto {
      .t-table__content {
        background: var(--main-theme-color-2);
      }
      .t-table__affixed-header-elm-wrap {
        .scrollbar {
          overflow: hidden;
        }
      }
      th,
      td {
        padding: 10px 12px;
      }
      tr {
        cursor: pointer;
      }
      thead {
        tr {
          th {
            white-space: nowrap;
            border: none;
            box-sizing: border-box;
          }
        }
        & > :nth-child(1) {
          th {
            color: var(--td--main-btn-color-1);
            font-weight: bold;
            white-space: nowrap;
          }
          .t-align-center {
            height: 30px !important;
            padding: 0;
          }
          & > :nth-child(1) {
            &::before {
              border-left: none;
            }
          }
          & > :last-child {
            &::before {
              border-right: none;
            }
          }
        }
        & > :nth-child(2) {
          th {
            font-size: 14px;
            font-family: fiveFont;
            border-bottom: 1px solid var(--new-border-4);
          }
          & > * {
            position: relative !important;
            box-sizing: border-box;
            &::before {
              content: '';
              width: 200%;
              height: 200%;
              position: absolute;
              border: var(--new-border-2);
              top: 0;
              left: 0;
              transform-origin: 0 0;
              -webkit-transform-origin: 0 0;
              -o-transform-origin: 0 0;
              -ms-transform-origin: 0 0;
              -moz-transform-origin: 0 0;
              transform: scale(0.5);
              -webkit-transform: scale(0.5);
              -o-transform: scale(0.5);
              -ms-transform: scale(0.5);
              -moz-transform: scale(0.5);
            }
          }
          & > :nth-child(1) {
            &::before {
              border-left: none;
            }
          }
          .t-table__double-icons {
            .t-table-sort-asc {
              padding-top: 8px;
              svg {
                fill: #7b7d87;
                opacity: 1;
              }
              &:hover {
                svg {
                  fill: var(--td--main-btn-color-1);
                }
              }
            }
            .t-table-sort-desc {
              padding-bottom: 0px;
              svg {
                fill: #7b7d87;
              }
              &:hover {
                svg {
                  fill: var(--td--main-btn-color-1);
                }
              }
            }
            .t-table__sort-icon--active {
              svg {
                fill: var(--td--main-btn-color-1);
              }
            }
          }
        }
      }
      .t-table__body {
        font-size: var(--font-size-s);
        tr {
          background: var(--td-table-tr-back-color);
          transition: background-color 0s ease-in;
          td {
            border: none;
            border-bottom: 1px solid var(--new-border-3);
          }
        }
        .custom-third-class-name {
          background: var(--td-table-tr-click-back-color);
        }
      }
      .name-block {
        .tn {
          color: var(--main-theme-color);
          font-size: 15px;
          font-weight: bold;
        }
        .symbol {
          color: var(--td-search-btn-back-1);
          margin-top: 2px;
          font-size: 13px;
        }
      }
      .up {
        color: #23ab94;
      }
      .down {
        color: #f85260;
      }
      .custom-r-time-td {
        font-weight: 600;
        font-size: 13px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .custom-Indicators-td {
        font-size: 14px;
      }
    }
    .page-footer {
      padding: 0 24px;
    }
  }
}
</style>
