<template>
  <div :id="id" :class="className" :style="{ height: height, width: width }" />
</template>
  
  <script>
  import * as echarts from 'echarts';

  export default {
    name: 'TheEchart',
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      id: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '100%'
      },
      options: {
        type: Object,
        default: ()=>({})
      }
    },
    data () {
      return {
        chart: null
      }
    },
    watch: {
      options: {
        handler (options) {
          this.chart.showLoading({
            text: 'loading',
            color: 'rgba(84, 112, 198, .95)',
            textColor: '#fff',
            maskColor: 'rgba(255, 255, 255, 0.2)',
            zlevel: 0,
          });
          setTimeout(() => {
            // setOption前隐藏loading事件 
            this.chart.hideLoading();
            this.chart.setOption(options, true)
          }, 500)
  
          // 设置true清空echart缓存
          // this.chart.setOption(options, true)
        },
        deep: true
      }
    },
    mounted () {
      console.log(this.id);
      this.initChart();
    },
    beforeDestroy () {
      this.chart.dispose()
      this.chart = null

      // 销毁监听事件
      window.removeEventListener('resize', this.resizeHandler)
      // 销毁 Echarts 实例
      this.chart.dispose()
    },
    methods: {
      initChart () {
        // 初始化echart
        this.chart = echarts.init(this.$el)
  
        this.chart.showLoading({
          text: 'loading',
          color: 'rgba(84, 112, 198, .95)',
          textColor: '#fff',
          maskColor: 'rgba(255, 255, 255, 0.2)',
          zlevel: 0,
        });

        setTimeout(() => {
          // setOption前隐藏loading事件 
          this.chart.hideLoading();
          this.chart.setOption(this.options, true)
        }, 500)
        
        this.chart.on('click', event => {
          this.$emit('chartClick', event)
        })

        // 绑定监听事件
        window.addEventListener('resize', this.resizeHandler)
      },

      // Echarts 的 resize 方法
      resizeHandler() {
        this.chart.resize()
      }
    }
  }
  </script>
  
  <style>
  </style>
  