import type { Router } from 'vue-router'
import { useRouterStore } from '@/stores/router'
import { useUserStore } from '@/stores/user'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const whiteList = ['/login']
const title = useTitle()

const createRouterGuard = (router: Router) => {
  router.beforeEach(async (to, from) => {
    const userStore = useUserStore()
    const token = userStore.token

    NProgress.start()
    if (to.meta?.title) {
      title.value = to.meta?.title
    }

    if (token) {
      if (to.path === '/login') {
        return from.path
      } else {
        const routerStore = useRouterStore()
        // flag默认为false,为true时表示已经获取过用户信息
        if (!userStore.flag) {
          await userStore.getUserInfo()

          const accessedRouters = await routerStore.generatorRouter()
          accessedRouters.forEach(route => {
            router.addRoute('layout', route)
          })

          return { ...to, replace: true }
        }
        return true
      }
    } else {
      if (whiteList.includes(to.path)) {
        return true
      } else {
        return { path: '/login', query: { redirect: to.fullPath } }
      }
    }
  })

  router.afterEach(() => {
    NProgress.done()
  })
}

export default createRouterGuard
