import useStore from '@/store/index';

/**
 * 设置router的全局路由守卫
 * @param {VueRouter} router 路由对象
 */
function setGuard(router: any) {
    router.beforeEach(async (to: any, from: any, next: any) => {
        const { user, app, tagsView } = useStore()
        // console.log('to', to)
        // 添加页面缓存
        tagsView.addCachedView({name: to.name, path:'', meta: to.meta})

        const hasToken = user.getToken();
        // 未登录
        if (!hasToken) {
            // 未登录时放通login
            if (to.path === '/login') {
                next();
                return;
            }
            // 跳转login
            next(`/login?redirect=${to.fullPath}`);
            //   NProgress.done();
            return;
        }
        const routes = app.getRoutes;
        // 若没有设置routes
        if (routes && routes.length === 0) {
            const { app } = useStore();
            // 获取menuList
            const menuList: any = await app.getMenuList();
            // 如果menuList不存在或为空，则不走下面
            if (!menuList || menuList.length === 0) {
                return
            }
            // 生成路由
            const asyncRoutes: any = await app.generateRoutes(menuList);

            if (asyncRoutes.length >= 1) {
                // 加载路由
                asyncRoutes.map(item => {
                    // console.log("加载路由",item)
                    router.addRoute(item);
                })
                next({ ...to, replace: true });
            } else {
                // 没有菜单权限，跳转到个人中心页面
                next(`/404`);
                // proxy.$ElMessage.inso('没有任何菜单权限，请联系管理员添加');
            }

            return;
        }
        next();
    });
    router.afterEach(() => {

    });
}

export {
    setGuard
};
