| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- import { ref, computed, watch } from 'vue'
- //import { timerInterceptor } from '@/utils/timer'
- import { queryTSData } from '@/services/api/quote'
- import { getQuoteDayInfoByCode } from '@/business/common'
- import { useDataset } from './dataset'
- import { useOptions } from './options'
- import moment from 'moment';
- export function useTimelineChart(goodscode: string) {
- const { dataset, handleData, clearData, calcIndicator } = useDataset();
- const { options, initOptions, updateOptions } = useOptions(dataset);
- const loading = ref(false);
- const isEmpty = ref(false);
- const dataIndex = ref(-1); // 当前数据索引值
- const quote = getQuoteDayInfoByCode(goodscode); // 实时行情
- // 当前选中的数据项
- const selectedItem = computed(() => {
- const { close, ma5 } = dataset.timeline.source;
- return {
- close: close[dataIndex.value] ?? '--',
- ma5: ma5[dataIndex.value] ?? '--'
- }
- })
- /**
- * 初始化数据
- */
- const initData = () => {
- clearData();
- dataIndex.value = -1;
- isEmpty.value = true;
- loading.value = true;
- // 获取历史行情
- queryTSData({
- data: {
- goodscode
- },
- success: (res) => {
- const { historyDatas } = res.data;
- if (historyDatas.length) {
- dataIndex.value = historyDatas.length - 1;
- isEmpty.value = false;
- handleData(res.data);
- }
- },
- complete: () => {
- loading.value = false;
- }
- })
- }
- /**
- * 更新图表数据
- */
- const updateChart = () => {
- if (quote.value) {
- const { last, lasttime } = quote.value;
- const { close, ma5 } = dataset.timeline.source;
- const lastIndex = close.length - 1; // 历史数据最后索引位置
- const cycleMilliseconds = 60 * 1000; // 一分钟毫秒数
- const oldTime = lastIndex === -1 ? moment(lasttime) : moment(dataset.rawDate[lastIndex]); // 历史行情最后时间
- const diffTime = moment(lasttime).valueOf() - oldTime.valueOf(); // 计算时间差
- if (diffTime > cycleMilliseconds * 2) {
- // 时间间隔超过两个周期,重新请求历史数据
- //timerInterceptor.debounce(() => initData(), 1000, 'updateChart');
- } else {
- // 判断时间差是否大于周期时间
- if (lastIndex === -1 || diffTime > cycleMilliseconds) {
- oldTime.add(cycleMilliseconds, 'ms');
- const lastDate = oldTime.format('YYYY-MM-DD HH:mm:ss');
- // 新增分时数据
- dataset.rawDate.push(lastDate);
- close.push(last);
- ma5.push('-')
- } else {
- close[lastIndex] = last; // 更新最后一条记录的收盘价
- }
- // 更新各种指标
- calcIndicator(lastIndex === -1 ? 0 : lastIndex);
- updateOptions();
- }
- }
- }
- // 监听行情推送
- watch(() => quote.value?.last, () => {
- if (!loading.value && !isEmpty.value) {
- updateChart();
- }
- })
- initData();
- return {
- loading,
- isEmpty,
- dataIndex,
- options,
- selectedItem,
- initData,
- initOptions,
- }
- }
|