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', 'login-register']
    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 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(() => {
        return false
      })
  }
}
