import { ref, watch } from 'vue'
import { formatDecimal } from '@/utils/number';
import * as echarts from 'echarts';
import { State, Colors } from './type'
import { getTheme, ThemeEnum } from '@/common/config/theme';
import { throttle } from '@/utils/time'

export function useOptions(state: State) {
    const theme = getTheme(),
        timeOption = ref<echarts.EChartsOption>({});

    // 获取图表主题色
    const getColors = (): Colors => {
        switch (theme.value) {
            case ThemeEnum.default:
            case ThemeEnum.dark: {
                return {
                    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
                    ),
                };
            }
            case ThemeEnum.light: {
                return {
                    upColor: '#FF2B2B',
                    downColor: '#00A843',
                    xAxisLineColor: '#DAE5EC',
                    yAxisLineColor: '#DAE5EC',
                    seriesLineColor: '#3864d7',
                    seriesMarkLabelColor: '#777',
                    seriesMarkLineColor: '#ACB8C0',
                    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 initOptions = (onReady?: () => void) => {
        const colors = getColors();
        const { dataset, maxMark, minMark, interval, yestClose, decimal } = state;

        timeOption.value = {
            dataset,
            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) => formatDecimal(val, decimal).toString(),
                        color: (val: any) => {
                            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: any) => {
                            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: dataset.source.close[dataset.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,
                    },
                },
            ],
        }

        onReady && onReady();
    }

    // 动态更新数据
    const updateOptions = throttle(() => {
        const { seriesMarkLineColor } = getColors();
        const { dataset, yestClose } = state;

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

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

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

    // 监听主题变化
    watch(theme, () => initOptions());

    return {
        timeOption,
        initOptions,
        updateOptions,
    }
}