import store from '@/store'
import router, { resetRouter } from '@/router'
export default class BeforeEnter {
  constructor(opt) {
    this.opt = opt || {}
  }

  async update(to, from, next) {
    const isLogin = store.state.user.isLogin || (await store.dispatch('checkLogin'))
    if (!isLogin) {
      window.location.href = `${webConf.others.loginUrl}?rd=${encodeURIComponent(window.location.href)}`
      return
    } else {
      const hasPermissions = store.state.user.permissions && store.state.user.permissions.length > 0
      if (hasPermissions) {
        next()
      } else {
        // console.log(1234444)
        await store.dispatch('checkRolesPermissions')
        const permissions = store.state.user.permissions
        // 基于权限获取可接入的路由
        const accessRoutes = await store.dispatch('permission/routesByPermissions', permissions)
        // 重新设置路由
        resetRouter()
        // dynamically add accessible routes
        router.addRoutes(accessRoutes)
        // hack method to ensure that addRoutes is complete
        // set the replace: true, so the navigation will not leave a history record
        next({ ...to, replace: true })
      }
    }
    // store.dispatch('setUserRoles')
    next()
  }
}
