<template>
  <div ref="chart" class="chart"></div>
</template>
<script>
import * as echarts from "echarts";
import { chinaMap } from "../../utils/china.js";
let elementResizeDetectorMaker = require("element-resize-detector");

export default {
  name: "base-chart",
  props: {
    option: {
      type: Object,
      required: true,
    },
    clickFunc: {
      type: Function,
    },
    mouseoverFunc: {
      type: Function,
    },
    hightLightFunc: {
      type: Function,
    },
    legendselectchangedFn: {
      type: Function,
    },
    chartWidthChange: {
      type: Function,
    },
    chartType: {
      type: String,
    },
  },
  data() {
    return {
      chart: null,
      resizeTimeout: null,
      isMouseDown: false,
    };
  },
  mounted() {
    this.$nextTick(() => {
      if (this.chartType === "map") {
        echarts.registerMap("china", { geoJSON: chinaMap });
      }
      this.chart = echarts.init(this.$refs.chart);
      this.setOption(this.option);
      if (this.clickFunc) {
        this.chart.on("click", this.clickFunc);
      }

      if (this.hightLightFunc) {
        this.chart.on("highlight", this.hightLightFunc);
      }
      if (this.legendselectchangedFn) {
        this.chart.on("legendselectchanged", this.legendselectchangedFn);
      }
      if (this.chartWidthChange) {
        this.chartWidthChange(this.chart.getWidth());
      }
    });
    this.erd = elementResizeDetectorMaker();
    this.erd.listenTo(this.$refs.chart, () => {
      //使echarts尺寸重置
      this.resizeThrottler();
    });
  },
  watch: {
    option: {
      handler(val) {
        this.setOption(val);
      },
      deep: true,
    },
  },
  methods: {
    setOption(option) {
      if (this.chart) {
        this.chart.setOption(option, true);
      }
    },
    actualResizeHandler() {
      if (this.chart) {
        this.chart.resize();
        if (this.chartWidthChange) {
          this.chartWidthChange(this.chart.getWidth());
        }
      }
    },
    resizeThrottler() {
      if (!this.resizeTimeout) {
        this.resizeTimeout = setTimeout(() => {
          this.resizeTimeout = null;
          this.actualResizeHandler();
        }, 66);
      }
    },
    mouseDown() {
      this.isMouseDown = true;
    },
    mouseUp() {
      this.isMouseDown = false;
    },
  },
  beforeDestroy() {
    this.erd?.removeAllListeners(this.$refs.chart);
  },
};
</script>
<style lang="scss" scoped>
.chart {
  height: 100%;
  width: 100%;
}
</style>
