<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: {
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '500px'
    },
    height: {
      type: String,
      default: '400px'
    },
    title: {
      type: String,
      default: ''
    },
    desc: {
      type: String,
      default: ''
    },
    showTitle: {
      type: String,
      default: ''
    },
    seriesData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      chart: null
    }
  },
  computed: {
    legendData() {
      console.log(this.seriesData)
      const data = Object.assign([], this.seriesData)
      const out = []
      data.map(item => {
        out.push(item.name)
      })
      return out
    }
  },
  watch: {
    seriesData: {
      handler(newVal, oldVal) {
        this.initChart()
      },
      deep: true
    }
  },
  mounted() {
    this.initChart()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(document.getElementById(this.id))
      this.chart.clear()
      this.chart.setOption({
        title: {
          text: this.title,
          subtext: this.desc,
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        series: {
          name: this.showTitle,
          type: 'pie',
          radius: '50%',
          center: ['50%', '60%'],
          data: this.seriesData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      })
      window.onresize = this.chart.resize
    }
  }
}
</script>

