<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import echarts from 'echarts'
import resize from '@/components/Chart/mixins/resize'
import theme from '@/components/Chart/mixins/theme'
import { ColorDefines } from './colors'

export default {
  mixins: [resize, theme],
  props: {
    items: {
      type: Array,
      default: function() {
        return []
      }
    },
    loading: {
      type: Boolean,
      default: false
    },
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    title: {
      type: String,
      default: ''
    },
    xAxisRotate: {
      type: Number,
      default: 0
    },
    colors: {
      type: Array,
      default: () => []
    },
    labelSize: {
      type: String,
      default: 'small'
    },
    showToolBox: {
      type: Boolean,
      default: false
    },
    center: {
      type: Array,
      default: () => ['50%', '62%']
    },
    legendPosition: {
      type: String,
      default: 'top'
    },
    showLengend: {
      type: Boolean,
      default: true
    },
    innerRadius: {
      type: Array,
      default: () => [0, '30%']
    },
    outterRadius: {
      type: Array,
      default: () => ['35%', '53%']
    },
    labelLineLengths: {
      type: Array,
      default: () => [10, 5]
    },
    innerTitle: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      chart: null,
      chartOptions: null
    }
  },
  watch: {
    items(value) {
      this.loadChartData(value)
    },
    loading(value) {
      if (value) {
        this.showLoading()
      } else {
        this.hideLoading()
      }
    }
  },
  mounted() {
    this.chart = echarts.init(this.$el, 'customed')
    this.loadChartData(this.items)
    this.chart.on('click', params => {
      this.$emit('click', params)
    })
  },
  methods: {
    showLoading() {
      this.chart.showLoading()
    },
    hideLoading() {
      this.chart.hideLoading()
    },
    loadChartData(chartData) {
      this.chartOptions = this.generateOptions(chartData)
      this.chart.setOption(this.chartOptions)
    },
    getLabelOption() {
      var labelOption = {}
      if (this.labelSize === 'normal') {
        labelOption = {
          formatter: function(params) {
            return `  {b|${params.name}: ${params.value}} {per|${params.percent}%} `
          },
          backgroundColor: '#fff',
          borderColor: '#aaa',
          borderWidth: 1,
          borderRadius: 4,
          rich: {
            b: {
              fontSize: 14,
              lineHeight: 33
            },
            per: {
              fontSize: 14,
              lineHeight: 33,
              color: '#fff',
              backgroundColor: '#334455',
              padding: [2, 4],
              borderRadius: 2
            }
          }
        }
      } else if (this.labelSize === 'small') {
        labelOption = {
          formatter: function(params) {
            return `{b|${params.name}:${params.value}}\n{b|${params.percent}%}`
          },
          fontSize: 12,
          rich: {
            b: {
              align: 'center'
            }
          }
        }
      }

      return labelOption
    },
    getLengend(rawData) {
      var legendSelected = {}
      // rawData.forEach(t => {
      //   legendSelected[t.name] = t.value > 0;
      // });
      // var total = rawData
      //   .map(t => t.value)
      //   .reduce((prev, cur) => {
      //     return prev + cur;
      //   }, 0);
      var lengend = {
        show: this.showLengend,
        top: this.title ? 30 : 10,
        selected: legendSelected,
        data: rawData.map(i => i.name),
        formatter: name => {
          var item = rawData.find(t => t.name === name)
          // var percent = total ? ((item.value * 100) / total).toFixed(2) : 0;
          return `${name}: ${item.value}`
        }
      }
      if (this.legendPosition === 'left') {
        lengend.x = 'left'
        lengend.orient = 'vertical'
      }
      if (this.legendPosition === 'right') {
        lengend.x = 'right'
        lengend.orient = 'vertical'
      }
      return lengend
    },
    getLabelLine() {
      if (this.labelLineLengths.length) {
        return {
          length: this.labelLineLengths[0],
          length2: this.labelLineLengths[1]
        }
      } else {
        return {}
      }
    },
    generateOptions(rawData) {
      var self = this
      var total = rawData
        .map(t => t.value)
        .reduce((prev, cur) => {
          return prev + cur
        }, 0)

      return {
        color: [
          ColorDefines.redliner,
          ColorDefines.blueliner,
          ColorDefines.greenliner,
          ColorDefines.grayliner,
          ColorDefines.purpleliner,
          ColorDefines.pinkliner
        ],
        animation: true,
        title: {
          text: this.title
        },
        toolbox: {
          show: this.showToolBox,
          feature: {
            saveAsImage: {}
          },
          right: '10px'
        },
        legend: this.getLengend(rawData),
        tooltip: {
          trigger: 'item',
          formatter: this.title ? '{a} <br/>{b}: {c} ({d}%)' : '{b}: {c} ({d}%)'
        },
        series: [
          {
            name: this.title,
            type: 'pie',
            radius: this.innerRadius,
            center: this.center,
            color: !this.isMonitor ? '#fff' : 'rgba(0,0,0,0)',
            label: {
              normal: {
                formatter: function(params) {
                  return self.innerTitle ? self.innerTitle : `总数(${total})`
                },
                color: !this.isMonitor ? '#000' : '#fff',
                fontSize: this.isMonitor ? 12 : 16,
                show: true,
                position: 'center'
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data: [{ value: total, name: '总数', selected: false }]
          },
          {
            name: this.title,
            type: 'pie',
            radius: this.outterRadius,
            center: this.center,
            label: {
              show: false
              // normal: this.getLabelOption()
            },
            labelLine: this.getLabelLine(),
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            data: rawData
          }
        ]
      }
    }
  }
}
</script>
