ny
昨天 282fbc6488f4e8ceb5fda759f963ee88fbf7b999
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
/* eslint-disable no-template-curly-in-string */
import type { RouteRecordRaw } from 'vue-router';
 
import type {
  BackMenu,
  ComponentRecordType,
  GenerateMenuAndRoutesOptions,
} from '@vben-core/typings';
 
import { defineAsyncComponent, defineComponent, h } from 'vue';
 
import { mapTree } from '@vben-core/shared/utils';
 
import qs from 'qs';
 
/**
 * 动态生成路由 - 后端方式
 */
async function generateRoutesByBackend(
  options: GenerateMenuAndRoutesOptions,
): Promise<RouteRecordRaw[]> {
  const { layoutMap = {}, pageMap = {}, backMenus = [] } = options;
 
  try {
    const menuRoutes = backMenus;
    if (!menuRoutes) {
      return [];
    }
 
    const normalizePageMap: ComponentRecordType = {};
 
    for (const [key, value] of Object.entries(pageMap)) {
      normalizePageMap[normalizeViewPath(key)] = value;
    }
 
    const routes = convertRoutes(
      menuRoutes,
      layoutMap,
      normalizePageMap,
      options.globSetting,
      options.token,
      options.appEnCode,
      options.appPrefix,
    );
 
    return routes;
  } catch (error) {
    console.error(error);
    throw error;
  }
}
 
function convertRoutes(
  routes: BackMenu[],
  layoutMap: ComponentRecordType,
  pageMap: ComponentRecordType,
  globSetting: any,
  token: string | undefined,
  appEnCode: string | undefined,
  appPrefix: string | undefined,
): RouteRecordRaw[] {
  for (const route of routes) {
    route.component = 'BasicLayout';
  }
 
  return mapTree(routes, (node: BackMenu) => {
    const name = getRouteName(node.enCode);
    const route: any = {
      name,
      meta: {
        icon: node.icon,
        title: node.fullName,
        i18nCode: `routes.${node.enCode.replaceAll('.', '-')}`,
        modelId: node.id,
        type: node.type,
      },
    };
    // 应用/目录
    if (node.type == 0 || node.type == 1) {
      route.path = `/${node.enCode.replaceAll('.', '/')}`;
      if (node.component) route.component = layoutMap[node.component];
      if (node.children?.length) route.children = node.children;
    }
    // 确保路径以 '/' 开头
    const urlAddress =
      node.urlAddress && node.urlAddress.startsWith('/')
        ? node.urlAddress
        : `/${node.urlAddress}`;
    let routePath = urlAddress;
    let query = {};
    if (urlAddress.includes('?')) {
      routePath = urlAddress.split('?')[0] as string;
      try {
        if (urlAddress.split('?')[1]) {
          query = qs.parse(urlAddress.split('?')[1] as string);
        }
      } catch {}
    }
    // 2-页面、11-回传表单
    if ([2, 11].includes(node.type)) {
      route.path = routePath;
      route.meta.query = query;
      route.component = dynamicImport(
        node.pageAddress ?? node.urlAddress,
        layoutMap,
        pageMap,
      );
    }
    // 3-表单、4-字典、5-报表(原)、8-门户、9-流程、10-报表
    if ([3, 4, 5, 8, 9, 10].includes(node.type)) {
      let component = '';
      let isTree = 0;
      const propertyJson = node.propertyJson
        ? JSON.parse(node.propertyJson)
        : null;
      let relationId: string = '';
      if (propertyJson) {
        relationId = propertyJson.moduleId || '';
        isTree = propertyJson.isTree || 0;
      }
      if (node.type == 3 || node.type == 9) {
        component = 'OnlineModel';
      } else if (node.type == 4) {
        component = 'OnlineDict';
      } else if (node.type == 5) {
        component = 'OnlineDataReport';
      } else if (node.type == 10) {
        component = 'OnlineReport';
      } else {
        component = 'OnlinePortal';
      }
      route.path = routePath;
      route.meta.query = query;
      route.name = component + name;
      route.component = createCustomComponent(
        route.name,
        defineAsyncComponent(layoutMap[`${component}View`] as any),
      );
      route.meta.relationId = relationId;
      route.meta.isTree = isTree;
    }
    // 大屏
    if (node.type == 6) {
      let moduleId = '';
      const propertyJson = node.propertyJson
        ? JSON.parse(node.propertyJson)
        : null;
      if (propertyJson) moduleId = propertyJson.moduleId || '';
      route.meta.link = `${globSetting.dataVUrl || ''}${appEnCode ? `${appPrefix}${appEnCode}/` : ''}view/${moduleId}?token=${token || ''}`;
      route.path = `/${node.enCode.replaceAll('.', '/')}`;
      route.component = layoutMap.IFrameView;
    }
    // 外链
    if (node.type == 7) {
      route.path = routePath;
      route.meta.query = query;
      route.component = layoutMap.IFrameView;
      const path = node.pageAddress
        .replaceAll(
          '${dataV}',
          (globSetting.dataVUrl || '') +
            (appEnCode ? `${appPrefix}${appEnCode}/` : ''),
        )
        .replaceAll('${jnpfToken}', token || '')
        .replaceAll('${jnpfAppCode}', appEnCode || '');
      if (node.linkTarget === '_self') {
        route.meta.iframeSrc = path;
      } else {
        route.meta.link = path;
        route.path = path;
      }
    }
 
    return route;
  });
}
 
function dynamicImport(
  path: string,
  layoutMap: ComponentRecordType,
  pageMap: ComponentRecordType,
) {
  const normalizePath = normalizeViewPath(path);
  let component =
    pageMap[
      normalizePath.endsWith('.vue') ? normalizePath : `${normalizePath}.vue`
    ];
  if (!component) {
    component = pageMap[`${normalizePath}/index.vue`];
  }
  if (!component) {
    component = layoutMap.NotFoundView;
  }
  return component;
}
 
function normalizeViewPath(path: string): string {
  // 去除相对路径前缀
  const normalizedPath = path.replace(/^(\.\/|\.\.\/)+/, '');
 
  // 确保路径以 '/' 开头
  const viewPath = normalizedPath.startsWith('/')
    ? normalizedPath
    : `/${normalizedPath}`;
 
  // 这里耦合了jnpf-admin的目录结构
  return viewPath.replace(/^\/views/, '');
}
 
/**
 * 将指定组件设置自定义名称
 *
 * @param {string} customName 组件自定义名称
 * @param {AsyncComponent} asyncComponent
 * @return {Component}
 */
function createCustomComponent(customName: string, asyncComponent: any) {
  return defineComponent({
    name: customName,
    setup() {
      return () => h(asyncComponent);
    },
  });
}
 
// 获取路由名称
function getRouteName(name) {
  const routeName = name
    .split('.')
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join('');
  return routeName;
}
 
export { generateRoutesByBackend };