<template>
    <div ref="chartDom" class="pie-chart"></div>
</template>

<script setup>
import { onMounted, ref, watch, nextTick, onUpdated } from "vue";
import * as echarts from "echarts";
import { pieOption } from "./chartOption.js";
import { deepClone } from "@/common/commonFun";

const props = defineProps({
    chartData: {
        type: Array,
        default: () => [],
    },
    totalArea: {
        type: Number,
        default: 0,
    },
});

const chartDom = ref(null);
let myChart = null;

const initData = () => {
    const newOption = deepClone(pieOption);
    
    // 如果有传入数据，使用传入的数据
    if (props.chartData && props.chartData.length > 0) {
        newOption.series[0].data = props.chartData;
        // 更新总种植面积
        if (props.totalArea > 0) {
            newOption.title.subtext = Math.round(props.totalArea).toString();
            // 更新 tooltip 中的 total
            newOption.tooltip.formatter = function (params) {
                const data = params.data;
                const total = props.totalArea;
                const percent = (data.value / total * 100).toFixed(2);
                return `${params.marker}${data.name}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;${percent}%&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;${Math.round(data.value)}亩`;
            };
        }
    } else {
        // 数据为空时，清空图表
        newOption.series[0].data = [];
        newOption.title.subtext = '0';
        // 恢复默认 tooltip
        newOption.tooltip.formatter = function (params) {
            const data = params.data;
            const total = 3774;
            const percent = (data.value / total * 100).toFixed(2);
            return `${params.marker}${data.name}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;${percent}%&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;${data.value}亩`;
        };
    }
    
    // 使用 notMerge: true 完全替换配置，确保切换时正确更新
    myChart.setOption(newOption, { notMerge: true });
};

// 监听数据变化，更新图表
watch(
    () => [props.chartData, props.totalArea],
    () => {
        if (myChart) {
            nextTick(() => {
                initData();
                // 确保图表正确渲染
                myChart.resize();
            });
        }
    },
    { deep: true }
);

onMounted(() => {
    myChart = echarts.init(chartDom.value);
    initData();
});

// 组件更新后，确保图表正确渲染
onUpdated(() => {
    if (myChart && chartDom.value) {
        nextTick(() => {
            myChart.resize();
        });
    }
});

</script>

<style lang="scss" scoped>
.pie-chart {
    width: 100%;
    height: 100%;
}
</style>