import router from './router'
import store from './store'
import { getToken } from '@/utils/auth'
import './resource'

let initPower = false

router.beforeEach(async(to, from, next) => {
  // 查询logo
  await store.dispatch('dict/getLogo')
  // 如果当前是登录页或者重置密码页，则直接跳转
  if (['Login', 'ResetPassword'].includes(to.name)) {
    return next()
  }
  // 获取当前token
  const hasToken = getToken()
  // 如果当前没有登录过，则直接跳转去登录
  if (!hasToken) {
    return next({
      name: 'Login',
      query: to.query
    })
  }
  // 如果初始化过权限
  if (initPower) {
    await store.dispatch('stepView/addCachedView', [to, from])
    // 如果初始化设备
    store.dispatch('user/getDeviceInfo')
  } else {
    initPower = true
    try {
      // 获取当前用户有权限的菜单
      const menus = await store.dispatch('user/getMenus')
      // 获取有权限的路由
      const accessRoutes = await store.dispatch('permission/generateRoutes', menus)
      // 刷新字典项
      store.dispatch('dict/getDictionary')
      // 动态添加
      router.addRoutes(accessRoutes)
      return next({ ...to, replace: true })
    } catch (error) {
      console.error(error)
    }
  }
  next()
})

