<template>
  <div
    style="height: 100%; width: 100%; position: absolute; left: 0; top: 0"
    class="ChartsBar"
    :id="id"
  ></div>
</template>

<script>
import { markRaw } from "vue";
import * as echarts from "echarts";
import * as _ from "lodash";
import { collection } from "./echarts.js";
// 柱状图初始数据
export default {
  props: {
    // 柱状图生成所需id
    id: {
      type: String,
      default: "collection_ecahrt",
    },
    // 柱状图额外的数据
    option: {
      type: Object,
      default: () => {},
    },
    options: {
      type: Array,
      default: () => {},
    },
  },
  data() {
    return {
      myChart: null, //柱状图实例
    };
  },
  mounted() {
    // 柱状图dom
    const chartDom = document.getElementById(this.id);
    // 柱状图初始化
    this.myChart = markRaw(echarts.init(chartDom));
    collection.xAxis.data = this.option.time;
    // this.option.list.forEach((item, index) => {
    //   collection.series.push({
    //     name: "",
    //     type: "bar",
    //     // barWidth: 18,
    //     data: item,
    //   });
    // });
    // collection.series[0].data = this.option.data1;
    // 生成柱状图
    this.myChart.setOption(collection);
    // 监听页面缩放 防止dom重复渲染
    window.addEventListener("resize", _.debounce(this.handle, this.desc));
  },
  watch: {
    // 监听数据变化，重绘折线图
    option: {
      deep: true,
      handler(newVal) {
        collection.series = [];
        const chartDom = document.getElementById(this.id);
        // 先移除之前的实例，保证重绘的流畅性
        chartDom.removeAttribute("_echarts_instance_");
        this.myChart = markRaw(echarts.init(chartDom));
        collection.xAxis.data = newVal.time;
        let arr = JSON.parse(JSON.stringify(newVal.list));
        for (let index = 0; index < arr.length; index++) {
          collection.series.push({
            name: this.options[index],
            type: "bar",
            // barWidth: 18,
            data: arr[index],
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: "top",
                  textStyle: {
                    color: "black",
                    fontSize: 12,
                  },
                },
              },
            },
          });
        }
        this.myChart.setOption(collection);
      },
    },
  },
  destroyed() {
    // 销毁实例和移除监听
    this.myChart.dispose();
    window.removeEventListener("resize", this.handle);
  },
  methods: {
    /**
     * @description: 图形缩放
     * @param {*}
     * @return {*}
     */
    handle() {
      this.myChart.resize();
    },
  },
};
</script>
