<template>
  <div class="mtp-echats-timeline">
    <ul class="legend">
      <li class="legend-item">收: {{timeDetail && timeDetail.close}}</li>
      <li class="legend-item">MA5: {{timeDetail && timeDetail.ma5}}</li>
    </ul>
    <mtp-echarts :option="timeOption" :empty="showEmpty" v-model:index="dataIndex" v-model:loading="loading" @ready="initData" />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch, computed } from 'vue'
import { QueryQuoteDayRsp } from '@/services/go/quote/interface';
import { QueryTSData } from '@/services/go/quote';
import { getQuoteDayInfoByCode } from '@/services/bus/goods';
import { useDataset } from './dataset'
import { useOptions } from './options'
import moment from 'moment';
import MtpEcharts from '../../echarts/echarts-base/index.vue'

export default defineComponent({
  emits: ['ready'],
  components: {
    MtpEcharts,
  },
  props: {
    goodscode: {
      type: String,
      default: '',
    },
  },
  setup(props, { emit }) {
    const loading = ref(false),
      showEmpty = ref(false),
      dataIndex = ref(0), // 当前数据索引值
      quote = ref<QueryQuoteDayRsp>(getQuoteDayInfoByCode(props.goodscode)!); // 商品实时行情

    const { state, handleData, calcIndicator } = useDataset();
    const { timeOption, initOptions, updateOptions } = useOptions(state);
    const timeDetail = computed(() => {
      const { close, ma5 } = state.dataset.source;
      return {
        close: close[dataIndex.value] ?? '--',
        ma5: ma5[dataIndex.value] ?? '--',
      }
    });

    // 初始化数据
    const initData = () => {
      showEmpty.value = false;
      loading.value = true;
      state.dataset.source = {
        date: [],
        close: [],
        ma5: []
      }

      // 查询历史数据
      QueryTSData(props.goodscode).then((res) => {
        if (res.historyDatas.length) {
          dataIndex.value = res.historyDatas.length - 1;
          handleData(res, () => initOptions(updateChartData));
        } else {
          showEmpty.value = true;
        }

        // 调用父级函数查询tik数据 (不合理的逻辑处理，待优化)
        emit('ready', res.startTime, res.endTime);
      }).catch((err) => {
        console.error(err);
        showEmpty.value = true;
      }).finally(() => {
        loading.value = false;
      });
    }

    // 更新图表数据
    const updateChartData = () => {
      const { close, ma5 } = state.dataset.source,
        lastIndex = close.length - 1, // 历史行情最后索引位置
        cycleMilliseconds = 60 * 1000, // 一分钟毫秒数
        newTime = moment(quote.value.lasttime), // 实时行情最新时间
        newPrice = quote.value.last; // 实时行情最新价

      const oldTime = lastIndex === -1 ? newTime : moment(state.rawDate[lastIndex]); // 历史行情最后时间
      const diffTime = newTime.valueOf() - oldTime.valueOf(); // 计算时间差

      if (diffTime > cycleMilliseconds * 2) {
        // 时间间隔超过两个周期，重新请求历史数据
      } else {
        // 判断时间差是否大于周期时间
        if (lastIndex === -1 || diffTime > cycleMilliseconds) {
          oldTime.add(cycleMilliseconds, 'ms');
          const newDate = oldTime.format('YYYY-MM-DD HH:mm:ss');

          // 新增分时数据
          state.rawDate.push(newDate);
          close.push(newPrice);
          ma5.push('-')
        } else {
          close[lastIndex] = newPrice; // 更新最后一条记录的收盘价
        }

        // 更新各种指标
        calcIndicator(lastIndex === -1 ? 0 : lastIndex);
        updateOptions();
      }
    }

    // 监听行情推送
    watch(() => quote.value.last, () => {
      if (!loading.value) {
        updateChartData();
      }
    })

    return {
      loading,
      showEmpty,
      dataIndex,
      timeOption,
      timeDetail,
      initData,
    }
  }
})
</script>

<style lang="less">
@import './index.less';
</style>