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

<script setup name="BaseEChart">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'
import { useElementSize, useResizeObserver } from '@vueuse/core'

defineOptions({
  name: 'BaseEChart'
})

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

const chartRef = ref(null)
let chartInstance = null

// 初始化图表
const initChart = () => {
  if (chartInstance) {
    chartInstance.dispose()
  }
  
  if (!chartRef.value) return
  
  chartInstance = echarts.init(chartRef.value, props.theme)
  chartInstance.setOption(props.options)
}

// 监听容器大小变化
useResizeObserver(chartRef, () => {
  if (chartInstance) {
    chartInstance.resize()
  }
})

// 监听配置变化
watch(
  () => props.options,
  (newOptions) => {
    if (chartInstance) {
      chartInstance.setOption(newOptions)
    }
  },
  { deep: true }
)

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

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})

// 暴露更新方法
defineExpose({
  getChart: () => chartInstance,
  resize: () => chartInstance?.resize()
})
</script>

<style scoped>
.chart-container {
  position: relative;
}
</style> 