import cAction from '@action'

export default class Before {
  constructor(opt) {
    const UA = navigator.userAgent
    this.opt = opt || {}
    // 免登录列表
    this.whiteList = ['login-normal', 'login-code', 'login-forget', 'studentHelp', 'teacherHelp', '403', 'browser']
    this.isMobile = /iphone/i.test(UA) || (/android/i.test(UA) && /mobile/i.test(UA))
    this.isIe = window.ActiveXObject || 'ActiveXObject' in window
    this.isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime)
    // this.chromeVersion = 0
    // if (this.isChrome) {
    //   const temp = UA.match(/Chrome\/([\d.]+)/)
    //   this.chromeVersion = temp ? parseFloat(temp[1]) : 0
    // }
    // this.notSupport = !this.isMobile && (this.isIe || (this.isChrome && this.chromeVersion < 70))
    this.notSupport = !this.isMobile && this.isIe
    // https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
  }

  async update(to, from, next) {
    // 浏览器不支持
    if (this.notSupport && to.name !== 'browser') {
      next({ path: '/browser' })
      return
    }

    // 免登录页面
    if (this.whiteList.includes(to.name)) {
      next()
      return
    }
    // 检测登录状态
    const isLogin = await this.isLogin(next)
    if (!isLogin) {
      // next({
      //   path: '/login/index',
      //   query: { rd: encodeURIComponent(to.fullPath) }
      // })
      window.location.href = `${webConf.others.loginUrl}?rd=${encodeURIComponent(window.location.href)}`
      return
    }
    // 移动端
    if (this.isMobile && to.name !== 'mobileIndex') {
      next({ path: '/mobile/list' })
      return
    }
    next()
  }

  /* 获取用户信息 */
  isLogin(next) {
    if (window.G.UserInfo) return true
    return Promise.all([cAction.Other.getInfo(), cAction.Other.getUser()])
      .then(([p1, p2]) => {
        const res = { student_info: p1, ...p2.data }
        if (res.id) {
          window.G.UserInfo = res
          return true
        } else {
          return false
        }
      })
      .catch(res => {
        if (res.status === 401) {
          next({ path: '/403' })
          return true
        }
        return false
      })
  }
}
