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

/**
 * ECharts 图表实例管理 + 自动 resize
 * @param chartRefs 图表容器 ref 数组
 * @returns chartInstances 用于外部 setOption
 */
export function useChartResize(...chartRefs: Ref<HTMLElement | undefined>[]) {
  const chartInstances = new Map<HTMLElement, echarts.ECharts>()

  /** 获取或创建图表实例 */
  function getChart(ref: Ref<HTMLElement | undefined>): echarts.ECharts | undefined {
    const el = ref.value
    if (!el) return undefined
    if (!chartInstances.has(el)) {
      chartInstances.set(el, echarts.init(el))
    }
    return chartInstances.get(el)
  }

  /** 释放所有图表实例 */
  function disposeAll() {
    chartInstances.forEach(chart => chart.dispose())
    chartInstances.clear()
  }

  let resizeObserver: ResizeObserver | null = null

  onMounted(() => {
    resizeObserver = new ResizeObserver(() => {
      chartInstances.forEach(chart => {
        if (!chart.isDisposed()) {
          chart.resize()
        }
      })
    })
    // 观察所有图表容器
    chartRefs.forEach(r => {
      if (r.value) {
        resizeObserver!.observe(r.value)
      }
    })
    // 同时监听窗口 resize
    window.addEventListener('resize', handleResize)
  })

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

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

  return { getChart, disposeAll }
}
