index.ts 11.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
import type { MenuConfig } from "@/api/route";

import type { RouteRecordRaw } from "vue-router";

import { createRouter, createWebHistory } from "vue-router";

import {  transformMenuConfig } from "@/api/route";
import { isRouteInWhitelist } from "@/config/permission";
import { getMicroAppByPath } from "@/qiankun/apps";
import { useAppStore, useMenuStore, useUserStore } from "@/stores";
import { getToken } from "@/utils/auth";
import { waitForMicroAppContainer } from "@/utils/microapp";
import { ElMessage } from "element-plus";

import { fetchMicroAppRouteConfig } from "../config/center";

/**
 * 路由配置
 * 支持多级路由嵌套,配合菜单系统实现多级导航
 * 注意:Vue 微应用模块路由将通过 API 动态添加
 */
const routes: RouteRecordRaw[] = [
	{
		path: "/login",
		name: "Login",
		component: () => import("@/views/Login.vue"),
		meta: {
			title: "登录",
			requiresAuth: false, // 不需要认证
		},
	},

	// ==================== 主应用布局 ====================
	{
		path: "/",
		name: "Layout",
		component: () => import("@/layouts/BasicLayout.vue"),
		redirect: "/home",
		meta: {
			requiresAuth: true, // 需要认证
		},
		children: [
			// ==================== 首页模块 ====================
			{
				path: "/home",
				name: "Home",
				component: () => import("@/views/Home.vue"),
				redirect: "/assisant/assistant",
				meta: {
					title: "首页",
					level: 1,
					requiresAuth: true,
				},
				children: [
					{
						path: "dashboard",
						name: "Dashboard",
						component: () => import("@/views/Home.vue"),
						meta: {
							title: "工作台",
							level: 2,
							requiresAuth: true,
						},
					},
				],
			},
			// ==================== 403 页面 ====================
			{
				path: "/403",
				name: "Forbidden",
				component: () => import("@/views/Forbidden.vue"),
				meta: {
					title: "无权限访问",
					requiresAuth: false,
				},
			},
			// ==================== 404 页面 ====================
			{
				path: "/:pathMatch(.*)*",
				name: "NotFound",
				component: () => import("@/views/NotFound.vue"),
				meta: {
					title: "",
					requiresAuth: false,
				},
			},
		],
	},
];

const router = createRouter({
	history: createWebHistory(),
	routes: routes as readonly RouteRecordRaw[],
});

/**
 * 动态添加路由
 * @param routes 要添加的路由配置数组
 * @param parentName 父路由名称,如果提供,则添加到该父路由的 children 中
 */
export function addRoutes(routes: RouteRecordRaw[], parentName?: string) {
	if (parentName) {
		// 添加到指定父路由的 children 中
		const parentRoute = router
			.getRoutes()
			.find((route) => route.name === parentName);
		if (parentRoute) {
			routes.forEach((route) => {
				// console.log('[路由] addRoute', route);
				router.addRoute(parentName, route);
			});
		} else {
			console.warn(`[路由] 未找到父路由 "${parentName}"`);
		}
	} else {
		// 直接添加到根路由
		routes.forEach((route) => {
			router.addRoute(route);
		});
	}
}

// 登录页路径
const LOGIN_PATH = "/login";

// 标记是否正在加载动态路由
let isLoadingRoutes = false;

/**
 * 加载动态路由和菜单配置
 */
export async function loadDynamicRoutes() {
	// 防止重复加载
	if (isLoadingRoutes) {
		return;
	}
	const menuStore = useMenuStore();
	// 如果已经加载过,则不再重复加载
	if (menuStore.isMenusLoaded) {
		return;
	}
	try {
		isLoadingRoutes = true;
		// 调用 API 获取路由和菜单配置
		const response = await fetchMicroAppRouteConfig();
		if (response.code === 200 && response.data) {
			const routerData: MenuConfig = {
				topMenus: [],
				routes: []
			};
			response.data.microApps.forEach((item: { routerList: any; routes: any; }) => {
				routerData.topMenus.push(item.routerList as any);
				routerData.routes.push(item.routes as any);
			});
			// 此处需要对路由配置数据进行格式化处理
			const { topMenus, routes } = transformMenuConfig(routerData);
      
			// 更新菜单 store
			menuStore.setTopMenus(topMenus);

			// 动态添加路由到 Layout 的 children 中
			if (routes.length > 0) {
				addRoutes(routes, "Layout");
				menuStore.addDynamicRoutes(routes);
			}
		}
	} catch (error) {
		console.error(
			"[路由守卫] 加载动态路由和菜单配置失败将使用默认菜单配置:",
			error,
		);
	} finally {
		isLoadingRoutes = false;
	}
}

