/**
 * @author xiaoping
 * @email edwardhjp@gmail.com
 * @create date 2017-05-04 02:07:08
 * @modify date 2017-05-19 09:55:00
 * @desc [饼图options]
 */

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

const setRoseType = (series, roseType) => {
  if (roseType === 'ring') {
    series.roseType = false
    series.radius = ['50%', '75%']
  } else {
    series.roseType = roseType
    series.radius = ['0%', '75%']
  }
}

// 设置图表参数
const setProps = (ret, options) => {
  ret.autoPlay = options.autoPlay || false
  ret.playDuration = options.playDuration || 1000
}

// 设置图表系列
const setSeries = (ret, options) => {
  let item = options.series || {}
  ret.series[0] = Object.assign({}, item, {
    type: item.type || 'pie',
    silent: setUndef(item.silent, true),
    avoidLabelOverlap: setUndef(item.avoidLabelOverlap, true),
    stillShowZeroSum: setUndef(item.stillShowZeroSum, true),
  })
  setRoseType(ret.series[0], item.roseType)
  ret.series[0].label = setLabel(item)
  ret.series[0].itemStyle = setItem(item)
  ret.series[0].labelLine = setOthers(item, 'labelLine', 'pie')
}

// 设置图表数据
const setData = (ret, options) => {
  ret.series[0].data = [] // 初始化data
  if (options.datas) {
    let datas = {}
    if (Array.isArray(options.datas)) { // 如果是array就是series的data
      datas.series = options.datas
    } else {
      datas = options.datas
    }
    if (datas.series) {
      let data = datas.series || []
      let series = ret.series[0]
      let showPercent = series.showPercent || false
      let sum = data.reduce((prev, next) => {
        return prev + next.value
      }, 0)
      series.data = data.map(item => {
        let fixed = series.percentFixed || 1
        let percent = showPercent ? `(${(item.value / sum * 100).toFixed(fixed)}%)` : ''
        return {
          name: `${item.name}${percent}`,
          value: item.value,
        }
      })
    }
  }
}

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

export {
  setOptions
}
