import Taro from '@tarojs/taro'
import dayjs from 'dayjs'
import {
  STATUS_READY,
  STATUS_PROCESSING,
  STATUS_OVER,
  getPreText,
  getTkText,
  isFunction,
} from './utils'

export default class TimeTicker extends Taro.Component {
  static options = {
    addGlobalClass: true
  }

  state = {
    status: STATUS_READY,
    tmStart: undefined,
    tmEnd: undefined,
    preText: undefined,
    tkText: undefined,
  }

  timer = null

  componentWillMount() {
    this.computeProps(this.props)
  }

  componentWillReceiveProps(nextProps) {
    this.computeProps(nextProps)
  }

  componentWillUnmount() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  }

  computeProps(props) {
    const { timeRange } = props || {}
    const now = dayjs().valueOf()
    const [t1, t2] = timeRange || []
    
    // 当前状态 -  默认未开始
    let status = this.state.status
    let tmStart = undefined
    let tmEnd = undefined

    // 没有设置起止时间
    if (!t1 && !t2) {
      throw new Error('TimeTicker has no timeRange setting')
    }

    if (!t1 || !t2) {
      // 只设置了一个时间
      tmEnd = tmStart = t1 ? dayjs(t1).valueOf() : dayjs(t2).valueOf()
    } else {
      // 设置了时间区间
      tmStart = dayjs(t1).valueOf()
      tmEnd = dayjs(t2).valueOf()
    }

    if (tmStart > now) {
      status = STATUS_READY
    } else if (tmStart <= now && now < tmEnd) {
      status = STATUS_PROCESSING
    } else {
      status = STATUS_OVER
    }

    this.setState({ status, tmStart, tmEnd }, () => this.startTimer(props))
  }

  computeStatus(props) {
    const {
      onStart,
      onProcess,
      onEnd,
    } = props || {}

    let {
      status,
      tmStart,
      tmEnd,
      preText,
      tkText,
    } = this.state

    const now = dayjs().valueOf()
    const diff = status === STATUS_READY ? tmStart - now : tmEnd - now

    if (diff <= 0) {
      if (status === STATUS_READY) {
        status = tmStart === tmEnd ? STATUS_OVER : STATUS_PROCESSING
        
        if (isFunction(onStart)) {
          [preText, tkText] = onStart()
        }
      } else {
        status = STATUS_OVER
        if (this.timer) {
          clearInterval(this.timer)
        }

        if (isFunction(onEnd)) {
          [preText, tkText] = onEnd()
        }
      }
    } else {
      if (isFunction(onProcess)) {
        [preText, tkText] = onProcess(diff, status)
      }
    }

    if (preText === undefined) {
      preText = getPreText(diff, status)
    }
    
    if (tkText === undefined) {
      tkText = getTkText(diff, status)
    }

    this.setState({ status, preText, tkText })
  }

  startTimer = (props) => {
    const { interval = 1000 } = props || {}

    if (this.timer) {
      clearInterval(this.timer)
    }

    // 立即执行一次
    this.computeStatus(props);
    // 再循环执行
    this.timer = setInterval(() => this.computeStatus(props), interval)
  }



  classNames = (...args) => {
    return (args || []).reduce((cls, item) => {
      return [].concat(cls).concat(item)
    }, []).filter(x => x).join(' ')
  }

  render() {
    const wrapperCls = this.classNames('tk-box', this.props.className)
    const headerCls = this.classNames('tk-box-header', this.props.headerClass)
    const bodyCls = this.classNames('tk-box-body', this.props.bodyClass)

    return (
      <View className={wrapperCls}>
        {
          this.state.preText &&
          (<Text className={headerCls}>{this.state.preText}</Text>)
        }        
        {
          this.state.tkText &&
          (<Text className={bodyCls}>{this.state.tkText}</Text>)
        }        
      </View>
    );
  }
}
