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']
    this.isMobile = /android|iphone|ipad|ipod/i.test(UA)
  }

  async update(to, from, next) {
    // 免登录页面
    if (this.whiteList.includes(to.name)) {
      next()
      return
    }
    // 检测登录状态
    const isLogin = await this.isLogin()
    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() {
    if (window.G.UserInfo) return true
    return cAction.Other.getInfo()
      .then(res => {
        if (res.id) {
          window.G.UserInfo = res
          return true
        } else {
          return false
        }
      })
      .catch(() => {
        return false
      })
  }
}
