import { reactive, watch } from 'vue'
import { timerInterceptor } from '@/utils/timer'
import { useThemeStore } from '@/stores'
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)',
    }

    const colors = {
        default: defaultColors,
        dark: defaultColors,
        light: {
            ...defaultColors,
            downColor: '#00A843',
        }
    }

    return colors[appTheme.value];
}

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

    const initOptions = () => {
        const { xAxisLineColor } = options.colors
        const { line } = dataset

        options.line = {
            dataset: line,
            grid: {
                left: '16px',
                right: '16px',
                top: '24px',
                bottom: '16px',
                containLabel: true,
            },
            xAxis: {
                type: 'category',
            },
            yAxis: {
                splitLine: {
                    lineStyle: {
                        // 坐标分隔线颜色
                        color: xAxisLineColor,
                    },
                },
            },
            // series 中不指定 yAxisId 或 yAxisIndex 默认关联 yAxis 第一个配置，xAxis 配置同理
            series: [
                {
                    name: '分时',
                    type: 'line',
                    smooth: true,
                    symbol: 'none', //中时有小圆点
                },
            ],
        }
    }

    // 动态更新数据
    const updateOptions = timerInterceptor.setThrottle(() => {
        const { line } = dataset;
        options.line = {
            dataset: {
                source: line.source,
            },
        }
    }, 1000)

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

    return {
        options,
        initOptions,
        updateOptions,
    }
}