<template>
  <div ref="chartDom" style="width: 100%; height: 100%"></div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "LineChart",
  props: {
    xData: {
      type: Array,
      required: true,
    },
    yData: {
      type: Array, // 二维数组
      required: true,
    },
    yNames: {
      type: Array,
      required: true, // 只取第一个元素
    },
    yAxisName: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      myChart: null,
    };
  },
  mounted() {
    this.initChart();
  },
  watch: {
    xData: {
      handler: "initChart",
      deep: true,
      immediate: true,
    },
    yData: {
      handler: "initChart",
      deep: true,
      immediate: true,
    },
    yNames: {
      handler: "initChart",
      immediate: true,
    },
    yAxisName: {
      handler: "initChart",
      immediate: true,
    },
  },

  methods: {
    initChart() {
      if (!this.$refs.chartDom) return;

      if (!this.myChart) {
        this.myChart = echarts.init(this.$refs.chartDom);
      }

      const colors = ["#02aae9", "#5470C6", "#3CB9B9", "#9966CC"]; // 颜色列表可以根据需要扩展

      const series = this.yData.map((data, index) => ({
        name: this.yNames[index] || `系列${index + 1}`,
        type: "line",
        data: data,
        lineStyle: {
          color: colors[index % colors.length],
        },
        itemStyle: {
          color: colors[index % colors.length],
        },
      }));

      const option = {
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: this.yNames.slice(0, series.length),
          top: 10,
        },
        grid: {
          top: 40,
          bottom: 0,
          left: 40,
          right: 20,
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: this.xData,
        },
        yAxis: {
          type: "value",
          name: this.yAxisName,
        },
        series: series,
        color: colors,
      };

      this.myChart.clear(); // ✅ 清除旧配置
      this.myChart.setOption(option);
    },
  },
};
</script>

<style scoped>
</style>
