<template>
  <div :id="id" :style="[{ height: height }, { width: width }]"></div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  props: {
    id: {
      // 必填，图表唯一标识符避免id冲突不渲染
      type: String,
      default: 'chart'
    },
    width: {
      type: [String, Number],
      default: '100%'
    },
    height: {
      type: [String, Number],
      default: '100%'
    },
    option: {
      // 配置文件
      type: [Object],
      default: () => {}
    }
  },
  watch: {
    option: {
      handler(val) {
        this.$nextTick(() => {
          setTimeout(() => this.chart.setOption(val), 20)
        })
      },
      immediate: true,
      deep: true
    }
  },
  data() {
    return {
      chart: '',
      config: {}
    }
  },
  mounted() {
    const self = this
    setTimeout(() => self.drawChart(), 10) // 立即加载不会触发动画
    // 监听窗口发生变化，resize组件
    window.addEventListener('resize', self.handleResizeChart)
  },
  unmounted() {
    window.removeEventListener('resize', self.handleResizeChart)
  },
  methods: {
    drawChart() {
      this.config = Object.assign(this.option)
      // 基于准备好的dom，初始化echarts实例
      // echarts.registerMap('lincang',yn)
      this.chart = echarts.init(document.getElementById(this.id))
      this.chart.setOption(this.config, true)

      // 绑定点击事件
      this.chart.on('click', params => {
        // console.log(params)
        this.$emit('clickItem', params)
      })
    },
    handleResizeChart() {
      this.chart.resize()
    }
  },
  components: {}
}
</script>