import { ref, computed, watch } from 'vue'
//import { timerInterceptor } from '@/utils/timer'
import { queryTSData } from '@/services/api/quote'
import { useFuturesStore } from '@/stores'
import { useDataset } from './dataset'
import { useOptions } from './options'
import moment from 'moment';

export function useTimelineChart(goodscode: string) {
    const { getQuoteDayInfoByCode } = useFuturesStore()
    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,
    }
}