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

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

  // 初始化图表
  const initChart = () => {
    if (!domRef.value) return;
    chartInstance.value = echarts.init(domRef.value, 'macarons');
  };

  const setOption = (option) => {
    if (!chartInstance.value) return;
    chartInstance.value.setOption(option);
  };

  const handleResize = () => {
    if (!chartInstance.value) return;
    chartInstance.value.resize();
  };

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

  // 组件挂载时初始化
  onMounted(() => {
    initChart();
  });

  // 组件卸载时销毁
  onUnmounted(() => {
    if (chartInstance.value) {
      chartInstance.value.dispose();
      chartInstance.value = null;
    }
  });

  return {
    chartInstance,
    setOption,
  };
}