/**
 * @author xiaoping
 * @email edwardhjp@gmail.com
 * @create date 2017-05-18 09:26:02
 * @modify date 2017-05-19 09:52:34
 * @desc [柱状图options]
*/

import {
  setInitOpts, setUndef, setAxis, setLabel, setItem
} from '@/utils/options'

const setBg = (series, options) => {
  let data = series.data.slice(0)
  let max = 0
  data.forEach(v => {
    if (v[1] > max) max = v[1]
  })
  max = max * 1.2 // 比最多更大一点
  let ret = JSON.parse(JSON.stringify(series))
  ret.z = 1
  ret.label.normal.show = false
  ret.itemStyle.normal.color = options.bgColor
  ret.data = data.fill(max)
  return ret
}

// 设置图表系列
const setSeries = (ret, options) => {
  ret.series = [] // clear old series
  options.series = options.series || []
  if (!Array.isArray(options.series)) {
    options.series = [options.series]
  }
  options.series.forEach((item, index) => {
    let temp = Object.assign({}, item, {
      type: item.type || 'bar',
      silent: setUndef(item.silent, true),
    })
    temp.label = setLabel(item)
    temp.itemStyle = setItem(item)
    ret.series.push(temp)
  })
}

// 设置图表数据
const setData = (ret, options) => {
  ret.delZero = setUndef(options.delZero, true) // 删除0数据
  ret.showBg = options.showBg || false // 设置背景
  if (options.datas) {
    let datas = {}
    if (Array.isArray(options.datas)) { // 如果是array就是series的data
      datas.series = options.datas
    } else {
      datas = options.datas
    }
    if (datas.series) {
      datas.series.forEach((data, index) => {
        let temp = ret.series[index]
        if (temp) {
          if (ret.delZero) {
            data = data.filter(item => item.value !== 0)
          }
          temp.data = data
        }
      })
      if (ret.showBg && datas.series.length === 1) {
        let tempBg = setBg(ret.series[0], options)
        ret.series.push(tempBg)
      }
    }
    if (datas.xAxis) {
      ret.xAxis.data = datas.xAxis
    } else if (!datas.xAxis && ret.xAxis.type === 'category') {
      ret.xAxis.data = datas.series[0].map(item => item[0])
    }
    if (datas.yAxis) {
      ret.yAxis.data = datas.yAxis
    } else if (!datas.yAxis && ret.yAxis.type === 'category') {
      ret.yAxis.data = datas.series[0].map(item => item[1])
    }
  }
}

const setOptions = (options) => {
  let ret = setInitOpts(options)
  setAxis(ret, options)
  setSeries(ret, options)
  setData(ret, options)
  return options.custom ? options : ret
}

export {
  setOptions,
}
