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

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

const props = defineProps({
    chartData: {
        type: Object,
        default: () => ({
            categories: [],
            values: [],
        }),
    },
    yAxisFormatter: {
        type: String,
        default: "{value}%", // 默认百分比格式
    },
});

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

const initData = () => {
    const newOption = deepClone(barOption);
    
    // 如果有传入数据，使用传入的数据
    if (props.chartData && props.chartData.categories && props.chartData.categories.length > 0) {
        newOption.xAxis.data = props.chartData.categories;
        newOption.series[0].data = props.chartData.values;
    }
    
    // 更新 yAxis 的 formatter
    newOption.yAxis.axisLabel.formatter = props.yAxisFormatter;
    
    myChart.setOption(newOption);
};

// 监听数据变化，更新图表
watch(
    () => [props.chartData, props.yAxisFormatter],
    () => {
        if (myChart) {
            initData();
        }
    },
    { deep: true }
);

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

</script>

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