import axiosInstance from '@/api';
import { userInfoResponseSchema, type Route } from '@/schemas';
import { useUserStore } from '@/stores';
import { errorMessage } from '@/utils';
import { ElMessage } from 'element-plus';
import { type Component } from 'vue';
import { createRouter, createWebHashHistory, type RouteRecordRaw } from 'vue-router';
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/404',
    component: () => import('@/views/NotFoundPage.vue')
  }
];
const router = createRouter({
  history: createWebHashHistory(),
  routes: routes
});
const componentMap: Record<string, () => Promise<Component>> = {
  'MainPage.vue': () => import('@/views/MainPage.vue')
};
function _getAvailableRoutes(routeResponses: Route[], root: boolean, pathList: string[]) {
  const res: RouteRecordRaw[] = [];
  const { routeMap } = useUserStore();
  for (const routeResponse of routeResponses) {
    const path = routeResponse.name.toLowerCase();
    pathList.push(path);
    const route = {
      path: root ? `/${path}` : path,
      component: componentMap[routeResponse.component],
      children: _getAvailableRoutes(routeResponse.children, false, pathList.concat(path))
    };
    routeMap.set(`/${pathList.join('/')}`, root ? route : routeMap.get(`/${pathList[0]}`)!);
    res.push(route);
  }
  return res;
}
function getAvailableRoutes(routeResponse: Route[]) {
  _getAvailableRoutes(routeResponse, true, []);
}
router.beforeEach(async (to) => {
  const userStore = useUserStore();
  console.log(userStore.userInfo);
  // await timeout(1000);
  if (!userStore.isInitialized) {
    const userInfoResponse = userInfoResponseSchema.parse(
      (await axiosInstance.get('/api/user/info')).data
    );
    console.log(userInfoResponse);
    if (userInfoResponse.type === 'error') {
      ElMessage.error(
        errorMessage('获取用户信息失败', userInfoResponse.code, userInfoResponse.msg)
      );
      return false;
    }
    if (userStore.token !== null) {
      userStore.updateUserInfo(userInfoResponse);
    }
    getAvailableRoutes(userInfoResponse.data.auth.permissions[0].routers);
    userStore.isInitialized = true;
  }
  if (userStore.addedRouteSet.has(to.fullPath) || to.fullPath === '/404') {
    return true;
  }
  const route = userStore.routeMap.get(to.fullPath);
  if (route !== undefined) {
    router.addRoute(route);
    userStore.addedRouteSet.add(to.fullPath);
    return to;
  } else {
    return '/404';
  }
});
export default router;
