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

class Bar extends Echart {
  constructor(layer, screen) {
    super(layer, screen)
    this.data = {
      xData: [],
      seriesData: []
    }
  }
  /**
   * 传入已经处理的表格数据，更新图表视图
   */
  setPaint() {
    let paint = this._initPaint()
    let option = this._getOption(paint)
    this._render(option)
  }

  _getOption(paint) {
    let option = getOption(paint, this.type)
    option.xAxis.data = this.data.xData || []
    let subType = paint.style
    if (subType === 'overlay') {
      // 堆叠柱状图
      for (let i = 0; i < option.series.length; i++) {
        option.series[i].stack = 'total'
        option.series[i].data = this.data.seriesData[i] || []
        option.legend.data.push(option.series[i].name)
      }
    } else if (subType === 'percent_overlay') {
      let seriesCount = option.series.length
      let totalData = []
      option.yAxis.max = 100
      this.data.xData.forEach((d, j) => {
        let total = 0
        for (let i = 0; i < seriesCount; i++) {
          total += this.data.seriesData[i][j]
        }
        totalData.push(total)
      })
      for (let i = 0; i < seriesCount; i++) {
        let seriesData = this.data.seriesData[i].map((item, index) =>
          Number((item / totalData[index]) * 100).toFixed(2)
        )
        option.series[i].stack = 'percent'
        option.series[i].data = seriesData || []
        option.legend.data.push(option.series[i].name)
      }
    } else {
      for (let i = 0; i < option.series.length; i++) {
        option.series[i].data = this.data.seriesData[i] || []
        option.legend.data.push(option.series[i].name)
      }
    }
    return option
  }

  /**
   * 根据paint属性中指定的字段，将表格数据处理成图表组件需要的格式
   */
  reduceData(paint) {
    if (!this.originalData || !this.originalData.length) {
      this.data = {
        xData: [],
        seriesData: []
      }
      return
    }
    if (paint.xAxis && paint.xAxis.field) {
      let xField = paint.xAxis.field
      this.data.xData = util.pickColData(xField, this.originalData)
    }

    let series = paint.series
    let seriesData = []
    series.forEach(s => {
      let t = []
      if (s.field) {
        t = util.pickColData(s.field, this.originalData)
      }
      seriesData.push(t)
    })
    this.data.seriesData = seriesData
  }
}

export default Bar
