import { onBeforeUnmount, onMounted, type Ref } from 'vue';
import * as echarts from 'echarts';

/**
 * 统一管理振动报表页的 ECharts 实例，并在容器尺寸变化时立即重绘。
 * 这里直接监听容器而不是只监听 window，避免抽屉、栅格折行后图表仍停留旧尺寸。
 */
export function useChartResize(...chartRefs: Ref<HTMLElement | undefined>[]) {
  const chartInstances = new Map<HTMLElement, echarts.ECharts>();
  let resizeObserver: ResizeObserver | null = null;

  function getChart(chartRef: Ref<HTMLElement | undefined>) {
    const element = chartRef.value;
    if (!element) {
      return undefined;
    }
    if (!chartInstances.has(element)) {
      chartInstances.set(element, echarts.init(element));
    }
    return chartInstances.get(element);
  }

  function resizeAll() {
    chartInstances.forEach((chart) => {
      if (!chart.isDisposed()) {
        chart.resize();
      }
    });
  }

  function disposeAll() {
    chartInstances.forEach((chart) => chart.dispose());
    chartInstances.clear();
  }

  onMounted(() => {
    resizeObserver = new ResizeObserver(() => {
      resizeAll();
    });
    chartRefs.forEach((chartRef) => {
      if (chartRef.value) {
        resizeObserver?.observe(chartRef.value);
      }
    });
    window.addEventListener('resize', resizeAll);
  });

  onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeAll);
    resizeObserver?.disconnect();
    disposeAll();
  });

  return {
    getChart,
    disposeAll
  };
}
