import { QueryTSDataRsp } from '@/services/go/quote/interface';
import { State } from './type';
import { getRangeTime } from '@/utils/time';
import moment from 'moment';

export function useDataset() {
    // 行情历史数据中所有补充数据的索引位置(用于指标计算)
    const invalidData: number[] = [];
    const state: State = {
        rawDate: [],
        yestClose: 0,
        decimal: 0,
        maxMark: 0,
        minMark: 0,
        interval: 0,
        dataset: {
            dimensions: ['date', 'close', 'ma5'],
            source: {
                date: [],
                close: [],
                ma5: []
            },
        }
    }

    // 处理行情数据
    const handleData = (rawData: QueryTSDataRsp) => {
        const { date, close, ma5 } = state.dataset.source;
        invalidData.length = 0;
        state.decimal = rawData.decimalPlace;
        state.yestClose = rawData.preSettle;

        // 开盘交易时间
        for (let i = 0; i < rawData.runSteps.length; i++) {
            const { start, end } = rawData.runSteps[i];
            const rangeTime = getRangeTime(start, end, 'HH:mm', 'm');
            date.push(...rangeTime);
        }

        for (let i = 0; i < rawData.historyDatas.length; i++) {
            const { ts, c, f } = rawData.historyDatas[i];
            const date = moment(ts).format('YYYY-MM-DD HH:mm:ss');

            if (f) invalidData.push(i); // 添加补充数据的索引位置

            state.rawDate.push(date);
            close.push(c);
            ma5.push('-');
        }
        // 计算各种指标
        calcIndicator();
    }

    // 计算MA
    const calcMA = (startIndex = 0) => {
        const { close, ma5 } = state.dataset.source;
        for (let i = startIndex; i < close.length; i++) {
            // 判断是否补充数据
            if (invalidData.includes(i)) {
                ma5[i] = i > 0 ? ma5[i - 1].toString() : '--'; // 如果存在，取上一条记录的MA值
            } else {
                let n = 0;
                const tmpList: number[] = [];

                for (let j = i; j >= 0; j--) {
                    if (invalidData.includes(j)) continue; // 如果是补充数据，跳过本次循环
                    if (n === 5) break; // 如果 n 等于计数，结束循环
                    tmpList.push(close[j]);
                    n++;
                }

                if (n === 5) {
                    // 计算总价(收盘价总和)
                    const total = tmpList.reduce((res, val) => res + val, 0);
                    // 计算均价
                    ma5[i] = (total / 5).toFixed(2);
                } else {
                    ma5[i] = '--';
                }
            }
        }
    }

    // 计算图表最高低指标线
    const calcMarkLine = () => {
        const { close } = state.dataset.source;
        let max = Math.max(...close); // 取历史行情最高价
        let min = Math.min(...close); // 取历史行情最低价

        const last = close[close.length - 1], // 历史行情最后收盘价
            a = state.yestClose - min, // 计算收盘价和最低价的差值
            b = max - state.yestClose; // 计算收盘价和最高价的差值

        // 比较差值大小
        if (a > b) {
            max = state.yestClose + a;
            if (last > max) {
                const c = last - max;
                max += c;
                min -= c;
            }
        } else {
            min = min - (b - a);
            if (min > last) {
                const c = min - last;
                max += c;
                min -= c;
            }
        }

        state.maxMark = max + min * 0.01;
        state.minMark = min - min * 0.01;
        state.interval = (state.maxMark - state.minMark) / 6;
    };

    // 计算各种指标
    const calcIndicator = (startIndex = 0) => {
        calcMA(startIndex);
        calcMarkLine();
    }

    return {
        state,
        handleData,
        calcIndicator,
    }
}