<template>
  <div ref="barChart" :id="id" :style="{ height: height, width: width }"></div>
</template>

<script>
import * as echarts from "echarts";
export default {
  props: {
    chartOptions: {
      type: Object,
      default: () => {},
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "200px",
    },
    id: {
      type: String,
      default: "barChart",
    },
  },
  mounted() {
    // this.initEcharts();
  },
  watch: {
    chartOptions: {
      handler(newVal, oldVal) {
        this.initEcharts();
      },
      // 这里的deep是深度监听，因为我们传递过来的是一个对象
      deep: true,
    },
  },
  methods: {
    initEcharts(data, title) {
      let legend = [];
      let series = [];
      (data || []).forEach((e, i) => {
        legend.push(e.companyName);
        series.push(
          {
            name: `${e.companyName}目标值`,
            type: "line",
            stack: "Total",
            data: Array(12)
              .fill(0)
              .map((it, ii) => {
                return e[`${this.id}${ii < 10 ? "0" + (ii + 1) : ii + 1}`] || 0;
              }),
          },
          {
            name: `${e.companyName}实际值`,
            type: "line",
            stack: "Total",
            data: Array(12)
              .fill(0)
              .map((it, ii) => {
                return e[`${this.id}${ii < 10 ? "0" + (ii + 1) : ii + 1}`] || 0;
              }),
          }
        );
      });
      let myChart = echarts.getInstanceByDom(document.getElementById(this.id));
      if (myChart == null) {
        myChart = echarts.init(document.getElementById(this.id));
      }
      // 指定图表的配置项和数据
      var option = {
        tooltip: {
          trigger: "axis",
        },
        textStyle: {
          color: "#fff",
        },
        legend: {
          data: legend,
          type: "scroll",
          top: "8%",
          textStyle: {
            color: "#fff",
          },
        },
        grid: {
          left: "1%",
          right: "3%",
          bottom: "0%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: Array(12)
            .fill(0)
            .map((it, i) => `${i + 1}月`),
        },
        yAxis: {
          type: "value",
        },
        series: series,
      };
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option, true);
      setTimeout(() => {
        myChart.resize();
      }, 100);
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
