<template>
  <div
    ref="historyList"
    class="history-list-wrapper narrow-scrollbar"
    id="history-list-wrapper"
  >
    <div class="history-btns">
      <div class="left">
        <t-radio-group
          v-model="groupbtn"
          class="custom-group2"
          :options="groupList"
          @change="groupbtnChange"
        >
          <t-radio-button
            v-for="item of groupList"
            :key="item.value"
            :value="item.value"
            >{{ item.label }}</t-radio-button
          >
        </t-radio-group>
      </div>
      <div class="right-reset">
        <t-button @click="resetClick">
          <template #icon>
            <ResetSvg class="icon"></ResetSvg>
          </template>
          {{ $t('Customized.reset') }}</t-button
        >
      </div>
    </div>
    <t-table
      row-key="index"
      hover
      id="history-table-body"
      :data="resultData.list"
      table-layout="auto"
      :columns="columns"
      :defaultDisplayColumns="MydisplayColumns.list"
      :column-controller="{}"
      :rowClassName="getRowClasss"
      :asyncLoading="loadingNode"
      :loading="loading"
      :header-affixed-top="tablesticky"
      :scroll="{
        type: '',
        bufferSize: 10,
      }"
      @filter-change="onFilterChange"
      v-show="groupbtn === 'table'"
    >
      <template #st="{ row }">
        <span>{{
          row.st == 'buy' ? $t('TableList.hisBuy') : $t('TableList.hisSell')
        }}</span>
      </template>
      <template #nh="{ row }">
        <span>{{
          row.nh == 1 ? $t('securityCheck.yes') : $t('securityCheck.no')
        }}</span>
      </template>
      <template #h100="{ row }">
        <span>{{
          row.h100 == 1 ? $t('securityCheck.yes') : $t('securityCheck.no')
        }}</span>
      </template>
      <template #txn="{ row }">
        <a class="jump-txn" href="javascript:;" @click="goTxn(row)">
          {{ row.hash.substr(0, 6) }}
        </a>
      </template>
    </t-table>
    <div v-show="groupbtn !== 'table'" class="Customized">
      <div class="custom-content">
        <div class="title">{{ $t('TableList.customtitle') }}</div>
        <t-button @click="JoinUs(tgUrl)">{{
          $t('Customized.Contact')
        }}</t-button>
      </div>
    </div>
    <historyListFilter
      v-model:visible="dialogvisible"
      @update:visible="closeDialog"
      :option="dialogTitle"
    ></historyListFilter>
  </div>
</template>
<script setup lang="tsx">
import {
  parseCoinAmount,
  parsePercent,
  filtercriteria,
  filterIncludeValue,
  filterRepeatTimestamp,
} from '@/utils/tool';
import request from '@/utils/request';
import dayjs from 'dayjs';
import { useI18n } from 'vue-i18n';
import { tgUrl } from '@/utils/open';
import ResetSvg from '/public/images/svg/filter/reset.svg';
import FilterSvg from '/public/images/svg/filter/filter.svg';
import FilterBuyAndSellSVG from '/public/images/svg/filter/filterBuyAndSell.svg';
import historyListFilter from './historyListFilter.vue';
import { filterChainObj } from '@/constants/UnifiedManagementChain';
const i18n = useI18n();
let interval = null;
const tokenVisible = ref(false);
const baseTokenVisible = ref(false);
// 是否首次加载表格
const hasOneTable = ref(false);
const resultData = reactive({
  // 表格数据
  list: [],
  // 筛选结果
  filterlist: [],
  // 所有数据
  allList: [],
  /**
   * 当前展示的数据是筛选数据还是全部数据--true为全部数据，false为筛选数据
   * 用于判断是否需要异步加载
   * 默认全部数据-true
   */
  status: true,
  type: '', // 交易类型  -- sell or buy
  newHolder: '', //新增持有人--yes or no
  top100Holder: '', //前一百持有人 -- yes or no
});
// 表格加载状态
const loading = ref(false);
// 对话框状态
const dialogvisible = ref(false);
// 对话框标题
const dialogTitle = ref({});
// 滚动元素
let historyList = ref(null);
// 当前选中的按钮
const groupbtn = ref('table');
// 按钮组
const groupList = computed(() => [
  {
    label: i18n.t('TableList.TradingHistory'),
    value: 'table',
  },
  {
    label: i18n.t('TableList.LargeOrderTracking'),
    value: 'order',
  },
  {
    label: i18n.t('TableList.PriceAlert'),
    value: 'alert',
  },
]);
const JoinUs = (url: string) => {
  window.open(url);
};