/**
 * 检查路径是否可能是子应用路由
 * @param path 路由路径
 */
async function isPossibleMicroAppPath(path: string): Promise<boolean> {
	// 检查路径是否以已知的微应用 activeRule 开头
	// 等待配置加载完成以确保能正确匹配
	const microApp = await getMicroAppByPath(path, true);
	return !!microApp;
}

/**
 * 等待动态路由加载完成并重新匹配路由
 * @param targetPath 目标路径
 */
async function waitForRoutesAndRematch(targetPath: string): Promise<boolean> {
	const menuStore = useMenuStore();

	// 如果已经加载过,直接检查路由是否匹配,不再重复加载
	if (menuStore.isMenusLoaded) {
		const matchedRoutes = router.resolve(targetPath);
		return matchedRoutes.name !== "NotFound";
	}

	const appStore = useAppStore();
	// 显示 loading
	appStore.setLoading(true);

	try {
		// 等待动态路由加载完成(loadDynamicRoutes 内部有防重复加载逻辑)
		await loadDynamicRoutes();

		// 等待一小段时间,确保路由已经添加到 router 中
		await new Promise((resolve) => setTimeout(resolve, 100));

		// 检查路由是否已存在
		const matchedRoutes = router.resolve(targetPath);
		const isMatched = matchedRoutes.name !== "NotFound";

		return isMatched;
	} catch (error) {
		console.error("[路由守卫] 等待动态路由加载失败:", error);
		return false;
	} finally {
		// 隐藏 loading
		appStore.setLoading(false);
	}
}

/**
 * 全局前置守卫
 */
router.beforeEach(async (to, _from, next) => {
	// 设置页面标题
	document.title = to.meta.title
		? `${to.meta.title} - 汽车销售超级孪生智能体`
		: "汽车销售超级孪生智能体";

	// 获取 token
	const token = getToken();
	const userStore = useUserStore();

	// 判断是否需要认证
	const requiresAuth = to.meta.requiresAuth !== false;

	// ==================== Token 检查 ====================
	// 如果本地 token 不存在,检查访问权限
	if (!token) {
		// 明确声明忽略权限访问权限,则可以访问
		if (to.meta.ignoreAccess) {
			next();
			return;
		}

		// 如果已经在登录页,直接放行
		if (to.path === LOGIN_PATH) {
			next();
			return;
		}

		// 在白名单中,直接放行
		if (isRouteInWhitelist(to.path)) {
			next();
			return;
		}

		// 不需要认证的页面,直接放行
		if (!requiresAuth) {
			next();
			return;
		}

		// 没有访问权限,弹框提示后跳转登录页面
		ElMessage.warning("登录已过期,请重新登录");
		next({
			path: LOGIN_PATH,
			query:
        to.fullPath === "/home" || to.fullPath === "/"
        	? {}
        	: { redirect: encodeURIComponent(to.fullPath) },
			replace: true,
		});
		return;
	}

	// 如果匹配到404路由,检查是否是子应用路由
	if (to.name === "NotFound") {
		const menuStore = useMenuStore();
    
		// 优化:如果动态路由还未加载,才进行检查和加载
		if (!menuStore.isMenusLoaded) {
			// 检查当前路径是否可能是子应用路由(等待配置加载完成)
			const isMicroAppPath = await isPossibleMicroAppPath(to.path);
      
			if (isMicroAppPath) {
				console.log(
					"[路由守卫] 检测到可能的子应用路由,等待动态路由加载:",
					to.path,
				);

				// 等待动态路由加载完成
				const isMatched = await waitForRoutesAndRematch(to.path);

				if (isMatched) {
					// 路由已匹配,重新导航到目标路径
					next({ path: to.path, replace: true });
					return;
				}
			}
		}
		// 动态路由已加载但仍是404,或不是微应用路由,显示404页面
		next();
		return;
	}

	// ==================== 已登录状态处理 ====================
	// 如果已登录,访问登录页则跳转到首页
	if (to.path === LOGIN_PATH) {
		next({ path: "/home" });
		return;
	}

	// 已登录,处理其他路由
	// 检查是否已获取用户信息
	if (userStore.userInfo) {
		// 检查权限(支持 authority、permissions 和 roles)
		if (to.meta.authority || to.meta.permissions || to.meta.roles) {
			const hasPermission = checkPermission(to, userStore);
			if (hasPermission) {
				// 如果是微应用路由,确保数据已同步
				if (to.meta.isMicroApp) {
					await syncDataToQiankun(userStore);
				}
				next();
			} else {
				// 无权限,跳转到 403 页面
				ElMessage.error("无权限访问该页面");
				next("/403");
			}
		} else {
			// 如果是微应用路由,确保数据已同步并且容器已就绪
			if (to.meta.isMicroApp) {
				await syncDataToQiankun(userStore);
				// 等待容器就绪
				const isContainerReady = await waitForMicroAppContainer();
				if (!isContainerReady) {
					console.error("[路由守卫] 微应用容器未就绪,跳转可能失败");
				}
			}
			next();
		}
	} else {
		try {
			// 获取用户信息(会自动同步到 qiankun 全局状态)
			await userStore.getUserInfo();

			// 用户信息获取成功后,加载动态路由和菜单
			await loadDynamicRoutes();

			// 如果是微应用路由,确保数据已同步并且容器已就绪
			if (to.meta.isMicroApp) {
				await syncDataToQiankun(userStore);
				// 等待容器就绪
				const isContainerReady = await waitForMicroAppContainer();
				if (!isContainerReady) {
					console.error("[路由守卫] 微应用容器未就绪,跳转可能失败");
				}
			}

			next();
		} catch {
			// 获取用户信息失败,清除 token 并跳转到登录页
			ElMessage.warning("获取用户信息失败,请重新登录");
			await userStore.logout();
			next({
				path: LOGIN_PATH,
				query: { redirect: to.fullPath },
			});
		}
	}
});

