<template>
    <v-chart ref="saleChartRef" style="height: 420px" :option="options" />
</template>
<script setup>
    import VChart from 'vue-echarts';
    import { use } from 'echarts/core';
    import { CanvasRenderer } from 'echarts/renderers';
    import { PieChart } from 'echarts/charts';
    import {
        GridComponent,
        TooltipComponent,
        LegendComponent,
        ToolboxComponent
    } from 'echarts/components';
    import { ref, reactive, defineExpose } from 'vue';
    import request from '@/utils/request';

    // 按需加载echarts
    use([
        CanvasRenderer,
        PieChart,
        GridComponent,
        TooltipComponent,
        LegendComponent
    ]);

    const options = reactive({
        title: {
            text: '上报分析-理由比例',
            left: 'center',
            top: 10,
            textStyle: {
                fontSize: 16,
                fontWeight: 'bold'
            }
        },
        legend: {
            top: 'bottom'
        },
        series: [
            {
                name: '理由比例分布',
                type: 'pie',
                radius: [50, 150],
                center: ['50%', '50%'],
                roseType: 'area',
                itemStyle: {
                    borderRadius: 8
                },
                label: {
                    formatter: '{b}: {c} ({d}%)'
                },
                data: []
            }
        ]
    });

    // 更新图表数据
    const updateChartData = (data) => {
        if (!data || !Array.isArray(data)) return;

        // 将接口返回的数据转换为图表所需格式
        const chartData = data.map((item) => ({
            value: item.count,
            name: item.reason
        }));

        options.series[0].data = chartData;
    };

    // 暴露更新方法给父组件使用
    defineExpose({
        updateChartData
    });
</script>