// 表格表头吸顶
const tablesticky = ref(null);

const asyncLoading = ref('');
const props = defineProps({
  currentPath: String,
  tb: String,
  PoolAddress: String,
  token: String,
  mt: String,
});
// 自增赋值给key
let thisIndex = 1;
const groupbtnChange = (value: string) => {
  if (value == 'order') {
  }
};
watch(
  () => props.PoolAddress,
  (v) => {
    if (v) {
      // 先注销上个定时器
      clearInterval(interval);
      resultData.list = [];
      asyncLoading.value = '';
      getHistoryList('fetch');
      handleScrollEvent();
    }
  }
);
watch(
  () => props.mt,
  (v) => {
    if (v) {
      // 挂载前判断是否是主流币，如果是主流币，将交易历史表格中的部分字段隐藏
      if (!hasOneTable.value && props.mt == '2') {
        // 隐藏列
        let h100 = MydisplayColumns.list.findIndex(
          (item: any) => item === 'h100'
        );
        let sr = MydisplayColumns.list.findIndex((item: any) => item === 'sr');
        let nh = MydisplayColumns.list.findIndex((item: any) => item === 'nh');
        if (h100 !== -1 && sr !== -1 && nh !== -1) {
          MydisplayColumns.list.splice(h100, 1);
          MydisplayColumns.list.splice(sr, 1);
          MydisplayColumns.list.splice(nh, 1);
        }
        hasOneTable.value = true;
      }
      getHistoryList('fetch');
      handleScrollEvent();
      interval = setInterval(getHistoryList, 10000);
    }
  }
);
const monitor = (e: any) => {
  let isExist = e.target.visibilityState;
  if (isExist === 'visible') {
    // 先关再开
    if (interval) {
      clearInterval(interval);
    }
    // 开启前立即请求一次
    getHistoryList();
    interval = setInterval(getHistoryList, 10000);
  } else {
    // 离开页面
    if (interval) {
      clearInterval(interval);
    }
  }
};
// 滚动事件
const ScrollClick = () => {
  let fiexdHeader: any = document.querySelector(
    '.t-table__affixed-header-elm-wrap'
  );
  if (fiexdHeader.style.display !== 'block') {
    fiexdHeader.style.display = 'block';
  } else {
    return;
  }
};

onMounted(() => {
  // 注册滚动监听,滚动时重新显示吸顶表头
  historyList.value.addEventListener('scroll', ScrollClick);

  // 监听是否切除页面
  document.addEventListener('visibilitychange', monitor);

  // 开启表格吸顶
  tablesticky.value = {
    offsetTop: 63,
    zIndex: 1,
    container: '#history-list-wrapper',
  };
});

