import { ref, onMounted, onUnmounted, getCurrentInstance } from 'vue'
import { debounce } from '@/utils/time'
import { v4 } from 'uuid'
import { getTheme, ThemeEnum } from '@/common/config/theme';
import ResizeObserver from 'resize-observer-polyfill';
import * as echarts from 'echarts'

// 默认配置项
const defaultOption: echarts.EChartsOption = {
    backgroundColor: 'transparent',
    animation: false,
    grid: {
        top: 20,
        bottom: 40,
    },
    axisPointer: {
        show: true,
        triggerTooltip: false,
    },
}

export function useEcharts() {
    const context = getCurrentInstance();
    const chartElement = ref<HTMLElement>(); // chart 元素
    let chart: echarts.ECharts; // chart 对象

    // 图表配置项
    const setOptions = (option: echarts.EChartsOption, notMerge = false) => {
        chart.setOption(option, notMerge);
        chart.hideLoading();
        context?.emit('update:loading', false);
    };

    // 显示加载动画
    const showLoading = (loading: boolean) => {
        if (loading) {
            chart.clear(); // 清空图表
            chart.setOption(defaultOption);

            const theme = getTheme(); // 当前主题
            switch (theme.value) {
                case ThemeEnum.default:
                case ThemeEnum.dark:
                    chart.showLoading({
                        text: '加载中...',
                        textColor: '#fff',
                        color: 'rgba(255, 255, 255, 0.75)',
                        maskColor: 'transparent',
                    });
                    break;
                default:
                    chart.showLoading({
                        text: '加载中...',
                        maskColor: 'transparent',
                    });
            }
        }
    };

    // 图表初始化
    onMounted(() => {
        const uuid = v4();
        const el = chartElement.value;

        if (el) {
            // 初始化图表
            chart = echarts.init(el as HTMLElement);
            chart.setOption(defaultOption);
            chart.off('mousemove');

            // 监听鼠标滑动
            chart.getZr().on('mousemove', (params) => {
                const pointInPixel = [params.offsetX, params.offsetY];
                if (chart.containPixel('grid', pointInPixel)) {
                    const pointInGrid = chart.convertFromPixel({ seriesIndex: 0 }, pointInPixel)
                    const dataIndex = pointInGrid[0];
                    if (dataIndex > -1) {
                        context?.emit('update:index', dataIndex);
                    }
                }
            })

            // 监听元素变化
            new ResizeObserver(() => {
                debounce(() => {
                    chart.resize && chart.resize(); // 重置图表大小
                }, 50, uuid);
            }).observe(el);

            context?.emit('ready', chart);
        }
    })

    onUnmounted(() => {
        chart?.dispose();
    })

    return {
        chartElement,
        showLoading,
        setOptions
    }
}