import cAction from '@action'

import { Message } from 'element-ui'

export default class Before {
  constructor(opt) {
    this.opt = opt || {}
  }

  async update(to, from, next) {
    const isLogin = await this.isLogin()
    if (to.meta && to.meta.userRole) {
      if (isLogin) {
        next()
      } else {
        next({ path: '/apply/for' })
      }
    } else {
      next()
    }
  }

  /* 获取用户信息 */
  isLogin() {
    if (window.G.UserInfo && Object.keys(window.G.UserInfo.data).length > 0) {
      return true
    }
    return cAction.Test.getInfo()
      .then(res => {
        if (res.code === 0) {
          window.G.UserInfo = res
          return true
        } else {
          return false
        }
      })
      .catch(res => {
        Message({ type: 'error', message: res.message })
        return false
      })
  }
}
