import { ElMessage } from 'element-plus';
import NProgress from 'nprogress';
import router from './router';
import 'nprogress/nprogress.css';
import { getToken, removeToken } from '@/utils/auth';
import usePermissionStore from '@/store/permission';
import { useUserStore } from '@/store/user.ts';

NProgress.configure({ showSpinner: true });

const whiteList = ['/login', '/register'];

router.beforeEach((to, from, next) => {
    NProgress.start();
    
    if (getToken()) {
        if (to.path === '/login') {
            usePermissionStore().setRoutes([]);
            usePermissionStore().setSidebarRouters([]);
            useUserStore().updateToken('');
            useUserStore().updateUserName('');
            useUserStore().updateLoginUser(null);
            usePermissionStore().setRoutes([]);
            usePermissionStore().setSidebarRouters([]);
            removeToken();
            next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
            // next();
            NProgress.done();
        } else if (whiteList.indexOf(to.path) !== -1) {
            next();
        } else if (!usePermissionStore().routeFlag) {
            // 修改判断为是否请求成功
            usePermissionStore()
                .generateRoutes()
                .then((accessRoutes) => {
                    // 递归修复所有路由（包括子路由）的双斜杠
                    const fixRouteSlashes = (route) => {
                        if (route.path && route.path.includes('//')) {
                            route.path = route.path.replace(/\/+/g, '/');
                        }
                        if (route.children && Array.isArray(route.children)) {
                            route.children.forEach(child => fixRouteSlashes(child));
                        }
                    };
                    
                    // 根据roles权限生成可访问的路由表
                    accessRoutes.forEach((route) => {
                        // 验证路由路径
                        if (!route.path || !route.path.startsWith('/')) {
                            console.error('Invalid route path:', route.path, 'for route:', route);
                            return;
                        }
                        
                        // 递归修复路由及其所有子路由的双斜杠
                        fixRouteSlashes(route);
                        
                        router.addRoute(route); // 动态添加可访问路由表
                    });
                    next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
                })
                .catch((error) => {
                    console.error('Failed to generate routes:', error);
                    // 如果路由生成失败，跳转到首页
                    next({ path: '/', replace: true });
                });
        } else {
            next();
        }
    } else {
        // 没有token
        useUserStore().updateToken('');
        useUserStore().updateUserName('');
        useUserStore().updateLoginUser(null);
        usePermissionStore().setRoutes([]);
        usePermissionStore().setSidebarRouters([]);
        if (whiteList.indexOf(to.path) !== -1) {
            // 在免登录白名单，直接进入
            next();
        } else {
            next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
            NProgress.done();
        }
    }
});

router.afterEach(() => {
    NProgress.done();
});
