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

<script lang="ts" setup>
import { ref, reactive, watch, computed } from 'vue'
import { useDataset } from './dataset'
import { useOptions } from './options'
import { queryHistoryDatas } from '@/services/api/quote'
import moment from 'moment';
import AppEcharts from '@/components/base/echarts/index.vue'

const props = defineProps({
  goodsCode: String,
})

const loading = ref(false),
  showEmpty = ref(false),
  dataIndex = ref(0); // 当前数据索引值

const { state, handleData, calcIndicator } = useDataset();
const { timeOption, initOptions } = useOptions(state);

const timeDetail = computed(() => {
  const { close, ma5 } = state.dataset.source;
  return {
    close: close[dataIndex.value],
    ma5: ma5[dataIndex.value],
  }
});

// 模拟最新价推送
const quote = reactive({
  last: 0,
  lasttime: new Date(),
});

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

  // 获取历史行情
  queryHistoryDatas({
    data: {
      goodscode: props.goodsCode
    },
    success: (res) => {
      const data = res.data;
      if (data.length) {
        dataIndex.value = data.length - 1;
        handleData(data, () => initOptions(updateChartData));
      } else {
        showEmpty.value = true;
      }
    },
    complete: () => {
      loading.value = false;
    }
  })
}

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

  const oldTime = lastIndex === -1 ? newTime : moment(date[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');

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

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

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

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