/**
 * 权限控制
 */

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

import router, { findFirstValidRoute } from './router'
import { INDEX_ROUTE, INDEX_ROUTE_NAME } from './router/routes'
import { useTabsStore } from './stores/modules/tabs'
import { useUserStore } from './stores/modules/user'

NProgress.configure({ showSpinner: false })

const loginPath = '/login'
const defaultPath = '/index'
// 免登录白名单
const whiteList: string[] = [loginPath, '/403']

const resetUserState = () => {
  const userStore = useUserStore()
  const tabsStore = useTabsStore()
  userStore.resetAuthInfo()
  tabsStore.resetTabsState()
}

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = to.meta.title ? `${to.meta.title} - ${settings.title}` : settings.title
  const userStore = useUserStore()
  const tabsStore = useTabsStore()
  if (whiteList.includes(to.path)) {
    next()
    return
  }
  if (!userStore.token) {
    next({ path: loginPath, query: { redirect: to.fullPath } })
    return
  }
  const hasGetUserInfo = Object.keys(userStore.userInfo).length !== 0
  if (hasGetUserInfo) {
    if (to.path === loginPath) {
      next({ path: defaultPath })
    } else {
      next()
    }
    return
  }
  try {
    await userStore.getUserInfo()
    const processedRoutes = userStore.routes
    const routeName = findFirstValidRoute(processedRoutes)
    if (!routeName) {
      resetUserState()
      next('/403')
      return
    }
    tabsStore.setIndexRouteName(routeName!)
    INDEX_ROUTE.redirect = { name: routeName }
    router.addRoute(INDEX_ROUTE)
    processedRoutes.forEach((route: any) => {
      try {
        router.addRoute(INDEX_ROUTE_NAME, route)
      } catch (e) {
        console.error('Error adding route:', e)
      }
    })
    next({ ...to, replace: true })
  } catch (err) {
    resetUserState()
    next({ path: loginPath, query: { redirect: to.fullPath } })
  }
})

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