import cAction from '@action'

import { Message } from 'element-ui'

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|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) }
      })
      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) => {
        window.G.UserInfo = res
        return true
      })
      .catch((res) => {
        if (res.code !== 80201) {
          Message({ type: 'error', message: res.message })
        }
        return false
      })
  }
}
