index.ts 7.06 KB
import type { RouteRecordRaw } from 'vue-router';

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

import { useUserStore } from '@/stores';
import { getToken } from '@/utils/auth';

/**
 * 路由配置
 * 支持多级路由嵌套,配合菜单系统实现多级导航
 */
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: '/home/dashboard',
        meta: {
          title: '首页',
          level: 1,
          requiresAuth: true,
        },
        children: [
          {
            path: 'dashboard',
            name: 'Dashboard',
            component: () => import('@/views/Home.vue'),
            meta: {
              title: '工作台',
              level: 2,
              requiresAuth: true,
            },
          },
          {
            path: 'analytics',
            name: 'Analytics',
            component: () => import('@/views/Home.vue'),
            meta: {
              title: '数据概览',
              level: 2,
              requiresAuth: true,
            },
          },
        ],
      },

      // ==================== Vue 微应用模块 ====================
      {
        path: '/subapp-vue/:pathMatch(.*)*',
        name: 'SubAppVue',
        component: () => import('@/views/MicroApp.vue'),
        meta: {
          title: '汽车销售智能体',
          level: 1,
          isMicroApp: true,
          requiresAuth: true,
        },
      },

      // ==================== React 微应用模块 ====================
      {
        path: '/subapp-react/:pathMatch(.*)*',
        name: 'SubAppReact',
        component: () => import('@/views/MicroApp.vue'),
        meta: {
          title: 'React 微应用',
          level: 1,
          isMicroApp: true,
          requiresAuth: true,
        },
      },
    ],
  },

  // ==================== 404 页面 ====================
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue'),
    meta: {
      title: '页面不存在',
      requiresAuth: false,
    },
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 白名单:不需要登录的路由
const whiteList = new Set(['/forgot-password', '/login', '/register']);

/**
 * 全局前置守卫
 */
router.beforeEach(async (to, _from, next) => {
  // 设置页面标题
  document.title = to.meta.title
    ? `${to.meta.title} - SCRM 微前端`
    : 'SCRM 微前端平台';

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

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

  if (token) {
    // 已登录
    if (to.path === '/login') {
      // 如果已登录,访问登录页则跳转到首页
      next({ path: '/home' });
    } else {
      // 检查是否已获取用户信息
      if (userStore.userInfo) {
        // 检查权限
        if (to.meta.permissions || to.meta.roles) {
          const hasPermission = checkPermission(to, userStore);
          if (hasPermission) {
            // 如果是微应用路由,确保数据已同步
            if (to.meta.isMicroApp) {
              await syncDataToQiankun(userStore);
            }
            next();
          } else {
            // 无权限,跳转到 403 或首页
            console.warn('无权限访问:', to.path);
            next({ path: '/home' });
          }
        } else {
          // 如果是微应用路由,确保数据已同步
          if (to.meta.isMicroApp) {
            await syncDataToQiankun(userStore);
          }
          next();
        }
      } else {
        try {
          // 获取用户信息(会自动同步到 qiankun 全局状态)
          await userStore.getUserInfo();

          // 如果是微应用路由,确保数据已同步
          if (to.meta.isMicroApp) {
            await syncDataToQiankun(userStore);
          }

          next();
        } catch (error) {
          // 获取用户信息失败,清除 token 并跳转到登录页
          console.error('获取用户信息失败:', error);
          await userStore.logout();
          next({
            path: '/login',
            query: { redirect: to.fullPath },
          });
        }
      }
    }
  } else {
    // 未登录
    if (whiteList.has(to.path)) {
      // 在白名单中,直接放行
      next();
    } else if (requiresAuth) {
      // 需要认证但未登录,跳转到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath },
      });
    } else {
      // 不需要认证的页面,直接放行
      next();
    }
  }
});

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

/**
 * 同步数据到 qiankun 全局状态
 * 确保在加载微应用前,主应用的关键数据已经同步到全局状态
 */
async function syncDataToQiankun(userStore: any): Promise<void> {
  try {
    console.log('[路由守卫] 准备进入微应用,同步数据到 qiankun 全局状态');

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

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

    // 获取当前全局状态,确认数据已同步
    const globalState = communicationManager.getGlobalState();
    console.log('[路由守卫] 当前全局状态:', globalState);

    // 如果用户信息还未同步,强制同步一次
    if (!globalState.user && userStore.userInfo) {
      console.log('[路由守卫] 检测到用户信息未同步,强制同步');
      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);
  }
}

/**
 * 检查权限
 */
function checkPermission(route: any, userStore: any): boolean {
  // 检查角色
  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;