<template>
  <div
    :style="{ width: width, height: height }"
    ref="baseEchartRef"
    id="baseEchart"
    v-on-echart-resize
  ></div>
</template>

<script>
import * as echarts from "echarts";
import elementResizeDetectorMaker from "element-resize-detector";
import "../aJs/chart.resize";
export default {
  props: {
    width: {
      type: String,
      default: "100%"
    },
    height: {
      type: String,
      default: "300px"
    },
    option: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    option() {
      this._initEchart();
    }
  },
  mounted() {
    // this.$nextTick(() => {
    //   setTimeout(() => {
    //     this._initEchart()
    //   },0)
    // })
    this._initEchart()
    let erd = elementResizeDetectorMaker();
    let that = this;
    erd.listenTo(document.getElementById("baseEchart"), (element) => {
      // let width = element.offsetWidth;
      // let height = element.offsetHeight;
      that.$nextTick(() => {
        //使echarts尺寸重置
        echarts.init(document.getElementById("baseEchart")).resize();
      });
    });
  },
  computed: {

  },
  methods: {
     _initEchart() {
      let that=this
      const echartInstance = echarts.init(this.$refs.baseEchartRef);
      echartInstance.setOption(this.option);
      echartInstance.on('legendselectchanged', function (params) {
        if(that.option.name=='barOption'){
          that.$emit('legendselectchanged',params.selected)
        }
      });
      // 监听window尺寸的变化
      // echartInstance.resize();
      // window.addEventListener("resize", () => {
      //   echartInstance.resize();
      // });
    }
  }
};
</script>
<style lang="less" scoped></style>