<template>
  <div class="">
    <ClientOnly>
      <MyLayout>
        <template #content>
          <div class="token-detail-wrapper">
            <div class="left-wrapper">
              <div id="tv_chart_container" ref="chartContainer"></div>
              <div
                class="history-table narrow-scrollbar"
                :style="{ height: tableHeight }"
                id="history-table"
              >
                <div class="resize-block" id="resize-block">
                  <div class="resize-icon">
                    <arrow-up-icon></arrow-up-icon>
                    <div class="line"></div>
                    <arrow-down-icon></arrow-down-icon>
                  </div>
                </div>
                <HistoryList
                  :mt="mt"
                  :currentPath="currentPath"
                  :tb="tb"
                  :PoolAddress="PoolAddress"
                ></HistoryList>
              </div>
            </div>
            <div class="right-wrapper">
              <RightDetail
                :mt="mt"
                scene="detail"
                :token="token"
                :tb="tb"
                :r24h="r24h"
                :currentPath="currentPath"
                @update:setPool="getPoll"
              ></RightDetail>
            </div>
            <FixedJoinUs></FixedJoinUs>
            <Announcement></Announcement>
          </div>
        </template>
      </MyLayout>
    </ClientOnly>
  </div>
</template>

<script setup lang="ts">
import MyLayout from '@/views/layout/layout.vue';
import HistoryList from '@/views/token/HistoryList.vue';
import RightDetail from '@/views/token/RightDetail.vue';
import { ArrowUpIcon, ArrowDownIcon } from 'tdesign-icons-vue-next';
import { DataFeed, Widget } from '@/utils/tradingview';
import request from '@/utils/request';
import { WebS } from '@/utils/TokenTrans';
import { filterChainObj } from '@/constants/UnifiedManagementChain';
import { webLogo } from '@/constants/logo';
const route = useRoute();
const tb = ref(route.params.tb + '');
const chain = useChain();
const chartContainer = ref(null);
useHead({
  title: `Dexfilter | ${tb.value}`,
  script: [
    {
      src: '/charting_library/charting_library.standalone.js',
    },
  ],
  link: [webLogo],
  meta: [
    {
      name: 'description',
      content: `Dexfilter-${tb.value}-实时的K线平台`,
    },
  ],
});

// 当前主题
const mode = useCurTheme();
const currentPath = ref(route.params.chain + '');
// 先取出对应链的接口id
let Obj = filterChainObj('name', currentPath.value.toUpperCase());
currentPath.value = Obj.value;
const CurrentKPrice = useCurrentKLinePrice();
// token---接口得到
const token = ref('');
// symbol--接口
const symbol = ref('');
// r24h--接口
const r24h = ref('');
// k线价格精度
const KPirce = ref();
// mt---是否主流币
const mt = ref('');
const PoolAddress = ref('');
let datafeed = null;
let widget: any = null;
onBeforeMount(() => {
  if (currentPath.value) {
    chain.value = currentPath.value;
  }
  request
    .get(`/v1/${currentPath.value}/getConfig`, {
      params: {
        tag: WebS(tb.value),
      },
    })
    .then((res: any) => {
      // 当url为token时
      if (res.is_token) {
        tb.value = res.pair;
      }
      CurrentKPrice.value = res.up;
      //
      r24h.value = res.r24h + '';
      symbol.value = res.sy;
      token.value = res.token;
      KPirce.value = res.up;
      mt.value = res.p + '';
    });
});
watch(
  () => PoolAddress.value,
  (v) => {
    if (v) {
      datafeed.clearIntervalGetBars();
      datafeed = null;
      getKLine(v);
    }
  }
);
watch(
  () => mode.value,
  (v) => {
    let mode = '';
    if (v === 'light') {
      mode = 'Light';
    } else {
      mode = 'Dark';
    }
    widget.widget.onChartReady(function () {
      widget.widget.changeTheme(mode);
    });
  }
);
let Interval = null;
// 轮询获取k线是否加载
const openInterval = () => {
  Interval = setInterval(() => {
    try {
      if (widget?.widget?.onChartReady) {
        widget.widget.onChartReady(function () {
          widget.widget.changeTheme(mode.value == 'light' ? 'Light' : 'Dark');
        });
        clearInterval(Interval);
      }
    } catch (e) {
      clearInterval(Interval);
    }
  }, 100);
};
const drag = () => {
  let oBox = document.getElementById('resize-block');
  let historyTable = document.getElementById('history-table');
  oBox.onmousedown = function (ev) {
    var iEvent = ev as MouseEvent;
    var startY = iEvent.clientY; //当你第一次单击的时候，储存Y轴的坐标。
    var boxH = historyTable.offsetHeight; //存储默认的div的高度。
    // 获取表格固钉--当拖动时，隐藏固钉
    let Histab: any = document.querySelector(
      '.t-table__affixed-header-elm-wrap'
    );
    document.getElementById('tv_chart_container').setAttribute('class', 'mask');
    document.onmousemove = function (ev) {
      var iEvent = ev as MouseEvent;
      historyTable.style.height = boxH - (iEvent.clientY - startY) + 'px';
      Histab.style.display = 'none';
    };
    document.onmouseup = function () {
      document.onmousedown = null;
      document.onmousemove = null;
      document.getElementById('tv_chart_container').setAttribute('class', '');
    };
    return false;
  };
};
const tableHeight = ref('100px');
watch(
  () => KPirce.value,
  (v) => {
    if (v) {
      getKLine(tb.value);
    }
  }
);
onMounted(() => {
  // 开启k线轮询
  openInterval();
  tableHeight.value = Math.floor((window.innerHeight - 64) * 0.4) + 'px';
  nextTick(() => {
    drag();
  });
});

