/* 基本饼状图 */
import Echart from '../echart'
import getOption from '../../libs/get_option'

class Pie extends Echart {
  constructor(layer, screen) {
    super(layer, screen)
    this.data = []
    this.colors = []
  }

  setPaint() {
    let paint = this._initPaint()
    let option = this._getOption(paint)
    this._render(option)
  }

  _getOption(paint) {
    let option = getOption(paint, this.type)
    for (let i = 0; i < option.series.length; i++) {
      option.series[i].data = this.data[i]
      this.data[i].forEach(d => {
        // 更新图例
        if (option.legend.data.indexOf(d.name) === -1) {
          option.legend.data.push(d.name)
        }
      })
    }
    return option
  }

  reduceData(paint) {
    if (!paint.series || !this.originalData || !this.originalData.length) {
      this.data = []
      return
    }
    this.colors = paint.colors || []
    let result = []
    let series = paint.series
    series.forEach(s => {
      let t = []
      let colorIndex = 0
      if (s.fields) {
        let data = this.originalData[0]
        s.fields.forEach(f => {
          t.push({
            name: f,
            value: data[f] || 0,
            itemStyle: {
              color: this.colors[colorIndex]
            }
          })
          colorIndex++
        })
      } else if (
        (s.nameField && s.valueField) ||
        (this.originalData[0].name && this.originalData[0].value)
      ) {
        let nameField = s.nameField || 'name'
        let valueField = s.valueField || 'value'
        this.originalData.forEach(d => {
          t.push({
            name: d[nameField] || '',
            value: d[valueField] || 0,
            itemStyle: {
              color: this.colors[colorIndex]
            }
          })
          colorIndex++
        })
      } else {
        for (let key in this.originalData[0]) {
          if (typeof +this.originalData[0][key] === 'number') {
            t.push({
              name: key,
              value: this.originalData[0][key],
              itemStyle: {
                color: this.colors[colorIndex]
              }
            })
            colorIndex++
          }
        }
      }
      result.push(t)
    })
    this.data = result
  }
}

export default Pie
