/**
 * 路由配置
 */
import NProgress from 'nprogress';
import type { _RouteLocationBase } from 'vue-router';
import { createRouter, createWebHistory } from 'vue-router';
import { WHITE_LIST, REDIRECT_PATH, LAYOUT_PATH } from '@/config/setting';
import { useUserStore } from '@/store/modules/user';
import { getToken } from '@/utils/token-util';
import { routes, getMenuRoutes } from './routes';
// import { useTenantStore } from '@/store/modules/tenant';

NProgress.configure({
  speed: 200,
  minimum: 0.02,
  trickleSpeed: 200,
  showSpinner: false
});

const router = createRouter({
  routes,
  history: createWebHistory(),
  scrollBehavior() {
    return { top: 0 };
  }
});

// 标记动态路由是否已经注册
let dynamicRoutesRegistered = false;

// 重置动态路由注册状态的函数
export function resetDynamicRoutes() {
  dynamicRoutesRegistered = false;
}

/**
 * 路由守卫
 */
router.beforeEach(async (to, from) => {
  if (!from.path.includes(REDIRECT_PATH)) {
    NProgress.start();
  }
  // 租户信息
  // const tenantStore = useTenantStore();
  // await tenantStore.fetchTenantInfo();
  if (!getToken()) {
    // 未登录跳转登录界面
    if (!WHITE_LIST.includes(to.path)) {
      return {
        path: '/login',
        query: to.path === LAYOUT_PATH ? {} : { from: to.path }
      };
    }
    return;
  }

  // 注册动态路由
  const userStore = useUserStore();
  if (!userStore.menus && !dynamicRoutesRegistered) {
    const { menus, homePath } = await userStore.fetchUserInfo();
    if (menus) {
      const menuRoute = getMenuRoutes(menus, homePath);
      router.addRoute(menuRoute);
      dynamicRoutesRegistered = true;

      // 只有当访问根路径时才跳转到首页
      if (to.path === LAYOUT_PATH) {
        return { path: homePath || '/dashboard', replace: true };
      }

      // 对于其他路径，只有在路由确实不存在时才跳转
      // 这避免了已存在页面的不必要跳转
      return { ...to, replace: true };
    }
  }
});

router.afterEach((to) => {
  if (!to.path.includes(REDIRECT_PATH) && NProgress.isStarted()) {
    setTimeout(() => {
      NProgress.done(true);
    }, 200);
  }
});

export default router;
