/*时间轴*/
import Echart from '../echart'

class TimeLine extends Echart {
  constructor(layer, screen) {
    super(layer, screen)
    this.events = ['year'] // 该组件可以出发year事件
    this.data = []
  }
  /**
   * 传入已经处理的表格数据，更新图表视图
   */
  setPaint() {
    let newPaint = this._mergePaint()
    this.reduceData(newPaint) // 将表格数据处理成图表组件可用的数据
    let options = {
      timeline: this._getOption(newPaint)
    }
    this._render(options)
    this.instance.off('timelinechanged')
    this.instance.on('timelinechanged', e => {
      let index = e.currentIndex
      let currentValue = this.data[index]
      let events = this.layer.events // 绑定的事件
      this.events.forEach(eventName => {
        let alias =
          events && events[eventName] ? events[eventName].alias : eventName
        this._screen.store.patchState(alias, currentValue)
      })
    })
  }

  _getOption(newPaint) {
    let option = {
      axisType: 'category',
      left: 10,
      top: 10,
      show: true,
      symbol: 'circle',
      symbolSize: newPaint.nodeSize,
      autoPlay: newPaint.autoPlay,
      playInterval: newPaint.playInterval,
      orient: newPaint.orient,
      lineStyle: {
        color: newPaint.lineColor,
        type: 'solid',
        width: newPaint.lineWidth
      },
      itemStyle: {
        color: newPaint.nodeColor
      },
      checkpointStyle: {
        symbolSize: newPaint.nodeSize + 2,
        color: newPaint.highlightColor,
        borderColor: newPaint.highlightBorderColor
      },
      controlStyle: {
        color: newPaint.lineColor,
        borderColor: newPaint.lineColor
      },
      label: {
        show: newPaint.showLabel,
        position: this._getLabelPosition(newPaint.nodeSize, newPaint.labelPosition),
        color: newPaint.labelColor,
        fontSize: newPaint.labelSize
      },
      emphasis: {
        itemStyle: {
          color: newPaint.highlightColor
        }
      },
      data: this.data
    }
    if (option.orient === 'vertical') {
      option.bottom = 10
    } else {
      option.top = 20
      option.right = 10
    }
    return option
  }

  _getLabelPosition(nodeSize, type) {
    let position = 0
    let flag = (type === 'bottom' || type === 'right') ? 1 : -1
    return flag * (Math.ceil(nodeSize / 2) + 10)
  }

  /**
   * 根据paint属性中指定的字段，将表格数据处理成图表组件需要的格式
   */
  reduceData(paint) {
    let { startTime, endTime } = paint
    if (!startTime || !endTime) {
      this.data = []
      return
    }
    let data = []
    let start = new Date(startTime).getFullYear()
    let end = new Date(endTime).getFullYear()
    for (let i = start; i <= end; i++) {
      data.push(i)
    }
    this.data = data
  }
}

export default TimeLine
