<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 { collectionStatistics } from "./echarts.js";
// 柱状图初始数据
export default {
  props: {
    // 柱状图生成所需id
    id: {
      type: String,
      default: "collection_ecahrt",
    },
    // 柱状图额外的数据
    option: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      myChart: null, //柱状图实例
    };
  },
  mounted() {
    // 柱状图dom
    const chartDom = document.getElementById(this.id);
    // 柱状图初始化
    this.myChart = markRaw(echarts.init(chartDom));
    collectionStatistics.xAxis.data = this.option.time;
    collectionStatistics.series[0].data = this.option.data1;
    collectionStatistics.series[1].data = this.option.data2;
    // collectionStatistics.series[1].name = this.option.kg;
    // collectionStatistics.legend.data[1] = this.option.kg;
    collectionStatistics.yAxis[0].name = this.option.kg;
    // 生成柱状图
    this.myChart.setOption(collectionStatistics);
    // 监听页面缩放 防止dom重复渲染
    window.addEventListener("resize", _.debounce(this.handle, this.desc));
  },
  watch: {
    // 监听数据变化，重绘折线图
    option: {
      deep: true,
      handler(newVal) {
        const chartDom = document.getElementById(this.id);
        // 先移除之前的实例，保证重绘的流畅性
        // console.log(newVal, "11111");
        chartDom.removeAttribute("_echarts_instance_");
        this.myChart = markRaw(echarts.init(chartDom));
        collectionStatistics.xAxis.data = newVal.time;
        collectionStatistics.series[0].data = newVal.data1;
        collectionStatistics.series[1].data = newVal.data2;
        // collectionStatistics.series[1].name = newVal.kg;
        // collectionStatistics.legend.data[1] = newVal.kg;
        collectionStatistics.yAxis[0].name = newVal.kg;
        this.myChart.setOption(collectionStatistics);
      },
    },
  },
  destroyed() {
    // 销毁实例和移除监听
    this.myChart.dispose();
    window.removeEventListener("resize", this.handle);
  },
  methods: {
    /**
     * @description: 图形缩放
     * @param {*}
     * @return {*}
     */
    handle() {
      this.myChart.resize();
    },
  },
};
</script>
<style lang="scss" scoped>
.ChartsBar {
  background: #ffffff;
}
</style>
