/**
 * @author xiaoping
 * @email edwardhjp@gmail.com
 * @create date 2017-05-18 09:26:02
 * @modify date 2017-05-19 09:54:22
 * @desc [折线图options]
*/

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

// 设置图表系列
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 || 'line',
      silent: setUndef(item.silent, true),
      smooth: setUndef(item.smooth, true),
    })
    temp.label = setLabel(item)
    temp.itemStyle = setItem(item)
    ;['lineStyle', 'areaStyle'].forEach(key => {
      temp[key] = setOthers(item, key, 'line')
    })
    ret.series.push(temp)
  })
}

// 设置图表数据
const setData = (ret, options) => {
  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) {
          temp.data = data
        }
      })
    }
    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,
}
