<template>
  <div ref="dom" class="charts chart-pie"></div>
</template>

<script>
import echarts from 'echarts'
import { on, off } from '@/libs/tools'
export default {
  name: 'ChartPie',
  props: {
    value: {
      type: Array,
      default () {
        return []
      }
    },
    name: {
      type: Array,
      default () {
        return []
      }
    },
    text: String,
    subtext: String
  },
  computed: {
    pieData () {
      let arr = []
      this.value.forEach((item, index) => {
        arr.push({
          name: this.name[index],
          value: this.value[index]
        })
      })
      // console.log('?????????????????????pie')
      // console.log(arr)
      return arr
    }
  },
  watch: {
    pieData () {
      this.$nextTick(() => {
        // let legend = this.value.map(_ => _.name)
        let option = {
          title: {
            text: this.text,
            subtext: this.subtext,
            x: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{b} : {c} ({d}%)'
          },
          // legend: {
          //   orient: 'vertical',
          //   left: 'left',
          //   data: legend
          // },
          series: [
            {
              type: 'pie',
              radius: '40%',
              color: ['#45C2E0', '#C1EBDD', '#FFC851', '#5A5476', '#1869A0', '#FF9393'],
              center: ['50%', '50%'],
              data: this.pieData,
              itemStyle: {
                emphasis: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                },
                normal: {
                  label: {
                    show: true,
                    formatter: '{b} ({d}%)'
                  },
                  labelLine: { show: true }
                }
              }
            }
          ]
        }
        this.dom = echarts.init(this.$refs.dom)
        this.dom.setOption(option)
        this.dom.dispatchAction({
          type: 'highlight',
          seriesIndex: 0,
          dataIndex: 0// 默认选中第二个
        })
        on(window, 'resize', this.resize)
      })
    }
  },
  data () {
    return {
      dom: null
    }
  },
  methods: {
    resize () {
      this.dom.resize()
    }
  },
  mounted () {

  },
  beforeDestroy () {
    off(window, 'resize', this.resize)
  }
}
</script>
