/* 基本散点图 */
import Echart from '../echart'
import getOption from '../../libs/get_option'

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

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

  _getOption(paint) {
    let option = getOption(paint, this.type)
    option.xAxis.type = 'value'
    for (let i = 0; i < option.series.length; i++) {
      option.series[i].data = this.data[i] || []
      option.legend.data.push(option.series[i].name)
      if (paint.style === 'bubble') {
        // 气泡图
        let dataRange = this._getDataRange(this.data[i])
        let symbolSize = option.series[i].symbolSize
        if (!Array.isArray(symbolSize)) {
          symbolSize = [symbolSize, symbolSize + 10]
        }
        option.series[i].symbolSize = data => {
          return (
            data[1] *
            ((symbolSize[1] - symbolSize[0]) / (dataRange[1] - dataRange[0]))
          )
        }
      }
    }
    return option
  }

  reduceData(paint) {
    if (!this.originalData || !this.originalData.length) {
      this.data = []
      return
    }
    if (!paint.xAxis || !paint.xAxis.field) {
      return
    }

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

  pickData(xField, sField, data) {
    let result = []
    data.forEach(d => {
      result.push([+d[xField], d[sField]])
    })
    return result
  }

  _getDataRange(data) {
    let min = Infinity
    let max = -Infinity
    data.forEach(d => {
      let value = d[1]
      min = Math.min(min, value)
      max = Math.max(max, value)
    })
    return [min, max]
  }
}

export default Scatter
