<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue'
import * as echarts from 'echarts/core'
import {
  TooltipComponent,
  LegendComponent
} from 'echarts/components'
import { PieChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer
])

const props = defineProps({
  chartData: {
    type: Array,
    default: () => []
  }
})

const chartRef = ref(null)
let chartInstance = null

const initChart = () => {
  if (!chartRef.value) return
  
  chartInstance = echarts.init(chartRef.value)
  
  // 按摩头类型映射
  const massageTypeMap = {
    thermotherapy: '深部热疗',
    shockwave: '点阵按摩',
    ball: '全能滚珠',
    finger: '指疗通络',
    roller: '滚滚刺疗',
    stone: '温砭舒揉',
    ion: '离子光灸'
  }
  
  // 处理数据，确保有正确的格式
  const formattedData = props.chartData.map(item => ({
    name: massageTypeMap[item.name] || item.name || '未知',
    value: item.value || 0
  }))
  
  const option = {
    title: {
      text: '按摩头类型分布',
      left: 'center',
      top: 10,
      textStyle: {
        fontSize: 14,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      type: 'scroll',
      orient: 'horizontal',
      bottom: 10,
      left: 'center'
    },
    series: [
      {
        name: '按摩头类型',
        type: 'pie',
        radius: ['35%', '60%'],
        center: ['50%', '45%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: formattedData,
        color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']
      }
    ]
  }
  
  chartInstance.setOption(option)
}

const resizeChart = () => {
  chartInstance?.resize()
}

onMounted(() => {
  nextTick(() => {
    initChart()
    window.addEventListener('resize', resizeChart)
  })
})

watch(() => props.chartData, () => {
  nextTick(() => {
    if (chartInstance) {
      chartInstance.dispose()
    }
    initChart()
  })
}, { deep: true })

// 清理
onUnmounted(() => {
  window.removeEventListener('resize', resizeChart)
  chartInstance?.dispose()
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 350px;
  min-height: 300px;
}

@media (max-height: 768px) {
  .chart-container {
    height: 280px;
    min-height: 250px;
  }
}

@media (min-height: 1080px) {
  .chart-container {
    height: 400px;
  }
}
</style>
