<template>
  <div ref="chartRef" style="width: 100%; height: 350px;"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  data: {
    type: Array as any,
    default: () => []
  }
});

const chartRef = ref<HTMLElement | null>(null);
let chart: echarts.ECharts | null = null;

const initChart = () => {
  if (!chartRef.value || props.data.length === 0) return;
  if (!chart) {
    chart = echarts.init(chartRef.value);
  }

  // 颜色：蓝、绿、橙
  const colors = ['#409EFF', '#67C23A', '#FFBB96'];

  const chartData = props.data.map((item: any, index: number) => ({
    name: item.label,
    value: parseFloat(item.value) || 0,
    itemStyle: {
      color: colors[index % colors.length]
    }
  }));

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}'
    },
    legend: {
      orient: 'vertical',
      right: '10%',
      top: 'center',
      itemWidth: 10,
      itemHeight: 10,
      itemGap: 20,
      formatter: (name: string) => {
        const item = props.data.find((i: any) => i.label === name);
        return `{name|${name}: }{value|${item ? item.value : ''}}`;
      },
      textStyle: {
        rich: {
          name: { color: '#666', fontSize: 12 },
          value: { color: '#333', fontSize: 13, fontWeight: 'bold' }
        }
      }
    },
    series: [
      {
        name: '访销统计',
        type: 'pie',
        radius: ['50%', '70%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        label: { show: false },
        emphasis: { label: { show: false } },
        data: chartData,
        itemStyle: {
          borderRadius: 0,
          borderColor: '#fff',
          borderWidth: 2
        }
      },
      // 外层背景装饰圈
      {
        type: 'pie',
        radius: ['45%', '75%'],
        center: ['40%', '50%'],
        silent: true,
        itemStyle: { color: '#f0f2f5' },
        z: -1,
        label: { show: false },
        data: [{ value: 1 }]
      }
    ]
  };

  chart.setOption(option);
};

onMounted(() => {
  initChart();
  window.addEventListener('resize', () => chart?.resize());
});

watch(() => props.data, () => {
  initChart();
}, { deep: true });
</script>
