import router from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isPathMatch } from '@/utils/validate'
import useSettingsStore from '@/store/modules/settings'
import usePermissionStore from '@/store/modules/permission'
import useUserStore from '@/store/modules/user'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/register']

const isWhiteList = (path) => {
  return whiteList.some(pattern => isPathMatch(pattern, path))
}

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  if (getToken()) {
    to.meta.title && useSettingsStore().setTitle(to.meta.title)
    /* has token*/
    const userStore = useUserStore()
    // 如果还没有用户信息，先获取用户信息
    if (!userStore.name && userStore.token) {
      try {
        await userStore.getInfo()
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 如果获取用户信息失败，清除token并跳转到登录页
        await userStore.logOut()
        next(`/login?redirect=${to.fullPath}`)
        NProgress.done()
        return
      }
    }
    if (to.path === '/login') {
      // 如果已经登录，跳转到首页
      next({ path: '/user/myuser', replace: true })
      NProgress.done()
    } else if (isWhiteList(to.path)) {
      next()
    } else {
      // 直接加载菜单，不需要角色权限判断
      const permissionStore = usePermissionStore()
      if (permissionStore.routes.length === 0) {
        // 菜单还未加载，先加载菜单
        try {
          const accessRoutes = await permissionStore.generateRoutes()
          // 动态添加路由
          accessRoutes.forEach(route => {
            router.addRoute(route) // 动态添加路由
          })
          // 路由加载完成后，继续导航到目标路径
          next({ ...to, replace: true })
        } catch (error) {
          console.error('加载路由失败:', error)
          next()
        }
      } else {
        next()
      }
    }
  } else {
    // 没有token
    if (isWhiteList(to.path)) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

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