onBeforeUnmount(() => {
  if (Interval) {
    clearInterval(Interval);
  }
});
const getKLine = (tb) => {
  if (!symbol.value) {
    symbol.value = 'any';
  }
  let symbolName = (symbol.value + '').toLocaleUpperCase();
  datafeed = new DataFeed(
    {
      name: symbol.value,
      ticker: tb,
      description: symbolName,
      KPirce: KPirce.value,
      currentPath: currentPath.value,
    },
    10000
  );
  widget = new Widget({
    datafeed,
    symbol: symbolName,
  });
};
const getPoll = (PoolValue) => {
  PoolAddress.value = PoolValue;
};
</script>

<style lang="less" scoped>
@import '@/style/flex.less';
.token-detail-wrapper {
  box-sizing: border-box;
  padding: 6px 0 0 6px;
  position: relative;
  height: calc(100vh - 70px);
  overflow: hidden;
  display: flex;
  .left-wrapper {
    width: calc(100vw - 380px);
    height: 100%;
    display: flex;
    flex-direction: column;
    margin-right: 12px;
    #tv_chart_container {
      flex: 1;
      min-height: 200px;
      position: relative;
      // height: calc((100vh - 70px) * 0.4);
      &.mask {
        &:after {
          content: ' ';
          position: absolute;
          width: 100%;
          height: 100%;
          top: 0;
          left: 0;
          z-index: 2;
        }
      }
    }
    .history-table {
      z-index: 10;
      min-height: 90px;
      position: relative;
      background-color: var(--td-bg-color-container);
      display: flex;
      height: calc(33vh + 23px) !important;
      .resize-block {
        position: absolute;
        user-select: none;
        width: 100%;
        height: 15px;
        top: -15px;
        left: 0px;
        z-index: 90;
        cursor: row-resize;
        .resize-icon {
          width: 100%;
          position: relative;
          top: 0px;
          text-align: center;
          flex-direction: column;
          .da();
          .t-icon {
            color: var(--td-brand-color-6);
            z-index: 200;
          }
          .line {
            width: 100%;
            height: 4px;
            background-color: var(--td-brand-color-6);
          }
        }
      }
    }
  }
  .right-wrapper {
    flex: 1;
    position: sticky;
    top: 0;
    border-left: 1px solid var(--td-component-border);
  }
}
</style>
