import { createWebHashHistory, createRouter } from 'vue-router'

import Layout from '../layout/index.vue'

// 检查路由是否在授权菜单中的函数
const checkRoutePermission = (route, menuList) => {

    // bag-monitor 路由不需要权限验证
    if (route.path === '/bag-monitor') {
      return true;
    }
    
  // 检查当前路由
  const hasPermission = menuList.some(menu => 
    menu.name === route.meta?.title && 
    menu.url === route.path
  );

  if (hasPermission) return true;

  // 如果有子路由，递归检查
  if (route.children) {
    return route.children.some(child => checkRoutePermission(child, menuList));
  }

  return false;
};

// 递归查找匹配的路由配置
const findMatchedRoute = (path, routes) => {
  for (const route of routes) {
    if (route.path === path) return route;
    if (route.children) {
      const found = findMatchedRoute(path, route.children);
      if (found) return found;
    }
  }
  return null;
};

const routes = [
    {
        path: '/',
        component: Layout,
        redirect: '/dashboard',
        children: [
          {
            path: '/dashboard',
            component: () => import('../views/dashboard/index.vue'),
            meta: { title: '首页', icon: 'dashboard', },
          },
          {
            path: '/dust-overview',
            component: () => import('../views/dustOverview/index.vue'),
            meta: { title: '除尘器总览', icon: 'dustOverview' },
          },
          {
            path: '/device-management',
            meta: { title: '设备管理', icon: 'deviceManage' },
            children: [
              {
                path: '/management/device-management',
                component: () => import('../views/equipmentManagement/index.vue'),
                meta: { title: '设备管理' },
              },
              {
                path: '/management/suspend-management',
                component: () => import('../views/equipmentManagement/suspendManagement/suspendManagement.vue'),
                meta: { title: '挂起设备管理' },
              },
            ]
          },
          {
            path: '/monitor',
            component: () => import('../views/dustMonitoring/index.vue'),
            meta: { title: '除尘器监控', icon: 'monitor' },
          },
           {
            path: '/collectorList',
            component: () => import('../views/collectorList/collectorList.vue'),
            meta: { title: '布袋周期', icon: 'collectorList' },
          },
          {
            path: '/bag-monitor',
            component: () => import('../views/dustMonitoring/bag-monitoring.vue'),
            meta: { title: 'BME布袋监测', icon: 'collectorList' },
          },
          {
            name: 'alerts',
            path: '/alerts',
            component: () => import('../views/AboutView/AboutView.vue'),
            meta: { title: '告警总览', icon: 'warnning' },
          },
          {
            path: '/my-loop',
            meta: { title: '我的闭环', icon: 'closeIcon' },
            children: [
              {
                path: '/my-loop/myAgency',
                component: () => import('@/views/closeManage/myAgency.vue'),
                meta: { title: '我的待办' },
              },
              {
                path: '/my-loop/myDone',
                component: () => import('@/views/closeManage/myDone.vue'),
                meta: { title: '我的已办' },
              },
            ]
          },
        ]
      },
    {
        path: '/intermediate',
        component: () => import('@/views/intermediate/index.vue'),
        meta: { title: '中间页面' }
    },
    {
        path: '/login',
        component: () => import('../views/login/index.vue'),
        meta: {
            title: '登录'
        }
    },
]

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

// 添加全局路由守卫
router.beforeEach((to, from, next) => {
    // 如果是从登录页面来的，并且不是去中间页的，就重定向到中间页
    if (to.path === '/intermediate') {
        next();
        return;
    }

    // 登录页面不需要权限验证
    if (to.path === '/login') {
        next();
        return;
    }

    // 获取存储的菜单列表
    const menuList = JSON.parse(localStorage.getItem('menuList') || '[]');
    
    // 如果没有菜单列表且不是登录页，跳转到登录页
    if (!menuList.length) {
        next('/login');
        return;
    }

    // 查找目标路由的配置
    const targetRoute = findMatchedRoute(to.path, routes[0].children || []);
    
    // 如果找不到路由配置，或者路由没有权限，跳转到首页或显示无权限页面
    if (!targetRoute || !checkRoutePermission(targetRoute, menuList)) {
        // 可以根据需求跳转到不同页面，比如 403 页面或首页
        next('/dashboard');
        return;
    }

    next();
});

export {
    routes,
    router
}