<template>
    <echart-base :options="options" v-model:loading="loading"></echart-base>
</template>

<script lang="ts">
import { defineComponent, PropType, ref, watch, watchEffect } from 'vue';
import { QueryHistoryDatasRsp, QueryQuoteDayRsp, QueryHistoryDatas, CycleType } from '@/services/go/quote/interface';
import { QueryHistoryDatas as queryHistoryDatas } from '@/services/go/quote';
import { handleEchart, ChartData } from './setup';
import EchartBase from '../echart-base/index.vue';
import moment from 'moment';

export default defineComponent({
    name: 'EchartKline',
    components: {
        EchartBase,
    },
    props: {
        // 周期类型
        cycleType: {
            type: Number as PropType<CycleType>,
            required: true,
        },
        // 实时行情数据
        quoteData: {
            type: Object as PropType<QueryQuoteDayRsp>,
            required: true,
        },
    },
    setup(props) {
        const loading = ref(true);
        const { chartData, options, updateOptions, initOptions } = handleEchart();

        // 处理图表数据
        const handleData = (rawData: QueryHistoryDatasRsp[]): ChartData => {
            const datas: number[][] = [],
                times: string[] = [];

            rawData.forEach((item) => {
                const { o, c, h, l, ts } = item;
                const t = moment(ts).format('YYYY/MM/DD');
                times.push(t);
                datas.push([o, c, h, l]);
            });

            const { last, lasttime: lastTime } = props.quoteData;

            return {
                datas,
                times,
                last,
                lastTime,
                ma5: calcMA(rawData, 5),
                ma10: calcMA(rawData, 10),
                ma15: calcMA(rawData, 15),
            };
        };

        // 计算平均线
        const calcMA = (rawData: QueryHistoryDatasRsp[], count: number) => {
            const result: string[] = [];
            if (rawData.length >= count) {
                // 所有非补充数据的索引id
                const dataIndexs = rawData.reduce((prev: number[], cur, index) => {
                    if (!cur.f) prev.push(index);
                    return prev;
                }, []);
                // 均线起始位置
                const startIndex = dataIndexs[count - 1];

                rawData.forEach((item, index) => {
                    if (index < startIndex) {
                        result.push('-');
                    } else {
                        const j = dataIndexs.findIndex((val) => val === index);
                        // 判断是否补充数据
                        if (j === -1) {
                            // 取上个平均值
                            result.push(result[result.length - 1]);
                        } else {
                            // 向后取MA数
                            const splitIndexs = dataIndexs.slice(j - (count - 1), j + 1);
                            // 计算总价
                            const total = splitIndexs.reduce((sum, val) => sum + rawData[val].c, 0);
                            // 计算均线
                            result.push((total / count).toFixed(2));
                        }
                    }
                });
            }
            return result;
        };

        // 监听周期选项变化
        watchEffect(() => {
            loading.value = true;
            const params: QueryHistoryDatas = {
                cycleType: props.cycleType,
                goodsCode: props.quoteData.goodscode,
                isAsc: true,
            };
            // 查询K线数据
            queryHistoryDatas(params).then((res) => {
                chartData.value = handleData(res);
                initOptions();
            });
        });

        watch(
            () => props.quoteData.last,
            (val) => {
                if (!loading.value) {
                    chartData.value.last = val;
                    updateOptions();
                }
            }
        );

        return {
            loading,
            options,
        };
    },
});
</script>