import { reactive, watch } from 'vue'
import { timerInterceptor } from '@/@next/utils/timer'
import { getTheme } from '@/common/config/theme'
import { echarts } from '@/@next/components/base/echarts/core'
import { EchartsDataset, EchartsOptions, Colors } from './interface'

const theme = getTheme();

function getColors() {
    // 默认主题色配置
    const defaultColors: Colors = {
        upColor: '#FF2B2B',
        downColor: '#1FF195',
        xAxisLineColor: '#171B1D',
        yAxisLineColor: '#171B1D',
        seriesLineColor: '#39afe6',
        seriesMarkLabelColor: '#3C454B',
        seriesMarkLineColor: '#666',
        seriesAreaGradients: new echarts.graphic.LinearGradient(0, 0, 0, 1,
            [
                {
                    offset: 0,
                    color: 'rgba(0, 136, 212, 0.3)',
                },
                {
                    offset: 1,
                    color: 'rgba(0, 136, 212, 0.3)',
                },
            ],
            false
        ),
    }

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

    return colors[theme.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,
            axisPointer: {
                label: {
                    // 小数点精度
                    precision: decimal,
                }
            },
            xAxis: {
                type: 'category',
                axisLabel: {
                    showMinLabel: true,
                    showMaxLabel: true,
                    margin: 12,
                },
            },
            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,
                        shadowColor: 'rgba(0, 0, 0, 0.1)',
                        shadowBlur: 10,
                    },
                    // 标线
                    markLine: {
                        // 标线两端图标
                        symbol: 'none',
                        // 标线标签样式
                        label: {
                            color: colors.seriesMarkLabelColor,
                            fontWeight: 'bold',
                            backgroundColor: 'rgba(255,255,255,.75)',
                            padding: 5,
                            borderRadius: 3
                        },
                        // 标线样式
                        lineStyle: {
                            type: 'dashed',
                        },
                        data: [
                            {
                                yAxis: timeline.source.close[timeline.source.close.length - 1] ?? '--', // 最新价
                                lineStyle: {
                                    color: colors.seriesMarkLineColor
                                },
                            },
                            {
                                yAxis: yestclose, // 昨日收盘价
                            },
                        ],
                    },
                },
                {
                    name: 'MA5',
                    type: 'line',
                    sampling: 'average', //折线图在数据量远大于像素点时候的降采样策略，开启后可以有效的优化图表的绘制效率
                    smooth: true,
                    symbol: 'none',
                    lineStyle: {
                        width: 1,
                        opacity: 0.8,
                    },
                },
            ],
        }
    }

    // 动态更新数据
    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(theme, () => {
        options.colors = getColors();
        initOptions();
    })

    return {
        options,
        initOptions,
        updateOptions,
    }
}