<script lang="ts" setup>
import type { EchartsUIType } from '@vben/plugins/echarts';

import { onMounted, ref } from 'vue';

import { EchartsUI, useEcharts } from '@vben/plugins/echarts';
import { getOrderSourceStatistics } from '#/api/order/order';

const chartRef = ref<EchartsUIType>();
const { renderEcharts } = useEcharts(chartRef);
const loading = ref(false);

// 获取订单来源统计数据
async function fetchOrderSourceStatistics() {
  try {
    loading.value = true;
    const response = await getOrderSourceStatistics();
    
    // 提取产品名称和订单数量
    const data = response.items.map(item => ({
      name: item.product_name,
      value: item.order_count,
    }));
    
    // 如果有数据，则渲染图表
    if (data && data.length > 0) {
      renderEcharts({
        legend: {
          bottom: '2%',
          left: 'center',
          data: data.map(item => item.name),
        },
        series: [
          {
            animationDelay() {
              return Math.random() * 100;
            },
            animationEasing: 'exponentialInOut',
            animationType: 'scale',
            avoidLabelOverlap: false,
            color: [
              '#5ab1ef', '#b6a2de', '#67e0e3', '#2ec7c9', 
              '#ffb980', '#d87a80', '#8d98b3', '#e5cf0d',
              '#97b552', '#95706d', '#dc69aa', '#07a2a4',
              '#9a7fd1', '#588dd5', '#f5994e', '#c05050'
            ],
            data: data,
            emphasis: {
              label: {
                fontSize: '12',
                fontWeight: 'bold',
                show: true,
              },
            },
            itemStyle: {
              borderRadius: 10,
              borderWidth: 2,
            },
            label: {
              position: 'center',
              show: false,
            },
            labelLine: {
              show: false,
            },
            name: '订单来源',
            radius: ['40%', '65%'],
            type: 'pie',
          },
        ],
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)',
        },
      });
    }
  } catch (error) {
    console.error('获取订单来源统计数据失败:', error);
  } finally {
    loading.value = false;
  }
}

onMounted(() => {
  fetchOrderSourceStatistics();
});
</script>

<template>
  <div v-if="loading" class="flex justify-center items-center h-64">
    加载中...
  </div>
  <EchartsUI v-else ref="chartRef" />
</template>
