import { markRaw, onMounted, onUnmounted, ref, type Ref } from "vue";
import * as echarts from "echarts";

//封装图表渲染逻辑
export function useChart(chartRef: Ref<HTMLElement | null>, setChartData: any, handleClickChart?: any) {
  const chartInstance = ref<echarts.ECharts | null>(null);
  const initChart = async () => {
    if (chartRef.value) {
      //这里echarts内部已经做了响应式处理 会和vue的响应式冲突 需要取消vue的响应式
      chartInstance.value = markRaw(echarts.init(chartRef.value));
      const options = await setChartData();
      chartInstance.value.setOption(options);
      //绑定图表点击事件
      if (handleClickChart) {
        chartInstance.value?.on("click", handleClickChart);
      }
    }
  };

  const resizeChart = () => {
    chartInstance.value?.resize();
  };

  onMounted(() => {
    initChart();
    window.addEventListener("resize", resizeChart);
  });

  onUnmounted(() => {
    window.removeEventListener("resize", resizeChart);
    if (chartInstance.value) {
      chartInstance.value.dispose();
    }
  });
}
