import type { Router } from "vue-router";
import { menuStore } from '@/store/menu'
import { userStore } from '@/store/user'
import { getToken, cleanSession } from '@/utils/auth'
import { useAppStore } from "@/store/app";
import { setRouteChange } from "@/utils/routeChange";

function setupRouterGuard(router: Router) {
    createPageGuard(router);
    createPageLoadingGuard(router)
    createPermissionGuard(router)
}

// 权限
function createPermissionGuard(router: Router) {
    //权限验证处理:全集守卫路由实现
    const whiteList = ['/login']; //白名单
    const ustore = userStore()
    const mstore = menuStore()
    router.beforeEach(async (to, from, next) => {
        //获取token
        let token = getToken();
        if (token) {
            if (to.path === '/login' || to.path === '/') {
                next({ path: '/' })
            } else {
                //从vuex里面获取菜单
                let hasRoles = ustore.permissions && ustore.permissions.length > 0
                if (hasRoles) {
                    next()
                } else {
                    try {
                        //vuex中不存在权限，从服务器获取
                        await ustore.getInfo()
                        //获取菜单、动态生成路由
                        await mstore.getMenuList(router)
                        //确保动态添加的路由已经被完全加载上去
                        next({ ...to, replace: true })
                    } catch (error) {
                        //重置token
                        cleanSession();
                        //跳到登录
                        next({ path: '/login' })
                    }
                }
            }
        } else {
            //判断是否在白名单中
            if (whiteList.indexOf(to.path) !== -1) { //存在白名单，放行
                next();
            } else { //不存在，登录
                next({ path: '/login' })
            }
        }
    })
}

// 用于处理页面状态
function createPageGuard(router: Router) {
    const loadedPageMap = new Map<string, boolean>();
    router.beforeEach(async (to) => {
        to.meta.loaded = !!loadedPageMap.get(to.path);
        setRouteChange(to);
        return true;
    });
    router.afterEach((to) => {
        loadedPageMap.set(to.path, true);
    });
}

// 页面加载
function createPageLoadingGuard(router: Router) {
    const userStore = useAppStore();
    router.beforeEach(async (to) => {
        if (!getToken()) {
            return true;
        }
        
        /*支持三级、四级菜单缓存*/
        if(to.matched && to.matched.length > 2){
            const deNumber = to.matched.length === 3 ? 1 : 2
            for (let i = 0; i<to.matched.length; i++){
                const element = to.matched[i];
                if (element.components && element.components.default.name) {
                    to.matched.splice(1, deNumber)
                }
            }
        }
        // 页面是否已加载
        if (to.meta.loaded) {
            return true;
        }
        // 加载状态
        userStore.setPageLoadingAction(true);
        return true;
    });
    router.afterEach(async () => {
        setTimeout(() => {
            userStore.setPageLoading(false);
        }, 220);
        return true;
    });
}

export {
    setupRouterGuard
}