<template>
    <v-chart
        class="flex-1"
        ref="saleChartRef"
        style="height: 220px"
        :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,
        TitleComponent
    } from 'echarts/components';
    import { ref, reactive, watch } from 'vue';

    const props = defineProps({
        title: {
            type: String,
            default: '占比分析'
        },
        data: {
            type: Array,
            default: () => []
        }
    });

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

    const options = reactive({
        title: {
            text: props.title,
            textStyle: {
                color: '#363636',
                fontSize: 14,
                fontWeight: 'normal'
            }
        },
        tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
        },
        legend: {
            right: 'right',
            orient: 'vertical',
            top: 'center'
        },
        series: [
            {
                name: props.title,
                type: 'pie',
                radius: [15, 40],
                center: ['36%', '50%'],
                roseType: 'area',
                itemStyle: {
                    borderRadius: 8
                },
                label: {
                    show: true,
                    formatter: (params) => {
                        return `${params.name}\n\n${params.value}`;
                    },
                    position: 'outside',
                    alignTo: 'none',
                    minMargin: 5,
                    edgeDistance: 5,
                    lineHeight: 10
                },
                labelLine: {
                    show: true,
                    length: 8,
                    length2: 8,
                    maxSurfaceAngle: 80,
                    minTurnAngle: 45,
                    smooth: 0.2
                },
                data: props.data
            }
        ]
    });

    // 监听数据变化
    watch(
        () => props.data,
        (newVal) => {
            if (newVal && newVal.length) {
                options.series[0].data = newVal;
            }
        },
        { deep: true }
    );

    // 监听标题变化
    watch(
        () => props.title,
        (newVal) => {
            options.title.text = newVal;
            options.series[0].name = newVal;
        }
    );
</script>
