<template>
  <div class="pie-chart" />
</template>

<script>
import echarts from 'echarts'

import { debounce } from '@/utils'
export default {
  props: {
    data: {
      type: Array,
      default: () => [
        {
          value: 3142,
          name: '餐厅',
          itemStyle: {
            color: '#82f3e2'
          }
        },
        {
          value: 20,
          name: '其他',
          itemStyle: {
            color: '#f66c7c'
          }
        }
      ]
    }
  },
  data() {
    return {}
  },
  computed: {
    /**
     * 仅用作两组数据的饼图
     */
    option() {
      return {
        title: {
          show: false,
          text: '1150',
          textStyle: {
            fontSize: 22,
            color: '#febb19'
          },
          subtext: '车位总数',
          subtextStyle: {
            fontSize: 14
          },
          // textAlign: 'center',
          textVerticalAlign: 'top',
          left: 'center',
          top: 'center'
        },
        tooltip: {
          trigger: 'item',
          textStyle: {
            fontSize: 18
          }
        },
        legend: {
          show: true,
          orient: 'vertical',
          left: '50%',
          top: 'center',
          icon: 'rect',
          itemGap: 20,
          itemWidth: 15,
          itemHeight: 15,
          formatter: (param) => {
            let value = ''
            for (const item of this.data) {
              if (item.name === param) {
                value = item.value
                break
              }
            }
            return `${param}  {val|${value}}`
          },
          textStyle: {
            rich: {
              val: {
                fontWeight: 600,
                fontSize: 16
              }
            }
          }
        },
        series: [
          {
            // name: 'Access From',
            type: 'pie',
            radius: ['50%', '80%'],
            center: ['25%', '50%'],
            avoidLabelOverlap: false,
            label: {
              show: false
            },
            labelLine: {
              show: false,
              showAbove: false,
              length: 12,
              length2: 30,
              minTurnAngle: 90,
              maxSurfaceAngle: 90,
              lineStyle: {
                width: 2
              }
            },
            data: this.data
          }
        ]
      }
    }
  },
  watch: {
    option: {
      handler: function() {
        this.debounceInitChart()
      },
      deep: true
    }
  },
  created() {
    this.debounceInitChart = debounce(this.initChart, 500)
  },
  mounted() {
    this.debounceInitChart()
  },
  methods: {
    initChart() {
      this.$nextTick(function() {
        const myChart = echarts.init(this.$el)
        myChart.setOption(this.option)
        window.addEventListener('resize', () => {
          myChart.resize()
        })
      })
    }
  }
}
</script>

<style lang='scss' scoped>
.pie-chart {
  width: 100%;
  height: 100%;
}
</style>
