yangyin
2024-05-20 4fe305c2a999eb2d1ccb92c9ffd9aefb8c68b316
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import { RouteRecordRaw } from 'vue-router';
import { storeToRefs } from 'pinia';
import pinia from '/@/stores/index';
import { useUserInfo } from '/@/stores/userInfo';
import { useRequestOldRoutes } from '/@/stores/requestOldRoutes';
import { Local, Session } from '/@/utils/storage';
import { NextLoading } from '/@/utils/loading';
import { dynamicRoutes, notFoundAndNoPower } from '/@/router/route';
import { formatTwoStageRoutes, formatFlatteningRoutes, router } from '/@/router/index';
import { useRoutesList } from '/@/stores/routesList';
import { useTagsViewRoutes } from '/@/stores/tagsViewRoutes';
import { parseMenuTree, useMenuApi } from '/@/api/menu/index';
import { ElMessage } from 'element-plus';
import { pathMap } from '/@/router/pathMap';
import { accessTokenKey, clearAccessTokens } from '/@/utils/request';
 
// 后端控制路由
 
// 引入 api 请求接口
const menuApi = useMenuApi();
 
/**
 * 获取目录下的 .vue、.tsx 全部文件
 * @method import.meta.glob
 * @link 参考:https://cn.vitejs.dev/guide/features.html#json
 */
const layoutModules: any = import.meta.glob('../layout/routerView/*.{vue,tsx}');
const viewsModules: any = import.meta.glob('../views/**/*.{vue,tsx}');
const dynamicViewsModules: Record<string, Function> = Object.assign({}, { ...layoutModules }, { ...viewsModules });
 
/**
 * 后端控制路由:初始化方法,防止刷新时路由丢失
 * @method NextLoading 界面 loading 动画开始执行
 * @method useUserInfo().setUserInfos() 触发初始化用户信息 pinia
 * @method useRequestOldRoutes().setRequestOldRoutes() 存储接口原始路由(未处理component),根据需求选择使用
 * @method setAddRoute 添加动态路由
 * @method setFilterMenuAndCacheTagsViewRoutes 设置路由到 pinia routesList 中(已处理成多级嵌套路由)及缓存多级嵌套数组处理后的一维数组
 */
export async function initBackEndControlRoutes() {
    // 界面 loading 动画开始执行
    if (window.nextLoading === undefined) NextLoading.start();
    // 无 token 停止执行下一步
    if (!Local.get(accessTokenKey)) return false;
    // 触发初始化用户信息 pinia
    // https://gitee.com/lyt-top/vue-next-admin/issues/I5F1HP
    // await useUserInfo().setUserInfos();
    // 获取路由菜单数据
    const res = (await getBackEndControlRoutes()) as any;
 
    if (res?.Code === 0) {
        if (res.Data) {
            const formattedTreeMenu = parseMenuTree(res.Data, pathMap);
            // 无登录权限时,添加判断
            // https://gitee.com/lyt-top/vue-next-admin/issues/I64HVO
            // if (res.data.length <= 0) return Promise.resolve(true);
            // 存储接口原始路由(未处理component),根据需求选择使用
            useRequestOldRoutes().setRequestOldRoutes(JSON.parse(JSON.stringify(formattedTreeMenu)));
 
            // 处理路由(component),替换 dynamicRoutes(/@/router/route)第一个顶级 children 的路由
            dynamicRoutes[0].children = await backEndComponent(formattedTreeMenu);
            // 添加动态路由
            await setAddRoute();
            // 设置路由到 pinia routesList 中(已处理成多级嵌套路由)及缓存多级嵌套数组处理后的一维数组
            await setFilterMenuAndCacheTagsViewRoutes();
        }
        if (!res.Data || res.Data?.length === 0) {
            ElMessage.error('该账号暂时没有菜单,请尝试切换账号!');
            clearAccessTokens();
        }
    } else {
        ElMessage.error('获取菜单失败' + (res?.Message ? `,${JSON.stringify(res.Message)}` : '') + '请尝试切换账号');
        clearAccessTokens();
 
        return Promise.resolve(true);
    }
}
 