onBeforeUnmount(() => {
  clearInterval(interval);
});
onUnmounted(() => {
  // 注销滚动监听
  if (historyList.value) {
    historyList.value.removeEventListener('scroll', ScrollClick, false);
  }
  document.removeEventListener('visibilitychange', monitor);
});
// 当前展示的列
const MydisplayColumns = reactive({
  list: [
    'tsStr',
    'st',
    'tokenNumStr',
    'vnStr',
    'upStr',
    'nh',
    'sr',
    'h100',
    'txn',
  ],
});
const handleScrollEvent = () => {
  let dom = document.getElementById('history-list-wrapper');
  dom.onscroll = (e) => {
    if (asyncLoading.value === 'loading' || asyncLoading.value === 'end') {
      return;
    }
    if (
      Math.abs(dom.scrollHeight - dom.clientHeight - dom.scrollTop) < 100 &&
      resultData.status
    ) {
      getHistoryList('fetch');
    }
  };
};
const loadingNode = (h) => {
  if (asyncLoading.value === 'end' || asyncLoading.value === 'stop') {
    return (
      <div class="asyncLoadingTitle">
        {i18n.t('TableList.emptyhistorylist')}
      </div>
    );
  } else if (asyncLoading.value === 'maxLength') {
    return (
      <div class="asyncLoadingTitle">{i18n.t('TableList.maxFilterlength')}</div>
    );
  } else if (asyncLoading.value === 'nolist') {
    return (
      <div class="asyncLoadingTitle">{i18n.t('TableList.emptyfilterdata')}</div>
    );
  } else {
    return (
      <div style="color:var(--td--main-btn-color-1)">
        <t-loading size="small" text="正在加载中，请稍后..."></t-loading>
      </div>
    );
  }
};
// 历史数据筛选sell,buy
const filterHistoryList = (label: string) => {
  // 交易类型
  if (label == 'type') {
    let buy = 'buy',
      sell = 'sell';
    if (resultData.type == '') {
      resultData.filterlist = filterIncludeValue('st', buy, resultData.allList);
      resultData.type = buy;
    } else if (resultData.type == buy) {
      resultData.filterlist = filterIncludeValue(
        'st',
        sell,
        resultData.allList
      );
      resultData.type = sell;
    } else if (resultData.type == sell) {
      resultData.filterlist = filterIncludeValue('st', buy, resultData.allList);
      resultData.type = buy;
    }
  } else if (label == 'nh') {
    if (resultData.newHolder == '') {
      // 查不是新增持有人的
      resultData.filterlist = filterIncludeValue('nh', 0, resultData.allList);
      resultData.newHolder = 'no';
    } else if (resultData.newHolder == 'no') {
      resultData.filterlist = filterIncludeValue('nh', 1, resultData.allList);
      resultData.newHolder = 'yes';
    } else if (resultData.newHolder == 'yes') {
      resultData.filterlist = filterIncludeValue('nh', 0, resultData.allList);
      resultData.newHolder = 'no';
    }
  } else if (label == 'top100') {
    if (resultData.top100Holder == '') {
      // 查不是新增持有人的
      resultData.filterlist = filterIncludeValue('h100', 0, resultData.allList);
      resultData.top100Holder = 'no';
    } else if (resultData.top100Holder == 'no') {
      resultData.filterlist = filterIncludeValue('h100', 1, resultData.allList);
      resultData.top100Holder = 'yes';
    } else if (resultData.top100Holder == 'yes') {
      resultData.filterlist = filterIncludeValue('h100', 0, resultData.allList);
      resultData.top100Holder = 'no';
    }
  }
  // 改变异步加载模式
  resultData.status = false;
  if (resultData.filterlist.length) {
    asyncLoading.value = 'stop';
  } else {
    asyncLoading.value = 'nolist';
  }
  resultData.list = resultData.filterlist;
};

const getHistoryList = async (type = 'update') => {
  try {
    let params: any = {
      tag: props.PoolAddress ? props.PoolAddress : props.tb,
      mainstream: props.mt,
    };
    // 定时刷新数据
    if (type === 'update') {
      params.t = resultData.allList[0].ts;
    } else {
      // 加载更多
      if (resultData.allList.length !== 0) {
        params.tb = resultData.allList[resultData.allList.length - 1].ts;
      }
      if (asyncLoading.value === 'end' || asyncLoading.value === 'loading') {
        return;
      }
      asyncLoading.value = 'loading';
    }
    // 请求
    let result: any = await request.get(
      `/v1/${props.currentPath}/getBelowInfo`,
      {
        params,
      }
    );
    if (result === null || result === 'null') {
      return;
    }
    // 过滤出重复数据
    if (resultData.allList.length && result.length) {
      // 全部数据里面必须要有值，才合并去重
      result = filterRepeatTimestamp(resultData.allList, result);
    }
    result.forEach((item, index) => {
      // sr保留一个旧值
      if (item.sr) {
        item.oldsr = item.sr;
        item.sr = parsePercent(parseFloat(item.sr).toFixed(3));
      }
      thisIndex += 1;
      item.index = thisIndex;
      item.upStr = '$' + parseCoinAmount(item.up);
      item.tsStr = dayjs(item.ts).format('MM-DD HH:mm:ss');
      // 筛选字段需要保留原始数据格式
      item.tokenNumStr = parseCoinAmount(
        item.st === 'sell' ? item.sn : item.bn
      );
      item.oldtokenNumStr = item.st === 'sell' ? item.sn : item.bn;
      //
      item.vnStr = '$' + parseCoinAmount(item.vn);
      item.vn = item.vn;
    });
    // 定时刷新数据
    if (type === 'update') {
      resultData.allList = result.concat(resultData.allList);
      if (resultData.status) {
        resultData.list = resultData.allList;
      }

      // 大于100，则继续拉取最新数据
      if (result.length === 100) {
        getHistoryList('update');
      }
    } else {
      asyncLoading.value = result.length < 100 ? 'end' : 'load-more';
      resultData.allList = resultData.allList.concat(result);
      if (resultData.status) {
        resultData.list = resultData.allList;
      }
    }
  } catch (e) {}
};
// 重置筛选
const resetClick = () => {
  resultData.list = resultData.allList;
  resultData.status = true;
  asyncLoading.value = 'load-more';
};
const filterObj = reactive({
  type: '',
  tokenNum: { min: '', max: '' },
  baseTokenNum: { min: '', max: '' },
});

