<template>
  <div ref="chartRef" :style="{ height: height, width: width }"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  option: {
    type: Object,
    required: true
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '400px'
  }
})

const chartRef = ref(null)
let chart = null

onMounted(() => {
  const initChart = () => {
    chart = echarts.init(chartRef.value)
    chart.setOption(props.option)
  }
  initChart()

  // 监听窗口大小变化，自动调整图表大小
  const handleResize = () => {
    chart && chart.resize()
  }
  window.addEventListener('resize', handleResize)

  // 监听组件选项变化，更新图表
  const handleOptionChange = (newOption) => {
    chart && chart.setOption(newOption)
  }
  watch(() => props.option, handleOptionChange, { deep: true })

  // 监听 DOM 变化，调整图表大小
  const resizeObserver = new ResizeObserver(() => {
    chart && chart.resize()
  })
  resizeObserver.observe(chartRef.value)
})

onUnmounted(() => {
  window.removeEventListener('resize', () => {
    chart && chart.resize()
  })
  chart && chart.dispose()
  chart = null
})
</script>
