import Echarts from 'echarts'

export default {
  data() {
    return {
      $__chart: null,
      $__el: null,
      registeredEvents: []
    }
  },
  watch: {
    option: function(val) {
      this.$__setOptions()
    },
    events: {
      deep: true,
      handler: '$__eventProxy'
    }
  },
  mounted() {
    this.$__initChart()
  },
  created() {

  },
  methods: {
    $__initChart() {
      this.$__el = this.$refs.chart
      this.$__chart = Echarts.init(this.$__el, 'macarons')
      this.$__setOptions()
      this.$__eventProxy()
    },
    $__setOptions() {
      if (this.$__chart) {
        this.$__chart.clear()
        let empty = false
        // 判断暂无数据
        if (!this.series) {
          empty = true
        } else {
          if (Array.isArray(this.series)) {
            let allEmpty = true
            for (let i = 0; i < this.series.length; i++) {
              const element = this.series[i]
              if (element.data && element.data.length > 0) {
                allEmpty = false
                break
              }
            }
            empty = allEmpty
          } else {
            if (!this.series.data || (Array.isArray(this.series.data) && this.series.data.length === 0)) {
              empty = true
            }
          }
        }

        if (empty) {
          const baseOption = {
            title: {
              textStyle: {
                color: 'grey',
                fontSize: 20
              },
              text: '暂无数据',
              left: 'center',
              top: 'center'
            }

          }
          this.$__chart.setOption(baseOption)
        } else {
          this.$__chart.setOption(this.option)
        }
      }
    },
    $__eventProxy() {
      // 只要用户添加events 时间，都使用on 方法绑定事件
      // 是否真正执行取决于该方法是否存在于echarts events中
      const self = this
      const keys = Object.keys(this.events || {})
      keys.length && keys.forEach(ev => {
        if (this.registeredEvents.indexOf(ev) === -1) {
          this.registeredEvents.push(ev)
          this.$__chart.on(ev, (function(ev) {
            return function(...args) {
              if (ev in self.events) {
                self.events[ev].apply(null, args)
              }
            }
          })(ev))
        }
      })
    }
  },
  beforeDestroy() {
    this.$__chart.dispose()
  }
}
