<template>
  <div :id="id" :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    option: {
      type: Object,
      default: () => { return {} }
    },
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '200px'
    },
    height: {
      type: String,
      default: '200px'
    },
    chartData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      handler(newVal, oldVal) {
        if (this.chart) {
          this.initChart(newVal)
        }
      },
      immediate: true
    }

  },
  mounted() {
    this.chart = echarts.init(document.getElementById(this.id))
    this.initChart(this.chartData)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart(chartData) {
      const option = {
        tooltip: {
          trigger: 'item',
          position: [10, 10],
          formatter: '{b}: {c} ({d}%)'
        },
        grid: {
          top: 100,
          left: '2%',
          right: '2%',
          bottom: '2%',
          containLabel: true
        },
        series: [
          {
            name: '',
            type: 'pie',
            data: chartData
          }
        ]
      }
      Object.assign(option, this.option)
      if (this.option.series) {
        option.series[0].data = chartData
        if (this.option.legend) {
          option.legend.data = chartData.map(obj => obj.name)
        }
      }
      this.chart.setOption(option)
    }
  }
}
</script>
