<template>
  <div ref="chart" :style="style"></div>
</template>

<script lang="ts" setup>
import * as echarts from 'echarts'
import elementResizeDetectorMaker from 'element-resize-detector'

const props = defineProps({
  // 图表的宽度
  width: {
    type: String,
    default: '600px'
  },
  // 图表的高度
  height: {
    type: String,
    default: '400px'
  },
  // 图表的配置
  option: {
    type: Object,
    required: true
  }
})

const chart = shallowRef<any>()

const style = computed(() => ({
  width: props.width,
  height: props.height
}))

// 初始化图表
const initChart = () => {
  // setTimeout(() => {
  if (!chartInstance.value) {
    chartInstance.value = echarts.init(chart.value)
  }
  chartInstance.value.clear();
  props.option && chartInstance.value.setOption(props.option, true)

  // }, 1000)

}

// 处理图表容器大小变化
const handleResize = () => {
  const erd = elementResizeDetectorMaker()
  // 监听图表容器的大小变化
  erd.listenTo(chart.value, () => {
    // 改变图表尺寸
    chartInstance.value?.resize()
  })
}

const chartInstance = shallowRef<any>()

watch(
  () => props.option,
  () => {
    initChart()
  },
  { deep: true }
)

onMounted(() => {
  initChart()
  handleResize()
})

onBeforeUnmount(() => {
  if (chartInstance.value) {
    // 销毁图表实例
    chartInstance.value.dispose()
    chartInstance.value = null
  }
})
</script>

<style lang="scss" scoped>
/* 你可以在这里定义样式 */
</style>
