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)}`
      next()
    } else {
      const hasPermissions = store.state.user.permissions && store.state.user.permissions.length > 0
      if (hasPermissions) {
        const permissions = store.state.user.permissions
        if (to.path.includes('error-page')) {
          next()
        } else {
          if (!permissions.includes(to.meta.permission)) {
            router.push('/error-page/401')
          }
          next()
        }
      } else {
        const { permissions } = await store.dispatch('checkRolesPermissions')
        if (!permissions.length) {
          window.location.href = `${webConf.others.loginUrl}?rd=${encodeURIComponent(window.location.href)}`
          next()
        } else {
          try {
            // 基于权限获取可接入的路由
            const accessRoutes = await store.dispatch('permission/routesByPermissions', permissions)
            // 重新设置路由
            resetRouter()
            // 动态添加路由
            router.addRoutes(accessRoutes)
            next({ ...to, replace: true })
          } catch (error) {
            next()
          }
          if (to.path.includes('error-page')) {
            next()
          } else {
            if (!permissions.includes(to.meta.permission)) {
              router.replace('/error-page/401')
            }
            next()
          }
        }
      }
    }
  }
}
