<template>
  <div class="lineChart" ref="lineChart"></div>
</template>
<script>
export default {
  props: ["chartdata"],
  data() {
    return {};
  },
  watch: {
    chartdata: function (newValue, oldValue) {
      this.$nextTick(() => {
        // 通过 DOM API 更新文本
        if (this.chartdata.length !== 0) {
          this.drawLine();
        }
      });
    },
  },
  mounted() {
    this.$nextTick(() => {
      // 通过 DOM API 更新文本
      console.log(this.chartdata);
      if (this.chartdata.length !== 0) {
        this.drawLine();
      }
    });
  },
  methods: {
    drawLine() {
      console.log("我是曲线图");
      console.log(this.chartdata.points);
      var pointsData = this.chartdata.points;
      var legendData = [];
      var xData = this.chartdata.content.map((item) => item.acquisitionTime);
      var seriseData = [];
      var yAxisData = [];

      for (var i = 0; i < pointsData.length; i++) {
        console.log(pointsData[i]);
        console.log(pointsData[i].name);
        seriseData.push({
          name: pointsData[i].name,
          type: "line",
          yAxisIndex: i,
          data: pointsData[i].data,
          smooth: true,
        });
        legendData.push(pointsData[i].name);
        console.log(legendData);
        yAxisData.push({
          name: pointsData[i].name,
          type: "value",
          position: i % 2 == 0 ? "left" : "right",
          offset: i + 1 <= 2 ? 0 : (Math.ceil((i + 1) / 2) - 1) * 40,
          // 整条y轴
          axisLine: {
            show: true,
          },
          // y轴上的小横线
          axisTick: {
            show: true,
          },
          axisLabel: {
            formatter: "{value}",
          },
        });
      }
      let myChart = this.$echarts.init(this.$refs.lineChart);
      //myChart.removeAttribute("_echarts_instance_"); // 移除容器上的 _echarts_instance
      if (this.$refs.lineChart.hasAttribute("_echarts_instance_")) {
        console.log(this.$refs.lineChart);
        this.$refs.lineChart.removeAttribute("_echarts_instance_");
      }
      // 绘制图表
      myChart.setOption({
        //animation: false,
        legend: {
          data: legendData,
        },
        tooltip: {
          trigger: "axis",
        },
        dataZoom: [
          {
            type: "inside",
            start: 0,
            end: 20,
          },
          {
            start: 0,
            end: 20,
          },
        ],
        xAxis: {
          type: "category",
          name: "时间",
          boundaryGap: false,
          data: xData,
        },
        yAxis: yAxisData,
        series: seriseData,
      });
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },
  },
};
</script>
<style lang="less">
.lineChart {
  width: 100%;
  height: 100%;
}
</style>
