import { ref, computed, watch } from 'vue'
import { futuresStore } from '@/stores'
import { formatDate } from '@/filters'
import { queryHistoryTikDatas } from '@/services/api/quote'
import { useDataset } from './dataset'
import { useOptions } from './options'

export function useSmoothedLineChart(goodscode: string) {
    const { dataset, clearData } = useDataset()
    const { options, initOptions, updateOptions } = useOptions(dataset)

    const loading = ref(false)
    const isEmpty = ref(false)
    const dataIndex = ref(-1); // 当前数据索引值
    const quote = futuresStore.actions.getQuoteDayInfoByCode(goodscode) // 实时行情

    // 当前选中的数据项
    const selectedItem = computed(() => {
        const { price } = dataset.line.source;
        return {
            price: price[dataIndex.value] ?? '--',
        }
    })

    /**
     * 初始化数据
     */
    const initData = () => {
        clearData();
        dataIndex.value = -1;
        isEmpty.value = true;
        loading.value = true;

        queryHistoryTikDatas({
            goodsCode: goodscode,
            startTime: formatDate(new Date().toISOString(), 'YYYY-MM-DD 00:00:00'),
            endTime: formatDate(new Date().toISOString(), 'YYYY-MM-DD 23:59:59'),
            isAsc: true,
        }).then((res) => {
            if (res.data.length) {
                const { date, price } = dataset.line.source
                dataIndex.value = res.data.length - 1
                isEmpty.value = false

                res.data.forEach(({ PE, TS }) => {
                    date.push(formatDate(TS, 'HH:mm:ss'))
                    price.push(PE)
                })
            }
        }).finally(() => {
            loading.value = false
        })
    }

    // 监听行情推送
    watch(() => quote.value?.last, () => {
        if (!loading.value && quote.value) {
            const { last, lasttime } = quote.value
            const { date, price } = dataset.line.source
            date.push(formatDate(lasttime, 'HH:mm:ss'))
            price.push(last)
            updateOptions()
        }
    })

    return {
        options,
        loading,
        isEmpty,
        dataIndex,
        selectedItem,
        initData,
        initOptions,
    }
}