<template>
    <div style="width: 100%;height: 100%" ref="chart" @resize="resize" />
</template>

<script>
import * as echarts from 'echarts';

export default {
  expose: ['setData'],
  props:['defaultOption'],
  data() {
    return {
      chart: null,
      option: null,
      resizeTime:true
    }
  },
  mounted() {
    this.$nextTick(() => {
      const resizeObserver = new ResizeObserver(entries => {
        for (let entry of entries) {
          this.resize()
        }
      });

      resizeObserver.observe(this.$refs.chart);
    });
    window.addEventListener('resize', this.resize)
    if(this.defaultOption){
      this.setData(this.defaultOption)
    }
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
    window.removeEventListener('resize', this.resize)
  },
  methods: {
    setData(option) {
      this.option = option
      this.initChart(option)
    },
    initChart(option) {
      if(!this.chart){
        this.chart = echarts.init(this.$refs.chart, 'macarons')
      }
      this.chart.setOption(option,true)
    },
    resize() {
      if(this.resizeTime){
        this.resizeTime = false
        if (this.option && this.chart) {
          this.chart.resize()
        }
      setTimeout(()=>{
        this.resizeTime = true
      },16)
      }
    },
  }
}
</script>
