import type { Router } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
import i18n from '@/locales'

/** 路由白名单 */
const whitePathList = ['/login', '/reset-password']

export function createRouterGuards(router: Router) {
  router.beforeEach((to, _from, next) => {
    window.$loadingBar.start()

    const userStore = useUserStore()

    if (userStore.isLogin && to.name === 'Login') {
      next({ name: 'Root' })
      return
    }

    // 白名单直接跳过
    if (whitePathList.includes(to.path) || to.meta.ignoreAuth) {
      next()
      return
    }

    if (!userStore.isLogin && !whitePathList.includes(to.fullPath)) {
      next({ path: '/login', query: { redirect: encodeURIComponent(to.fullPath) } })
      return
    }

    next()
  })

  router.afterEach((to) => {
    if (to.meta.hiddenTitle) {
      document.title = ''
    } else if (to.meta.title) {
      document.title = `${import.meta.env.VITE_APP_NAME}-${i18n.global.t(to.meta.title as string)}`
    } else {
      document.title = import.meta.env.VITE_APP_NAME
    }

    window.$loadingBar.finish()
  })

  router.onError((error) => {
    console.log(error, '--路由错误--')
  })
}
