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

<script>
import * as echarts from "echarts";
import resize from "../../../../dashboard/mixins/resize";
export default {
  mixins: [resize],
  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 source = [
        [
          "product",
          "停电总时长目标",
          "预安排停电总时长目标",
          "故障停电总时长目标",
        ],
      ];
      (data || []).forEach((e, i) => {
        legend.push(e.companyName);
        source.push([
          e.companyName,
          e.stopTimeTotal ?? 0,
          e.planStopTimeTotal ?? 0,
          e.errorStopTimeTotal ?? 0,
        ]);
      });
      let myChart = echarts.getInstanceByDom(document.getElementById(this.id));
      if (myChart == null) {
        myChart = echarts.init(document.getElementById(this.id));
      }
      // 指定图表的配置项和数据
      var option = {
        legend: {
          type: "scroll",
          top: "8%",
        },
        grid: {
          left: "1%",
          right: "3%",
          bottom: "1%",
          containLabel: true,
        },
        tooltip: {},
        dataset: {
          source: source,
        },
        xAxis: { type: "category" },
        yAxis: {},
        // Declare several bar series, each will be mapped
        // to a column of dataset.source by default.
        series: [{ type: "bar" }, { type: "bar" }, { type: "bar" }],
      };
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
      setTimeout(() => {
        myChart.resize();
      }, 100);
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },
  },
};
</script>

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