<template>
  <div class="custom-chart" ref="containerRef" :style="{ height: height + 'px' }"></div>
</template>
<script>
import * as echarts from 'echarts'
import 'echarts-gl'

const events = ['click', 'brushEnd']
const zrEvents = ['mousemove', 'mousedown', 'mouseup', 'click']
export default {
  props: {
    option: {
      type: Object,
      default: () => ({})
    },
    height: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {}
  },
  mounted() {
    this._chart = echarts.init(this.$refs.containerRef)
    this._chart.setOption(this.option)
    this.initEventListener()
  },
  destroyed() {
    if(this._chart) {
      this._chart.dispose()
    }
  },
  methods: {
    initEventListener() {
      events.forEach(eventName => {
        this._chart.on(eventName, params => {
          this.$emit(eventName, params)
        })
      })

      const zr = this.getZRender()
      zrEvents.forEach(eventName => {
        zr.on(eventName, params => {
          this.$emit(`zr:${eventName}`, params)
        })
      })
    },

    resize() {
      this._chart && this._chart.resize()
    },

    // 获取echart实例
    getChartInstance() {
      return this._chart
    },

    getZRender() {
      return this._chart.getZr()
    }
  },
  watch: {
    option: {
      handler() {
        if (this._chart) {
          this._chart.setOption(this.option)
        }
      },
      deep: true
    },
    height() {
      this.$nextTick(() => {
        this._chart && this._chart.resize()
      })
    }
  }
}
</script>
<style lang="less" scoped>
.custom-chart {
  height: 100% !important;
}
</style>
