<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 = ['#3AA1FF', '#4ECB73', '#FFBB96'];

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

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}'
    },
    legend: {
      orient: 'vertical',
      right: '5%',
      top: 'center',
      itemWidth: 12,
      itemHeight: 12,
      itemGap: 25,
      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: ['60%', '80%'],
        center: ['35%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: false
          }
        },
        labelLine: {
          show: false
        },
        data: chartData
      },
      // 装饰性的背景圆环
      {
        type: 'pie',
        radius: ['55%', '85%'],
        center: ['35%', '50%'],
        silent: true,
        itemStyle: {
          color: '#f8f9fb'
        },
        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>
