import { createRouter, createWebHashHistory } from "vue-router";
import Cookies from 'js-cookie'

// cookies

// 创建routes
const routes = [
    {
        // 重定向
        path: "/home",
        redirect: "/",
    },
    {
        //前台首页
        path: "/",
        name: "root",
        component: () => import("@/views/Layout/index.vue"),
        children: [
            {
                path: '/',
                name: 'OpStatus',
                component:  () => import("@/views/OpStatus/index.vue")
            }
        ]
    },
    {
        //前台首页
        path: "/login",
        component: () => import("@/views/Login/index.vue"),
    },
    // {  // 404有毛病 目前 初始化动态路由有问题 404暂改为重定向到首页
    //   // 404
    //   path: "/:pathMatch(.*)*",
    //   component: () => import("@/views/404.vue"),
    // },
    {
        // 404
        path: "/:pathMatch(.*)*",
        redirect: "/",
    },
];

//History路由模型
const router = createRouter({
    history: createWebHashHistory(import.meta.env.BASE_URL),
    routes,
});

//这里设置路由拦截
router.beforeEach(async (to, from, next) => {
    // 设置游览器标题
    if (to.meta.title) {
        window.document.title = to.meta.title;
    }
    // 放行
    // next();
    if (to.path === '/login' || to.path === '/') {
        next();
        return;
    } else {
        const AID = Cookies.get('AID');
        if (!AID) {
            next('/');
            return;
        } else {
            next();
            return;
        }
    }
});

// 递归替换引入component
function dynamicRouter(routerList) {
    const list = [];
    routerList.forEach((route) => {
        const routeItem = {
            path: '/' + route.path,
            name: route.path,
            meta: {
                title: route.权限模块,
            },
            component: async () => {
                try {
                    const component = await import(`@/views/${route.path}/index.vue`);
                    console.log(component)
                    return component.default || component;
                } catch (error) {
                    console.error('引入路由组件失败，请确认地址是否配置正确:', error);
                    return null;
                }
            },
        };
        list.push(routeItem);
    });
    return list;
}

// 动态添加路由的函数
export async function addDynamicRoutes(routerList) {
    try {
        // routerList.forEach(route => {
        //   console.log(123, route)
        //   // {权限模块:车体到位,path:CarBodyPlace}
        //   router.addRoute('root', {
        //     path: '/' + route.path,
        //     name:route.path,
        //     meta: {
        //       title: route.权限模块,
        //     },
        //     component: () => import(`@/views/${route.path}/index.vue`),
        //   });
        // });
        // router.addRoute('root',{
        //   children: dynamicRouter(routerList)
        // })


        // let userId = Cookies.get('userId')
        // if(userId !== ''){
        //   // 获取权限列表
        //   var param = []
        //   param[0] = ['userId', userId]
        //   var Data = CreateData('11', '基础表_权限模块_查询', param)
        //   ExecDatabase(Data).then(response => {
        //     if(response.data.length > 0){
        //       routerData.value.userRouterList = response.data
        //       // 创建动态路由列表
        //       const dynamicRoutes = dynamicRouter(response.data);
        //
        //       dynamicRoutes.forEach((route) => {
        //         // 检查是否已存在该路由，避免重复添加
        //         if (!router.hasRoute(route.name)) {
        //           router.addRoute('root', route);
        //         }
        //       });
        //     }else{
        //       ElMessage.warning('该角色未分配角色模块，请先进行分配!')
        //     }
        //   })

        // 创建动态路由列表
        const dynamicRoutes = dynamicRouter(routerList);

        dynamicRoutes.forEach((route) => {
            // 检查是否已存在该路由，避免重复添加
            if (!router.hasRoute(route.name)) {
                router.addRoute('root', route);
            }
        });
    } catch (error) {
        console.error('动态添加路由失败:', error);
    }
}

export default router;
