import Http from './Http'
const Promise = require('../lib/bluebird')

// 时间管理对象
class ManageDate {
  constructor () {
    this.recordTime = 0 // 上一次刷新的时间戳
    this.curTime = 0 // 当前的时间戳
    this.updateTime = 3000 // n毫秒刷新时间
  }
  setNow (now) {
    this.now = now
  }

  /**
   * 从服务器端获取时间
   */
  hanleRequest (resolve, now) {
    this.curTime = new Date().getTime()
    // 当前时间与上一次更新时间差比配置更新时间大,则调用接口获取服务器最新时间;
    if (!now || ((this.curTime - this.recordTime) > this.updateTime)) {
      new Http().get('hs/getNowTime').then(res => {
        now = res.data.data.now
        this.recordTime = new Date().getTime()
        this.setNow(now)
        resolve(now)
      })
    } else {
      this.setNow(now)
      resolve(now)
    }
  }

  // 获取当前时间
  getNow () {
    let now = this.now
    return new Promise((resolve, reject) => {
      this.hanleRequest(resolve, now)
    })
  }
}

export default ManageDate