/**
 * 设置路由到 pinia routesList 中(已处理成多级嵌套路由)及缓存多级嵌套数组处理后的一维数组
 * @description 用于左侧菜单、横向菜单的显示
 * @description 用于 tagsView、菜单搜索中:未过滤隐藏的(isHide)
 */
export async function setFilterMenuAndCacheTagsViewRoutes() {
    const storesRoutesList = useRoutesList(pinia);
    storesRoutesList.setRoutesList(dynamicRoutes[0].children as any);
    setCacheTagsViewRoutes();
}
 
/**
 * 缓存多级嵌套数组处理后的一维数组
 * @description 用于 tagsView、菜单搜索中:未过滤隐藏的(isHide)
 */
export function setCacheTagsViewRoutes() {
    const storesTagsView = useTagsViewRoutes(pinia);
    storesTagsView.setTagsViewRoutes(formatTwoStageRoutes(formatFlatteningRoutes(dynamicRoutes))[0].children);
}
 
/**
 * 处理路由格式及添加捕获所有路由或 404 Not found 路由
 * @description 替换 dynamicRoutes(/@/router/route)第一个顶级 children 的路由
 * @returns 返回替换后的路由数组
 */
export function setFilterRouteEnd() {
    let filterRouteEnd: any = formatTwoStageRoutes(formatFlatteningRoutes(dynamicRoutes));
    // notFoundAndNoPower 防止 404、401 不在 layout 布局中,不设置的话,404、401 界面将全屏显示
    // 关联问题 No match found for location with path 'xxx'
    filterRouteEnd[0].children = [...filterRouteEnd[0].children, ...notFoundAndNoPower];
    return filterRouteEnd;
}
 
/**
 * 添加动态路由
 * @method router.addRoute
 * @description 此处循环为 dynamicRoutes(/@/router/route)第一个顶级 children 的路由一维数组,非多级嵌套
 * @link 参考:https://next.router.vuejs.org/zh/api/#addroute
 */
export async function setAddRoute() {
    await setFilterRouteEnd().forEach((route: RouteRecordRaw) => {
        router.addRoute(route);
    });
}
 
/**
 * 请求后端路由菜单接口
 * @description isRequestRoutes 为 true,则开启后端控制路由
 * @returns 返回后端路由菜单数据
 */
export async function getBackEndControlRoutes() {
    // 模拟 admin 与 test
    const stores = useUserInfo();
    let userInfo = (await stores.getUserInfo()) as any;
    const {
        SoftWare: { ID: SoftwareID },
        User: { ID: UserID },
    } = userInfo;
    const params = { SoftwareID, UserID };
    return menuApi.getAdminMenu(params);
    // const auth = userInfos.value.roles[0];
    // 管理员 admin
    // if (auth === 'admin') return menuApi.getAdminMenu();
    // 其它用户 test
    // else return menuApi.getTestMenu();
}
 
/**
 * 重新请求后端路由菜单接口
 * @description 用于菜单管理界面刷新菜单(未进行测试)
 * @description 路径:/src/views/system/menu/component/addMenu.vue
 */
// export async function setBackEndControlRefreshRoutes() {
//     await getBackEndControlRoutes();
// }
 
/**
 * 后端路由 component 转换
 * @param routes 后端返回的路由表数组
 * @returns 返回处理成函数后的 component
 */
export function backEndComponent(routes: any) {
    if (!routes) return;
    return routes.map((item: any) => {
        if (item.component) item.component = dynamicImport(dynamicViewsModules, item.component as string);
        item.children && backEndComponent(item.children);
        return item;
    });
}
 
/**
 * 后端路由 component 转换函数
 * @param dynamicViewsModules 获取目录下的 .vue、.tsx 全部文件
 * @param component 当前要处理项 component
 * @returns 返回处理成函数后的 component
 */
export function dynamicImport(dynamicViewsModules: Record<string, Function>, component: string) {
    const keys = Object.keys(dynamicViewsModules);
    const matchKeys = keys.filter((key) => {
        const k = key.replace(/..\/views|../, '');
        return k.startsWith(`${component}`) || k.startsWith(`/${component}`);
    });
    if (matchKeys?.length === 1) {
        const matchKey = matchKeys[0];
        return dynamicViewsModules[matchKey];
    }
    if (matchKeys?.length > 1) {
        return false;
    }
}