import { type RouteRecordRaw, createRouter, createWebHashHistory } from 'vue-router';
import { prefixPathRoutes, unfoldRoutes } from './router-util';

/**
 * 不显示标题栏的路由路径列表
 */
export const notHeadRoute: string[] = [];

/**
 * 获取布局路由列表
 *
 * 该函数定义了整个应用的所有路由配置，包括：
 * 1. 登录页面
 * 2. 画板页面
 * 3. 选择课程页面
 * 4. 会议相关页面
 * 5. 辅导相关页面
 * 6. 互动相关页面
 * @returns 路由记录数组
 */
export function getLayoutRoutesList(): RouteRecordRaw[] {
  const list: RouteRecordRaw[] = [
    {
      // 根路径重定向到登录页
      path: '/',
      meta: { title: '首页', hidden: true, noCache: true },
      redirect: '/login',
    },
    {
      // 登录页面路由
      path: 'login',
      name: 'login',
      meta: { title: '登录', hidden: true, noCache: true },
      component: () => import('@/views/login/login.vue'),
    },

    {
      path: 'meeting',
      meta: { title: '会议', hidden: true, noCache: true },
      redirect: '/meeting/select-courses',
      children: [
        {
          path: 'select-courses',
          name: 'select-courses',
          component: () => import('@/views/meeting/select-courses/select-courses.vue'),
          meta: { title: '会议 - 选择课程', affix: false, noCache: true },
        },
        {
          path: 'join-room',
          name: 'join-room',
          component: () => import('@/views/meeting/join-room/join-room.vue'),
          meta: { title: '会议 - 加入房间', affix: false, noCache: true },
        },
        {
          path: 'meeting-room',
          name: 'meeting-room',
          component: () => import('@/views/meeting/meeting-room/meeting-room-teacher.vue'),
          meta: { title: '会议 - 教室端', affix: false, noCache: true },
        },
        {
          path: 'meeting-room-student',
          name: 'meeting-room-student',
          component: () => import('@/views/meeting/meeting-room/meeting-room-student.vue'),
          meta: { title: '会议 - 学生端', affix: false, noCache: true },
        },
        {
          path: 'meeting-room-monitor',
          name: 'meeting-room-monitor',
          component: () => import('@/views/meeting/meeting-room/meeting-room-monitor.vue'),
          meta: { title: '会议 - 监控端', affix: false, noCache: true },
        },
      ],
    },
  ];
  return list;
}

/**
 * 创建路由
 */
export const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: unfoldRoutes(prefixPathRoutes(getLayoutRoutesList())),
});

/**
 * 得到所有根页面路径 如['/login', '/err403', '/err404']
 */
export function getRootRoutes(routes?: RouteRecordRaw[]): string[] {
  const newRoutes = routes || router.options.routes.filter((item) => item.path !== '/' && !item.redirect);
  let paths: string[] = [];
  newRoutes.forEach((item) => {
    paths.push(item.path);
    if (item.children) {
      paths = paths.concat(getRootRoutes(item.children));
    }
  });
  return paths;
}

/**
 * 在测试环境下检测路由的合规性
 */
if (import.meta.env.DEV) {
  /** 原始配置表 子路由合规性验证 */
  const _childrenPathVerify = (_router: RouteRecordRaw[], isChild: boolean) => {
    _router.forEach((route) => {
      const path = route.path || '';
      isChild && path.includes('/') && console.warn(`${path}子路由路径不能包含/`);
      // 如果有下级就递归调用
      route.children && Array.isArray(route.children) && _childrenPathVerify(route.children, true);
    });
  };
  _childrenPathVerify(getLayoutRoutesList(), false);
  const lastPathObj: Record<string, boolean> = {};
  const nameObj: Record<string, boolean> = {};
  const titleObj: Record<string, boolean> = {};
  const _routerComplianceDetection = (_router: Readonly<RouteRecordRaw[]>) => {
    _router.forEach((route: RouteRecordRaw) => {
      const path = route.path || '';
      const name = (route.name || '') as string;
      !path && console.warn('路由的path字段不能为空');
      !route.component && name && console.warn(`${path}没有component的路由不能包含name字段`);
      route.component && !name && !route.redirect && console.warn(`${path}有component的路由必须包含name字段`);
      path !== '/:pathMatch(.*)*' && path.toLowerCase() !== path && console.warn(`${path}路由的path字段包含大写,建议统一改为小写`);
      name.toLowerCase() !== name && console.warn(`${path}路由的name字段包含大写,建议统一改为小写`);

      if (!route.redirect) {
        const title = route.meta && route.meta.title ? route.meta.title : '';
        const lastPath = path.split('/').pop() || '';

        lastPathObj[lastPath] && console.warn(`${path}路由的path字段有重复`);
        lastPathObj[lastPath] = true;
        nameObj[name] && console.warn(`${path}路由的name字段有重复`);
        nameObj[name] = true;
        if (!title) {
          console.warn(`${path}路由配置缺少meta.title字段`);
        } else {
          titleObj[title] && console.warn(`${path}路由的meta.title字段有重复`);
          titleObj[title] = true;
        }
      } else {
        !String(route.redirect).startsWith('/') && console.warn(`${path}重定向路径必须以/开头`);
      }
      if (route.children) {
        // 如果有下级就递归调用
        Array.isArray(route.children) && route.children.length > 0 && _routerComplianceDetection(route.children);
      } else {
        path.includes('/operation/') && route?.meta?.noCache && console.warn(`${route.path}订单相关路由meta.noCache必须设置为false`);
        path.includes('/query/') && route?.meta?.noCache && console.warn(`${route.path}查询相关路由meta.noCache必须设置为false`);
      }
    });
  };
  router.options.routes.forEach((route) => {
    !route.path.startsWith('/') && console.warn(`${route.path}顶级路由的路径必须/开头`);
    !route?.meta?.hidden && !route.redirect && console.warn(`${route.path}顶级路由meta.hidden必须设置为true`);
  });
  _routerComplianceDetection(router.options.routes);
}
export default router;
