import { reactive, watch } from 'vue'
import { timerInterceptor } from '@/utils/timer'
import { useThemeStore } from '@/stores'
import { echarts } from '@/components/base/echarts/core'
import { EchartsDataset, EchartsOptions, Colors } from './interface'

const { appTheme } = useThemeStore();

function getColors() {
    // 默认主题色配置
    const defaultColors: Colors = {
        upColor: '#ff3333',
        downColor: '#0aab62',
        xAxisLineColor: 'rgba(128,128,128,.1)',
        yAxisLineColor: 'rgba(128,128,128,.1)',
        seriesLineColor: '#50b4eb',
        seriesAreaGradients: new echarts.graphic.LinearGradient(0, 0, 0, 1,
            [
                {
                    offset: 0,
                    color: 'rgba(80, 180, 235, .2)',
                },
                {
                    offset: 1,
                    color: 'rgba(80, 180, 235, .15)',
                },
            ],
            false
        ),
        seriesMarkLabelColor: '#fff',
        seriesMarkLineColor: 'rgba(102,102,102,.6)'
    }

    const colors = {
        default: defaultColors,
        dark: defaultColors,
        light: {
            ...defaultColors,
            downColor: '#00A843',
            xAxisLineColor: '#DAE5EC',
            yAxisLineColor: '#DAE5EC',
            seriesLineColor: '#3864d7',
            seriesMarkLabelColor: '#777',
            seriesMarkLineColor: '#ACB8C0',
        }
    }

    return colors[appTheme.value];
}

export function useOptions(dataset: EchartsDataset) {
    // 图表配置项
    const options = reactive<EchartsOptions>({
        colors: getColors(),
        timeline: {},
    })

    // 计算涨跌幅百分比，涨跌幅=(今日收盘价-昨日收盘价)/昨日收盘价*100%
    const calcRatio = (val: number) => {
        const { yestclose } = dataset;
        const num = Number(val);

        if (isNaN(num)) {
            return '-';
        }
        if (yestclose > 0) {
            const result = (num - yestclose) / yestclose * 100;
            return result.toFixed(2) + '%';
        }
        return '0%';
    }

    const initOptions = () => {
        const { timeline, maxMark, minMark, interval, yestclose, decimal } = dataset;
        const { colors } = options;

        options.timeline = {
            dataset: timeline,
            grid: {
                left: '10px',
                right: '10px',
                top: '15px',
                bottom: '10px',
                containLabel: true,
            },
            axisPointer: {
                label: {
                    precision: decimal, // 小数点精度
                    backgroundColor: 'rgba(128,128,128,.75)',
                }
            },
            xAxis: {
                type: 'category',
                axisLabel: {
                    showMinLabel: true,
                    showMaxLabel: true,
                    margin: 12,
                },
                axisTick: {
                    show: false,
                }
            },
            yAxis: [
                {
                    id: 'leftY',
                    max: maxMark,
                    min: minMark,
                    interval,
                    axisLabel: {
                        formatter: (val: number) => val.toFixed(decimal),
                        color: (val) => {
                            if (val) {
                                const num = Number(val).toFixed(decimal);
                                if (Number(num) > yestclose) return colors.upColor;
                                if (Number(num) < yestclose) return colors.downColor;
                            }
                            return '#7a8a94';
                        },
                    },
                    splitLine: {
                        lineStyle: {
                            // 坐标分隔线颜色
                            color: colors.xAxisLineColor,
                        },
                    },
                },
                {
                    id: 'rightY',
                    max: maxMark,
                    min: minMark,
                    interval,
                    axisLabel: {
                        formatter: (val: number) => calcRatio(val),
                        color: (val) => {
                            if (val) {
                                const num = Number(val).toFixed(decimal);
                                if (Number(num) > yestclose) return colors.upColor;
                                if (Number(num) < yestclose) return colors.downColor;
                            }
                            return '#7a8a94';
                        },
                    },
                    axisPointer: {
                        show: false,
                    },
                    splitLine: {
                        show: false,
                    },
                }
            ],
            // series 中不指定 yAxisId 或 yAxisIndex 默认关联 yAxis 第一个配置，xAxis 配置同理
            series: [
                {
                    name: '分时',
                    type: 'line',
                    yAxisId: 'leftY',
                    smooth: true,
                    symbol: 'none', //中时有小圆点
                    lineStyle: {
                        color: colors.seriesLineColor,
                        opacity: 0.8,
                        width: 1,
                    },
                    areaStyle: {
                        color: colors.seriesAreaGradients,
                        opacity: 1,
                    },
                    // 标线
                    markLine: {
                        symbolSize: 6,
                        // 标线标签样式
                        label: {
                            show: false,
                            backgroundColor: 'rgba(128,128,128,.75)',
                            padding: 5,
                            borderRadius: 3,
                            position: 'insideStartTop',
                        },
                        // 标线样式
                        lineStyle: {
                            type: 'dashed',
                            color: 'rgba(128,128,128,.3)'
                        },
                        data: [
                            {
                                yAxis: timeline.source.close[timeline.source.close.length - 1] ?? '--', // 最新价
                                label: {
                                    show: true,
                                    color: colors.seriesMarkLabelColor,
                                },
                                lineStyle: {
                                    color: colors.seriesMarkLineColor,
                                },
                            },
                            {
                                yAxis: yestclose, // 昨日收盘价
                            },
                        ],
                    },
                },
                {
                    name: 'MA5',
                    type: 'line',
                    sampling: 'average', //折线图在数据量远大于像素点时候的降采样策略，开启后可以有效的优化图表的绘制效率
                    smooth: true,
                    symbol: 'none',
                    lineStyle: {
                        width: 1,
                        opacity: 0.8,
                        color: '#ffcc00',
                    },
                },
            ],
        }
    }

    // 动态更新数据
    const updateOptions = timerInterceptor.setThrottle(() => {
        const { colors } = options;
        const { timeline, yestclose } = dataset;

        options.timeline = {
            dataset: {
                source: timeline.source,
            },
            series: [
                {
                    name: '分时',
                    markLine: {
                        data: [
                            {
                                yAxis: timeline.source.close[timeline.source.close.length - 1] ?? '--', // 最新价
                                lineStyle: {
                                    color: colors.seriesMarkLineColor
                                },
                            },
                            {
                                yAxis: yestclose, // 昨日收盘价
                            },
                        ],
                    },
                },
            ],
        }
    }, 1000)

    // 监听主题变化
    watch(appTheme, () => {
        options.colors = getColors();
        initOptions();
    })

    return {
        options,
        initOptions,
        updateOptions,
    }
}