import Vue from 'vue';
import VueRouter from 'vue-router';
import GlobalLayout from '@/layouts/GlobalLayout';

Vue.use(VueRouter);

const usersData = JSON.parse(localStorage.getItem("users"));
const userPrivileges = usersData && usersData.userPrivileges ? parseInt(usersData.userPrivileges) : 0;

const RouteView = {
  name: 'RouteView',
  render: h => h('router-view'),
};

export const routes = [
  {
    path: '/',
    name: 'Home',
    meta: { title: '主页' },
    redirect: '/race/list',
    component: GlobalLayout,
    children: [
      {
        path: '/console',
        name: 'Console',
        redirect: '/console/list',
        component: RouteView,
        meta: { title: '首 页', icon: 'appstore' },
        children: [
          {
            path: '/console/list',
            name: 'ConsoleLog',
            component: () => import('@/views/user/Console.vue'),
            meta: { title: '大数据', auth: [0]  },
          },
        ],
      },
      {
        path: '/race',
        name: 'Race',
        redirect: '/race/list',
        component: RouteView,
        meta: { title: '赛事管理', icon: 'appstore' },
        children: [
          {
            path: '/race/list',
            name: 'RaceList',
            component: () => import('@/views/race/Race'),
            meta: { title: '赛事列表', auth: [0, 1, 2] },
          },
          {
            path: '/race/record',
            name: 'Record',
            component: () => import('@/views/race/Record'),
            meta: { title: '参赛记录', auth: [0, 1, 2] },
          },
          {
            path: '/race/down',
            name: 'Down',
            component: () => import('@/views/race/Down'),
            meta: { title: '参赛资料', auth: [0, 1, 2] },
          },
        ],
      },
      {
        path: '/user',
        redirect: '/user/student',
        name: 'User',
        component: RouteView,
        meta: { title: '用户管理', icon: 'user', auth: [0, 1] },
        children: [
          {
            path: '/user/student',
            name: 'Student',
            component: () => import('@/views/user/Student'),
            meta: { title: '学生列表', auth: [0, 1] },
          },
          {
            path: '/user/teacher',
            name: 'Teacher',
            component: () => import('@/views/user/Teacher'),
            meta: { title: '教师列表', auth: [0] },
          },
        ],
      },
      {
        path: '/community',
        redirect: '/community/list',
        name: 'Role',
        component: RouteView,
        meta: { title: '交流社区', icon: 'key' },
        children: [
          {
            path: '/community/Article',
            name: 'Article',
            meta: { title: '论坛首页', auth: [0, 1, 2] },
            component: () => import('@/views/communtiy/Article.vue'),
          },
          {
            path: '/community/publish',
            name: 'publish',
            meta: { title: '在线发帖', auth: [0, 1, 2] },
            component: () => import('@/components/edit/tinymce.vue'),
          },
          {
            path: '/community/edit',
            name: 'EditArticle',
            component: () => import('@/components/edit/tinymce'),
            meta: { 
              title: '文章编辑', 
              auth: [0,1,2], 
              hidden: true // 确保此项存在且为true
            },
          },
          {
            path: '/community/pages',
            name: 'pages',
            meta: { title: '帖子详细', auth: [0, 1, 2], hidden: true },
            component: () => import('@/views/communtiy/pages.vue'),
          },
          {
            path: '/account/center',
            name: 'AccountCenter',
            meta: { title: '个人中心', auth: [0, 1, 2] },
            component: () => import('@/views/account/center/index.vue'),
          },
        ],
      },
      {
        path: '/account',
        name: 'Account',
        component: RouteView,
        meta: { title: '竞赛助手', icon: 'key' },
        children: [
          {
            path: '/account/Agent',
            name: 'AccountAgent',
            meta: { title: '编程助手', auth: 0 },
            component: () => import('@/views/user/Agent.vue'),
          },
          {
            path: '/account/CompetitionAssistant',
            name: 'CompetitionAssistant',
            meta: { title: '竞赛助手', auth: 0 },
            component: () => import('@/views/user/Ai.vue'),
          },
        ],
      },
      {
        path: '/chart',
        name: 'Chart',
        component: RouteView,
        meta: { title: '智能分析', icon: 'key' },
        children: [
          {
            path: '/chart/system',
            name: 'ChartSystem',
            meta: { title: '智能分析', auth: 0 },
            component: () => import('@/views/Chart.vue'),
          },
        ],
      },
    ],
  },
  {
    path: '/login',
    name: 'Login',
    meta: { title: '登陆' },
    component: () => import('@/views/Login'),
  },
  {
    path: '/index',
    name: 'Index',
    meta: { title: '主页' },
    component: () => import('@/views/Index'),
  },
  {
    path: '/404',
    component: () => import('@/components/common/404'),
  },
  {
    path: '*',
    redirect: '/404',
  },
];

const filteredRoutes = filterRoutes(routes, userPrivileges);

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes: routes, // 使用原始路由，不过滤
});

// 修改后的过滤函数
export function filterRoutes(routes, userPrivileges) {
  // 递归处理单个路由
  function filterSingleRoute(route, userPrivileges) {
    if (!route) return null; // 空值检查
    
    // 1. 权限检查
    if (route.meta && route.meta.auth) {
      if (Array.isArray(route.meta.auth)) {
        if (!route.meta.auth.some(authLevel => userPrivileges == authLevel)) {
          return null;
        }
      } else {
        if (userPrivileges < route.meta.auth) {
          return null;
        }
      }
    }
    
    // 2. 隐藏检查 - 如果meta.hidden为true，则从菜单中隐藏，但不从路由中移除
    let shouldHideInMenu = route.meta && route.meta.hidden === true;
    
    // 创建路由副本，避免修改原始对象
    let routeCopy = { ...route };
    
    // 如果需要在菜单中隐藏，添加hideInMenu标记
    if (shouldHideInMenu) {
      if (!routeCopy.meta) routeCopy.meta = {};
      routeCopy.meta.hideInMenu = true;
    }
    
    // 递归处理子路由
    if (routeCopy.children && routeCopy.children.length > 0) {
      routeCopy.children = routeCopy.children
        .map(childRoute => filterSingleRoute(childRoute, userPrivileges))
        .filter(childRoute => childRoute !== null && childRoute !== undefined);
    }
    
    return routeCopy;
  }

  // 过滤整个路由树
  return routes
    .map(route => filterSingleRoute(route, userPrivileges))
    .filter(route => {
      return route !== null && 
             route !== undefined && 
             (route?.children?.length > 0 || route?.meta?.alwaysShow);
    });
}

export default router;