import {createRouter, createWebHashHistory} from "vue-router";
import Cookies from 'js-cookie'
import {useAppStore} from "@/store/app.js";

// cookies

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

//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;
    }

    // 获取store实例
    const store = useAppStore();
    
    // 检查Cookie中是否有用户信息
    const userInfo = Cookies.get('userInfo');
    const lastApiMesUrl = Cookies.get('API_MES_URL')
    if (lastApiMesUrl) {
        console.log('从cookie中获取的中控接口IP:', lastApiMesUrl)
        window.g.API_MES_URL = lastApiMesUrl
    }

    const lastApiMeControlCode = Cookies.get('API_MES_ControlCode')
    if (lastApiMeControlCode) {
        console.log('从cookie中获取的中控代码:', lastApiMeControlCode)
        window.g.API_MES_ControlCode = lastApiMeControlCode
    }
    
    if (to.path === '/login') {
        // 如果已经登录，则不允许访问登录页面
        if (store.user.AID || userInfo) {
            next('/');
        } else {
            next();
        }
    } else {
        // 如果未登录且Cookie中有用户信息，则恢复用户信息
        if (!store.user.AID && userInfo) {
            try {
                const parsedUserInfo = JSON.parse(userInfo);
                store.user = {
                    ...store.user,
                    ...parsedUserInfo
                };
                next();
            } catch (error) {
                console.error('解析用户信息失败:', error);
                next('/login');
            }
        } else if (!store.user.AID) {
            // 如果未登录且Cookie中也没有用户信息，则跳转到登录页面
            next('/login');
        } else {
            next();
        }
    }
});

// 递归替换引入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;
