import { createRouter, createWebHashHistory } from 'vue-router'
import NProgress from 'nprogress'
import { staticRouter, errorRouter } from './modules/staticRouter'
import { GlobalStore } from '@/stores/index'
import { initDynamicRouter } from './modules/asyncRouter'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [...staticRouter, ...errorRouter],
  strict: false
})

const ROUTER_WHITE_LIST = ['/login', '/404']

router.beforeEach(async (to, from, next) => {
  NProgress.start() // 开始加载
  const store = GlobalStore()
  let title = to.meta.title
  title && (document.title = title as string)

  if (store.GET_User_tokey && to.path !== '/login') {
    if (!store.GET_Flat_Menu.length) {
      await initDynamicRouter()
      return next({ ...to, replace: true })
    }
    next()
  } else if (ROUTER_WHITE_LIST.includes(to.path)) {
    if (store.GET_User_tokey) {
      next('/')
    } else {
      next()
    }
  } else {
    next('/login')
  }
})

router.afterEach(() => {
  NProgress.done() // 加载完成
})

export default router
