<template>
  <div class="main">
    <div
      class="chart"
      ref="chart"
    >
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
export default {
  props: {
    dataList: {
      type: Array,
      default: []
    },
    colorList: {
      type: Array,
      default: []
    }
  },
  watch: {
    dataList: function(val) {
      if (val.length > 0) {
        this.init()
      }
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      const myChart = this.chart || echarts.init(this.$refs.chart);
      let option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          left: 'center',
          bottom: '24',
          itemWidth: 12,
          itemHeight: 12,
          itemGap: 12,
          orient: 'horizontal',
          textStyle: {
            color: '#666666',
            fontSize: 12,
            height: 12,
            padding: [2, 20, 0, 0]
          }
        },
        series: [
          {
            type: 'pie',
            radius: ['60%', '100%'],
            left: 'center',
            height: 200,
            width: 584,
            minAngle: 5,
            bottom: 100,
            top: 50,
            label: {
              alignTo: 'edge',
              edgeDistance: 10,
              minMargin: 5,
              margin: '15%',
              formatter: (params) => {
                return '{a|' + params.name + '}\n{a|' + Math.round(params.percent) + '% ' + params.value + '辆}'
              },
              rich: {
                a: {
                  color: '#333333',
                  fontSize: 14,
                  fontWeight: 500
                }
              },
            },
            labelLine: {
              lineStyle: {
                color: '#B3B3B3'
              },
              length: 15,
              length2: 15
            },
            labelLayout: function(params) {
              var isLeft = params.labelRect.x < myChart.getWidth() / 2;
              var points = params.labelLinePoints;
              // Update the end point.
              points[2][0] = isLeft
                ? params.labelRect.x
                : params.labelRect.x + params.labelRect.width;

              return {
                labelLinePoints: points
              };
            },
            itemStyle: {
              color: (color) => {
                const item = this.colorList.find(i => i.name === color.name)
                return (item && item.color) || '#333333'
              }
            },
            data: this.dataList
          }
        ]
      };
      myChart.setOption(option);
      this.chart = myChart
    }
  }
}
</script>

<style lang="scss" scoped>
.main {
  height: 370px;
  width: 100%;
  .chart {
    width: 100%;
    height: 100%;
  }
}
</style>