const togglePopup = (v) => {
  if (v === 'token') {
    tokenVisible.value = !tokenVisible.value;
  } else {
    baseTokenVisible.value = !baseTokenVisible.value;
  }
};
const onFilterChange = (v, context) => {
  console.log(v, context);
};
const goTxn = (item) => {
  let Obj = filterChainObj('value', props.currentPath);
  if (Obj) {
    window.open(`${Obj.url.website.hashLink}${item.hash}`);
  }
};
const getRowClasss = ({ row }) => {
  return row.st;
};
// 打开筛选框
const openfilterDialog = (label: any) => {
  dialogTitle.value = label;
  dialogvisible.value = true;
};
// 关闭弹窗
const closeDialog = ({ visible, value }) => {
  dialogvisible.value = visible;
  // 判断是否需要筛选
  if (value.type == 'filter-self') {
    // loading.value = true;
    // filter--value是筛选条件对象
    resultData.filterlist = filtercriteria(value, resultData.allList);
    resultData.status = false;
    if (resultData.filterlist.length) {
      asyncLoading.value = 'stop';
    } else {
      asyncLoading.value = 'nolist';
    }
    // 再赋值给表格数据
    resultData.list = resultData.filterlist;
  } else if (value.type == 'filter-time') {
    // 请求后台数据
    getfilterTimeList(value);
  }
};
// 提交筛选条件
const getfilterTimeList = async (value: any) => {
  try {
    loading.value = true;
    let params: any = {
      tag: props.PoolAddress ? props.PoolAddress : props.tb,
      mainstream: props.mt,
      from: value.from,
      to: value.to,
    };
    // 请求
    let result: any = await request.get(
      `/v1/${props.currentPath}/getBelowInfo`,
      {
        params,
      }
    );
    if (result === null || result === 'null') {
      return;
    }
    // 阻止异步加载
    resultData.status = false;
    if (result.length) {
      result.forEach((item, index) => {
        // sr保留一个旧值
        if (item.sr) {
          item.oldsr = item.sr;
          item.sr = parsePercent(parseFloat(item.sr).toFixed(3));
        }
        thisIndex += 1;
        item.index = thisIndex;
        item.upStr = '$' + parseCoinAmount(item.up);
        item.tsStr = dayjs(item.ts).format('MM-DD HH:mm:ss');
        // 筛选字段需要保留原始数据格式
        item.tokenNumStr = parseCoinAmount(
          item.st === 'sell' ? item.sn : item.bn
        );
        item.oldtokenNumStr = item.st === 'sell' ? item.sn : item.bn;
        //
        item.vnStr = '$' + parseCoinAmount(item.vn);
        item.vn = item.vn;
      });
      // 有数据
      if (result.length == 200) {
        asyncLoading.value = 'maxLength';
      } else {
        asyncLoading.value = 'stop';
      }
    } else {
      // 空数据
      asyncLoading.value = 'nolist';
    }
    loading.value = false;
    resultData.list = result;
  } catch (e) {}
};

