<template>
  <div ref="chart" :style="{ width: width, height: height }" />
</template>

<script>
// import echarts from "echarts";
import echarts from 'echarts/lib/echarts'
import 'echarts/lib/chart/pie'
import 'echarts/lib/component/legend'
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    items: {
      type: Array,
      default: () => {
        return []
      }
    },
    title: {
      type: String,
      default: ''
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100%'
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    items: function() {
      if (this.chart) {
        var options = this.generateOptions()
        this.chart.setOption(options)
      }
    }
  },
  mounted() {
    this.chart = echarts.init(this.$refs.chart)
    var options = this.generateOptions()
    this.chart.setOption(options)

    this.chart.on('click', params => {
      console.log(params, '90909')
      this.$emit('echartClick', params)
    })
  },
  methods: {
    generateOptions() {
      var total = this.items
        .map(t => t.value)
        .reduce((prev, cur) => {
          return prev + cur
        }, 0)

      return {
        color: ['rgba(255,34,34,0.7)', 'rgba(0,123,255,0.7)', 'rgba(15,187,91,0.7)'],
        tooltip: {
          show: false
        },
        legend: {
          show: false
        },
        series: [
          {
            silent: true,
            name: '总数',
            type: 'pie',
            radius: ['85%', '100%'],
            center: ['50%', '50%'],
            color: '#eeeeee',
            label: {
              normal: {
                show: false
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data: [{ value: total, name: '总数', selected: false }]
          },
          {
            animation: false,
            name: this.title,
            type: 'pie',
            center: ['50%', '50%'], // 默认全局居中
            radius: ['0%', '85%'],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false,
                position: 'center'
              },
              emphasis: {
                show: false
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            itemStyle: {
              emphasis: {
                show: false
              }
            },
            data: this.items
          }
        ]
      }
    }
  }
}
</script>
