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

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

const animationDuration = 6000

const props = defineProps({
  className: {
    type: String,
    default: 'chart'
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '300px'
  }
})

const chartRef = ref(null)
let chartInstance = null
let resizeObserver = null
let resizeTimer = null

const handleResize = () => {
  if (resizeTimer) {
    clearTimeout(resizeTimer)
  }

  resizeTimer = setTimeout(() => {
    if (chartInstance) {
      try {
        chartInstance.resize()
      } catch (error) {
        console.error('图表重绘失败:', error)
      }
    }
  }, 200)
}

const initResizeListener = () => {
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)

  // 使用 ResizeObserver 监听容器自身大小变化
  if (typeof ResizeObserver !== 'undefined' && chartRef.value) {
    resizeObserver = new ResizeObserver((entries) => {
      handleResize()
    })
    resizeObserver.observe(chartRef.value)
  }
}

const removeResizeListener = () => {
  // 清理定时器
  if (resizeTimer) {
    clearTimeout(resizeTimer)
    resizeTimer = null
  }

  // 移除窗口监听
  window.removeEventListener('resize', handleResize)

  // 断开 ResizeObserver
  if (resizeObserver) {
    resizeObserver.disconnect()
    resizeObserver = null
  }
}

const initChart = () => {
  if (!chartRef.value) return

  if (chartInstance) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(chartRef.value, 'macarons')

  chartInstance.setOption({
    tooltip: {
      trigger: 'item',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      orient: 'horizontal',
      left: 'right'
    },
    series: [
      {
        name: 'Access From',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 1048, name: 'Search Engine' },
          { value: 735, name: 'Direct' },
          { value: 580, name: 'Email' },
          { value: 484, name: 'Union Ads' },
          { value: 300, name: 'Video Ads' }
        ],
        labelLine: {
          show: false
        },
        label:{
          show:false
        },
        animationEasing: 'cubicInOut',
        animationDuration: 2600,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })

  // 图表初始化后立即重绘一次，确保尺寸正确
  nextTick(() => {
    chartInstance.resize()
  })
}

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

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

// 暴露方法给父组件
defineExpose({
  resizeChart: handleResize
})
</script>