const columns = computed(() => [
  {
    colKey: 'tsStr',
    title: (h, { colIndex }) => (
      <div class="filter-header filter-time">
        <span>{i18n.t('TableList.date')}</span>
        <span
          class="icon"
          onClick={openfilterDialog.bind(this, {
            title: i18n.t('TableList.date'),
            value: 'ts',
          })}
        >
          <FilterSvg></FilterSvg>
        </span>
      </div>
    ),
  },
  {
    colKey: 'st',
    title: (h, { colIndex }) => (
      <div class="filter-header">
        <span class="name">{i18n.t('TableList.type')}</span>
        <span class="icon" onClick={filterHistoryList.bind(this, 'type')}>
          <FilterBuyAndSellSVG></FilterBuyAndSellSVG>
        </span>
      </div>
    ),
    align: 'center',
  },
  {
    colKey: 'tokenNumStr',
    title: (h, { colIndex }) => (
      <div class="filter-header">
        <span class="name">{i18n.t('TableList.amountToken')}</span>
        <span
          class="icon"
          onClick={openfilterDialog.bind(this, {
            title: i18n.t('TableList.amountToken'),
            value: 'oldtokenNumStr',
          })}
        >
          <FilterSvg></FilterSvg>
        </span>
      </div>
    ),
    align: 'center',
  },
  {
    colKey: 'vnStr',
    title: (h, { colIndex }) => (
      <div class="filter-header">
        <span class="name">{i18n.t('TableList.AmountUSD')}</span>
        <span
          class="icon"
          onClick={openfilterDialog.bind(this, {
            title: i18n.t('TableList.AmountUSD'),
            value: 'vn',
          })}
        >
          <FilterSvg></FilterSvg>
        </span>
      </div>
    ),
    align: 'center',
  },
  {
    colKey: 'upStr',
    title: (h, { colIndex }) => (
      <div class="filter-header">
        <span class="name">{i18n.t('TableList.hisPrice')}</span>
        <span
          class="icon"
          onClick={openfilterDialog.bind(this, {
            title: i18n.t('TableList.hisPrice'),
            value: 'up',
          })}
        >
          <FilterSvg></FilterSvg>
        </span>
      </div>
    ),
    align: 'center',
  },
  {
    colKey: 'nh',
    title: (h, { colIndex }) => (
      <div class="filter-header">
        <span class="name">{i18n.t('TableList.NewHolder')}</span>
        <span class="icon" onClick={filterHistoryList.bind(this, 'nh')}>
          <FilterBuyAndSellSVG></FilterBuyAndSellSVG>
        </span>
      </div>
    ),
    align: 'center',
  },
  {
    colKey: 'sr',
    // title: i18n.t('TableList.SellRatio'),
    title: (h, { colIndex }) => (
      <div class="filter-header">
        <span class="name">{i18n.t('TableList.SellRatio')}</span>
        <span
          class="icon"
          onClick={openfilterDialog.bind(this, {
            title: i18n.t('TableList.SellRatio'),
            value: 'oldsr',
          })}
        >
          <FilterSvg></FilterSvg>
        </span>
      </div>
    ),
    align: 'center',
  },
  {
    colKey: 'h100',
    title: (h, { colIndex }) => (
      <div class="filter-header">
        <span class="name">{i18n.t('TableList.top100Holders')}</span>
        <span class="icon" onClick={filterHistoryList.bind(this, 'top100')}>
          <FilterBuyAndSellSVG></FilterBuyAndSellSVG>
        </span>
      </div>
    ),
    align: 'center',
  },
  {
    colKey: 'txn',
    title: i18n.t('TableList.hisTxn'),
    align: 'center',
  },
]);
</script>
<style lang="less" scoped>
@import '@/style/flex.less';
@import '@/style/variables.less';
.history-list-wrapper {
  width: 100%;
  height: 100%;
  overflow-y: scroll;
  :deep .t-table {
    white-space: nowrap;
    .asyncLoadingTitle {
      color: var(--td--main-btn-color-1);
      font-size: 16px;
      font-weight: bold;
    }
    th,
    td {
      padding: 10px 12px;
    }
    .filter-header {
      .dja();
      .name {
        margin-right: 4px;
      }
      .icon {
        cursor: pointer;
        .dja();
      }
    }
    .filter-time {
      justify-content: flex-start;
      .icon {
        margin-left: 4px;
      }
    }
    .sell td:nth-child(n + 2) {
      color: #f85260;
    }
    .buy td:nth-child(n + 2) {
      color: #23ab94;
    }
    tr.t-table__first-full-row {
      display: none !important;
    }
    .t-table__body {
      font-size: 12px;
    }
    .jump-txn {
      color: var(--td-brand-color);
      padding-left: 0;
    }
    .t-table__body {
      tr {
        transition: none !important;
      }
    }
  }
  // 按钮组
  .history-btns {
    width: 100%;
    height: 60px;
    .dja(space-between);
    position: sticky;
    top: 3px;
    z-index: 80;
    background: var(--td-table-tr-back-color);
    .left {
      margin-left: 12px;
      background: var(--history-list-reset-btn-back);
      border: 1px solid var(--td--table-icon-color-1);
      border-radius: 6px;
      padding: 4px 6px;
      .t-radio-button {
        border: none;
      }
      .t-is-checked {
        background: var(--themeColor);
        border-radius: 6px;
        color: white;
      }
    }
    .right-reset {
      margin-right: 6px;
      .t-button {
        border: 1px solid var(--td--table-icon-color-1);
        background: var(--history-list-reset-btn-back);
        color: var(--td-Search-info-color-1);
        .icon {
          margin-right: 6px;
          fill: var(--td-Search-info-color-1);
        }
      }
    }
  }
  // 定制
  .Customized {
    width: 100%;
    height: calc(100% - 60px);
    position: relative;
    .custom-content {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      height: 100px;
      .dja(space-around);
      flex-direction: column;
      .title {
        font-weight: bold;
        white-space: nowrap;
        font-size: @font-size-xl;
      }
      .t-button {
        width: 120px;
      }
    }
  }
}
</style>
