import cAction from '@action'
import store from '@/store'
import { Message } from 'element-ui'

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

  async update(to, from, next) {
    if (to.meta && to.meta.userRole) {
      const isLogin = store.state.user.id || (await store.dispatch('checkLogin'))
      if (isLogin && window.PROJECT_ID) {
        next()
      } else {
        next({ path: '/login' })
      }
    } else {
      next()
    }
  }

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