/**
 * 全局后置守卫
 */
router.afterEach((to, from) => {
	console.log("[路由] afterEach", to, from);
	// 路由跳转完成后的处理
	console.log(`[路由] 从 ${from.path} 跳转到 ${to.path}`);
});

/**
 * 同步数据到 qiankun 全局状态
 * 确保在加载微应用前,主应用的关键数据已经同步到全局状态
 */
async function syncDataToQiankun(userStore: any): Promise<void> {
	try {

		// 同步用户信息
		if (userStore.userInfo) {
			userStore.syncUserToQiankun();
		}

		// 延迟导入 qiankun 通信模块
		const { communicationManager } = await import("@/qiankun/communication");

		// 获取当前全局状态,确认数据已同步
		const globalState = communicationManager.getGlobalState();

		// 如果用户信息还未同步,强制同步一次
		if (!globalState.user && userStore.userInfo) {
			communicationManager.updateUser({
				id: userStore.userInfo.id,
				name: userStore.userInfo.name,
				avatar: userStore.userInfo.avatar || "👨‍💼",
				role: userStore.roles[0] || "user",
				permissions: userStore.permissions,
			});
		}
	} catch (error) {
		console.error("[路由守卫] 同步数据到 qiankun 失败:", error);
	}
}

/**
 * 检查权限
 * 支持 authority(推荐)、permissions 和 roles 三种方式
 */
function checkPermission(route: any, userStore: any): boolean {
	// 优先检查 authority(推荐方式,兼容 permission.md 设计)
	if (route.meta.authority) {
		const authority = route.meta.authority as string | string[];
		if (!userStore.hasAuthority(authority)) {
			return false;
		}
	}

	// 检查角色
	if (route.meta.roles) {
		const roles = route.meta.roles as string[];
		if (!userStore.hasRole(roles)) {
			return false;
		}
	}

	// 检查权限(兼容旧版本)
	if (route.meta.permissions) {
		const permissions = route.meta.permissions as string[];
		if (!userStore.hasPermission(permissions)) {
			return false;
		}
	}

	return true;
}

export default router;