import { ref, onMounted, onBeforeUnmount, nextTick, type Ref } from 'vue'
import type { EChartsType } from 'echarts'
export function chartMixins() {
  const charts: Ref<(EChartsType | null)[]> = ref([])
  const destroyedFlag: Ref<boolean> = ref(false)

  const disposeAll = () => {
    charts.value.map((chart) => {
      if (chart) {
        chart.dispose()
        chart = null
      }
    })
  }

  const changeChartSize = () => {
    nextTick(() => {
      charts.value.forEach((chart) => {
        if (chart) {
          chart.resize()
        }
      })
    })
  }

  onMounted(() => {
    window.addEventListener('resize', changeChartSize)
  })

  onBeforeUnmount(() => {
    destroyedFlag.value = true
    window.removeEventListener('resize', changeChartSize)
    disposeAll()
  })

  return {
    charts,
    disposeAll,
    destroyedFlag,
  }
}
