import { ref, shallowRef } from 'vue';
import { useResizeObserver } from '@vueuse/core';
import * as echarts from 'echarts';

export function useEcharts(domRef) {
  const chartInstance = shallowRef(null);
  const initialized = ref(false);

  // 初始化图表
  const initChart = () => {
    if (!domRef.value || initialized.value) return;
    try {
      chartInstance.value = echarts.init(domRef.value, 'macarons');
      initialized.value = true;
    } catch (error) {
      console.error('ECharts初始化失败:', error);
    }
  };

  const setOption = (option, notMerge = false) => {
    if (!chartInstance.value && !initialized.value) {
      initChart();
    }
    if (!chartInstance.value) return;

    try {
      chartInstance.value.setOption(option, notMerge);
      // 仅在需要时调整大小，避免重复调用
      if (domRef.value && domRef.value.offsetHeight > 0) {
        chartInstance.value.resize();
      }
    } catch (error) {
      console.error('ECharts设置选项失败:', error);
    }
  };

  const handleResize = () => {
    if (!chartInstance.value) return;
    try {
      chartInstance.value.resize();
    } catch (err) {
      console.log(err);
    }
  };

  // 使用vueuse的resizeObserver监听容器大小变化
  useResizeObserver(domRef, () => {
    handleResize();
  });

  const dispose = () => {
    if (chartInstance.value) {
      chartInstance.value.dispose();
      chartInstance.value = null;
      initialized.value = false;
    }
  };

  return {
    chartInstance,
    setOption,
    dispose,
    initChart
  };
}