import { ref, onMounted, onUnmounted, getCurrentInstance } from 'vue'
import { timerInterceptor } from '@/utils/timer'
import { echarts, ECOption } from './core'
import ResizeObserver from 'resize-observer-polyfill'

// 默认配置项
const defaultOption: ECOption = {
    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: ECOption, notMerge = false) => {
        chart?.setOption(option, notMerge);
    }

    // 图表初始化
    onMounted(() => {
        const el = chartElement.value;
        if (el) {
            // 初始化图表
            chart = echarts.init(el);
            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];
                    context?.emit('update:dataIndex', dataIndex);
                }
            })

            // 图表重置大小
            const resize = timerInterceptor.setDebounce(() => {
                chart.resize && chart.resize();
            }, 50);

            // 监听元素变化
            const resizeObserver = new ResizeObserver(resize);
            resizeObserver.observe(el);
            context?.emit('ready', chart);

            onUnmounted(() => {
                resizeObserver.unobserve(el);
                chart.dispose();
            })
        }
    })

    return {
        chartElement,
        setOptions
    }
}