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

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

const props = defineProps({
    chartData: {
        type: Object,
        default: () => ({
            xAxisData: [],
            series: [],
        }),
    },
});

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

const initData = () => {
    const newOption = deepClone(lineOption);
    
    // 如果有传入数据，使用传入的数据
    if (props.chartData && props.chartData.xAxisData && props.chartData.xAxisData.length > 0) {
        newOption.xAxis.data = props.chartData.xAxisData;
        newOption.series = props.chartData.series;
    } else {
        // 数据为空时，清空图表
        newOption.xAxis.data = [];
        newOption.series = [];
    }
    
    // 使用 notMerge: true 完全替换配置，确保切换时正确更新
    myChart.setOption(newOption, { notMerge: true });
};

// 监听数据变化，更新图表
watch(
    () => props.chartData,
    () => {
        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>
.line-chart {
    width: 100%;
    height: 100%;
}
</style>