app.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
  2. import { PageLoading } from '@ant-design/pro-layout';
  3. import { notification, Modal } from 'antd';
  4. import type { RequestConfig, RunTimeLayoutConfig } from 'umi';
  5. import { history, Link } from 'umi';
  6. import RightContent from '@/components/RightContent';
  7. import Footer from '@/components/Footer';
  8. import { BookOutlined, LinkOutlined } from '@ant-design/icons';
  9. import Service from '@/pages/user/Login/service';
  10. // import { service as SystemConfigService } from '@/pages/system/Config';
  11. import Token from '@/utils/token';
  12. import type { RequestOptionsInit } from 'umi-request';
  13. // import ReconnectingWebSocket from 'reconnecting-websocket';
  14. import SystemConst from '@/utils/const';
  15. import { service as MenuService } from '@/pages/system/Menu';
  16. import getRoutes, {
  17. extraRouteArr,
  18. getMenuPathByCode,
  19. getMenus,
  20. handleRoutes,
  21. saveMenusCache,
  22. getRoutesLayout,
  23. } from '@/utils/menu';
  24. import { AIcon } from '@/components';
  25. import React from 'react';
  26. import 'moment/dist/locale/zh-cn';
  27. import moment from 'moment';
  28. moment.locale('zh-cn');
  29. const isDev = process.env.NODE_ENV === 'development';
  30. const loginPath = '/user/login';
  31. const bindPath = '/account/center/bind';
  32. const licensePath = '/init-license';
  33. const oauthPath = '/oauth';
  34. let extraRoutes: any[] = [];
  35. // const { permission: userPermission } = usePermissions('system/License');
  36. /** 获取用户信息比较慢的时候会展示一个 loading */
  37. export const initialStateConfig = {
  38. loading: <PageLoading />,
  39. };
  40. /**
  41. * @see https://umijs.org/zh-CN/plugins/plugin-initial-state
  42. * */
  43. export async function getInitialState(): Promise<{
  44. settings?: Partial<LayoutSettings>;
  45. currentUser?: UserInfo;
  46. fetchUserInfo?: () => Promise<UserInfo | undefined>;
  47. }> {
  48. const fetchUserInfo = async () => {
  49. try {
  50. const user = await Service.queryCurrent();
  51. const detail = await Service.userDetail();
  52. // console.log(user.result,'user')
  53. return {
  54. ...user.result,
  55. user: {
  56. ...user.result.user,
  57. avatar: detail.result.avatar,
  58. },
  59. };
  60. } catch (error) {
  61. history.push(loginPath);
  62. }
  63. return undefined;
  64. };
  65. const getSettings = async () => {
  66. try {
  67. const res = await Service.settingDetail('front');
  68. return res.result;
  69. } catch (error) {
  70. history.push(loginPath);
  71. }
  72. return undefined;
  73. };
  74. // 如果是登录页面,不执行
  75. if (
  76. history.location.pathname !== loginPath &&
  77. history.location.pathname !== bindPath &&
  78. history.location.pathname !== licensePath &&
  79. history.location.pathname !== oauthPath
  80. ) {
  81. const currentUser = await fetchUserInfo();
  82. const settings = await getSettings();
  83. return {
  84. fetchUserInfo,
  85. currentUser,
  86. settings: settings,
  87. };
  88. }
  89. // 链接websocket
  90. // const url = `${document.location.protocol.replace('http', 'ws')}//${document.location.host}/${
  91. // SystemConst.API_BASE
  92. // }/messaging/${Token.get()}?:X_Access_Token=${Token.get()}`;
  93. //
  94. // const ws = new ReconnectingWebSocket(url);
  95. //
  96. // // ws.send('sss');
  97. // ws.onerror = () => {
  98. // console.log('链接错误。ws');
  99. // };
  100. return {
  101. fetchUserInfo,
  102. settings: {},
  103. };
  104. }
  105. /**
  106. * 异常处理程序
  107. 200: '服务器成功返回请求的数据。',
  108. 201: '新建或修改数据成功。',
  109. 202: '一个请求已经进入后台排队(异步任务)。',
  110. 204: '删除数据成功。',
  111. 400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
  112. 401: '用户没有权限(令牌、用户名、密码错误)。',
  113. 403: '用户得到授权,但是访问是被禁止的。',
  114. 404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
  115. 405: '请求方法不被允许。',
  116. 406: '请求的格式不可得。',
  117. 410: '请求的资源被永久删除,且不会再得到的。',
  118. 422: '当创建一个对象时,发生一个验证错误。',
  119. 500: '服务器发生错误,请检查服务器。',
  120. 502: '网关错误。',
  121. 503: '服务不可用,服务器暂时过载或维护。',
  122. 504: '网关超时。',
  123. //-----English
  124. 200: The server successfully returned the requested data. ',
  125. 201: New or modified data is successful. ',
  126. 202: A request has entered the background queue (asynchronous task). ',
  127. 204: Data deleted successfully. ',
  128. 400: 'There was an error in the request sent, and the server did not create or modify data. ',
  129. 401: The user does not have permission (token, username, password error). ',
  130. 403: The user is authorized, but access is forbidden. ',
  131. 404: The request sent was for a record that did not exist. ',
  132. 405: The request method is not allowed. ',
  133. 406: The requested format is not available. ',
  134. 410':
  135. 'The requested resource is permanently deleted and will no longer be available. ',
  136. 422: When creating an object, a validation error occurred. ',
  137. 500: An error occurred on the server, please check the server. ',
  138. 502: Gateway error. ',
  139. 503: The service is unavailable. ',
  140. 504: The gateway timed out. ',
  141. * @see https://beta-pro.ant.design/docs/request-cn
  142. */
  143. /**
  144. * Token 拦截器
  145. * @param url
  146. * @param options
  147. */
  148. const filterUrl = [
  149. '/authorize/captcha/config',
  150. '/authorize/login',
  151. '/sso/bind-code/',
  152. '/sso/providers',
  153. ];
  154. const requestInterceptor = (url: string, options: RequestOptionsInit) => {
  155. // const {params} = options;
  156. let authHeader = {};
  157. if (!filterUrl.some((fUrl) => url.includes(fUrl))) {
  158. authHeader = { 'X-Access-Token': Token.get() || '' };
  159. }
  160. return {
  161. url: `${url}`,
  162. options: {
  163. ...options,
  164. // 格式化成后台需要的查询参数
  165. // params: encodeQueryParam(params),
  166. interceptors: true,
  167. headers: authHeader,
  168. },
  169. };
  170. };
  171. export const request: RequestConfig = {
  172. errorHandler: (error: any) => {
  173. const { response } = error;
  174. if (response.status === 401) {
  175. history.push('/user/login');
  176. return {};
  177. }
  178. if (
  179. response.status === 400 ||
  180. response.status === 500 ||
  181. response.status === 404 ||
  182. response.status === 403
  183. ) {
  184. // 添加clone() 避免后续其它地方用response.text()时报错
  185. response
  186. .clone()
  187. .text()
  188. .then((resp: string) => {
  189. if (resp) {
  190. notification.error({
  191. key: 'error',
  192. message: JSON.parse(resp || '{}').message || '服务器内部错误!',
  193. });
  194. if (JSON.parse(resp || '{}').code === 'license required') {
  195. //判断按钮权限
  196. let buttons = {};
  197. const buttonString = localStorage.getItem('MENUS_BUTTONS_CACHE');
  198. buttons = JSON.parse(buttonString || '{}');
  199. //判读是否是退出登录状态
  200. if (Object.keys(buttons) && Object.keys(buttons).length !== 0) {
  201. Modal.error({
  202. title: 'License已到期或者错误',
  203. content: (
  204. <>
  205. {buttons['system/License']?.includes('update') ? (
  206. <a
  207. onClick={() => {
  208. Modal.destroyAll();
  209. window.location.href = '/#/init-license';
  210. }}
  211. >
  212. 请更新License
  213. </a>
  214. ) : (
  215. '请联系管理员更新license'
  216. )}
  217. </>
  218. ),
  219. });
  220. } else {
  221. Modal.error({
  222. title: 'License已到期或者错误',
  223. content: (
  224. <a
  225. onClick={() => {
  226. Modal.destroyAll();
  227. window.location.href = '/#/init-license';
  228. }}
  229. >
  230. 请更新License
  231. </a>
  232. ),
  233. });
  234. }
  235. }
  236. } else {
  237. response
  238. .clone()
  239. .json()
  240. .then((res: any) => {
  241. notification.error({
  242. key: 'error',
  243. message: `请求错误:${res.message}`,
  244. });
  245. })
  246. .catch(() => {
  247. notification.error({
  248. key: 'error',
  249. message: '系统开小差,请稍后重试',
  250. });
  251. });
  252. }
  253. });
  254. return response;
  255. }
  256. if (!response) {
  257. notification.error({
  258. description: '网络异常,请检查网络连接',
  259. message: '网络异常',
  260. });
  261. }
  262. return response;
  263. },
  264. requestInterceptors: [requestInterceptor],
  265. };
  266. const MenuItemIcon = (
  267. menuItemProps: any,
  268. defaultDom: React.ReactNode,
  269. props: any,
  270. ): React.ReactNode => {
  271. if (defaultDom) {
  272. // @ts-ignore
  273. const menuItem = React.cloneElement(defaultDom, {
  274. // @ts-ignore
  275. children: [<AIcon type={menuItemProps.icon as string} />, defaultDom.props.children[1]],
  276. ...props,
  277. });
  278. return menuItem;
  279. }
  280. return defaultDom;
  281. };
  282. // ProLayout 支持的api https://procomponents.ant.design/components/layout
  283. export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  284. // console.log({ ...initialState });
  285. const ico: any = document.querySelector('link[rel="icon"]');
  286. if (ico !== null) {
  287. Service.settingDetail('front').then((res) => {
  288. if (res.status === 200) {
  289. // console.log(res.result.ico)
  290. ico.href = res.result.ico;
  291. }
  292. });
  293. }
  294. return {
  295. navTheme: 'light',
  296. headerTheme: 'light',
  297. rightContentRender: () => <RightContent />,
  298. disableContentMargin: false,
  299. waterMarkProps: {
  300. // content: initialState?.currentUser?.name,
  301. },
  302. itemRender: (route, _, routes) => {
  303. const isToParentUrl = getMenuPathByCode('notice');
  304. const chilck = routes.indexOf(route) !== 0;
  305. const goto = routes.some((item) => {
  306. if (!route.path.includes('iot')) {
  307. return routes.indexOf(route) <= 1;
  308. } else {
  309. if (route.path.includes('notice')) {
  310. return item.path.indexOf(isToParentUrl) > -1;
  311. } else {
  312. return routes.indexOf(route) > 1;
  313. }
  314. }
  315. });
  316. return chilck && goto && route.path !== '/iot/link/Channel' ? (
  317. <Link to={route.path}>{route.breadcrumbName}</Link>
  318. ) : (
  319. <span>{route.breadcrumbName}</span>
  320. );
  321. },
  322. footerRender: () => <Footer />,
  323. onPageChange: () => {
  324. const { location } = history;
  325. // 如果没有登录,重定向到 login
  326. if (
  327. !initialState?.currentUser &&
  328. location.pathname !== loginPath &&
  329. location.pathname !== bindPath &&
  330. location.pathname !== licensePath &&
  331. location.pathname !== oauthPath
  332. ) {
  333. history.push(loginPath);
  334. }
  335. },
  336. menuDataRender: () => {
  337. return getMenus(extraRoutes);
  338. },
  339. subMenuItemRender: MenuItemIcon,
  340. menuItemRender: (menuItemProps, defaultDom) => {
  341. return MenuItemIcon(menuItemProps, defaultDom, {
  342. onClick: () => {
  343. history.push(menuItemProps.path!);
  344. },
  345. });
  346. },
  347. // menuRender:(props,defaultDom)=>{
  348. // console.log(defaultDom,'11111111111111')
  349. // return true
  350. // },
  351. // headerRender:false,
  352. links: isDev
  353. ? [
  354. <Link key={1} to="/umi/plugin/openapi" target="_blank">
  355. <LinkOutlined />
  356. <span>OpenAPI 文档</span>
  357. </Link>,
  358. <Link key={2} to="/~docs">
  359. <BookOutlined />
  360. <span>业务组件文档</span>
  361. </Link>,
  362. ]
  363. : [],
  364. menuHeaderRender: undefined,
  365. ...initialState?.settings,
  366. // 自定义 403 页面
  367. // unAccessible: <div>unAccessible</div>,
  368. pageTitleRender: (_props, _, info) => {
  369. if (initialState?.settings?.title) {
  370. return info?.pageName + ' - ' + initialState?.settings?.title;
  371. } else {
  372. return info?.pageName;
  373. }
  374. },
  375. title: (
  376. <div
  377. title={initialState?.settings?.title || ''}
  378. style={{
  379. maxWidth: 150,
  380. overflow: 'hidden',
  381. textOverflow: 'ellipsis',
  382. whiteSpace: 'nowrap',
  383. }}
  384. >
  385. {initialState?.settings?.title}
  386. </div>
  387. ),
  388. };
  389. };
  390. export function patchRoutes(routes: any) {
  391. if (extraRoutes && extraRoutes.length) {
  392. const basePath = routes.routes.find((_route: any) => _route.path === '/')!;
  393. const _routes = getRoutes(extraRoutes);
  394. const baseRedirect = {
  395. path: '/',
  396. routes: [
  397. ..._routes,
  398. {
  399. path: '/',
  400. redirect: _routes[0].path,
  401. },
  402. ],
  403. };
  404. basePath.routes = [...basePath.routes, baseRedirect];
  405. // console.log(basePath.routes, 'basePath.routes,');
  406. }
  407. }
  408. export function render(oldRender: any) {
  409. if (![loginPath, bindPath, licensePath, oauthPath].includes(history.location.pathname)) {
  410. //过滤非集成的菜单
  411. const params = [
  412. {
  413. terms: [
  414. {
  415. terms: [
  416. {
  417. column: 'owner',
  418. termType: 'eq',
  419. value: 'iot',
  420. },
  421. {
  422. column: 'owner',
  423. termType: 'isnull',
  424. value: '1',
  425. type: 'or',
  426. },
  427. ],
  428. },
  429. ],
  430. },
  431. ];
  432. Service.settingDetail('api').then((res) => {
  433. if (res && res.status === 200 && res.result) {
  434. localStorage.setItem(SystemConst.AMAP_KEY, res.result.api);
  435. }
  436. });
  437. Service.getSystemVersion().then((resp) => {
  438. if (resp && resp.status === 200 && resp.result) {
  439. localStorage.setItem(SystemConst.Version_Code, resp.result.edition);
  440. const isCommunity = resp.result?.edition === 'community';
  441. MenuService.queryOwnThree({ paging: false, terms: params }).then((res) => {
  442. if (res && res.status === 200) {
  443. extraRoutes = handleRoutes([...res.result, ...extraRouteArr], isCommunity);
  444. saveMenusCache(extraRoutes);
  445. }
  446. oldRender();
  447. });
  448. }
  449. });
  450. } else {
  451. oldRender();
  452. }
  453. }
  454. export function onRouteChange({ routes, location }: any) {
  455. // console.log(11111111111)
  456. // debugger;
  457. if (location.query && location.query.layout === 'false') {
  458. // console.log(routes, 'onRouteChange')
  459. const basePath = routes.find((_route: any) => _route.path === '/')!;
  460. const _routes = getRoutesLayout(extraRoutes);
  461. const baseRedirect = {
  462. path: '/',
  463. layout: false,
  464. routes: [
  465. ..._routes,
  466. {
  467. path: '/',
  468. layout: false,
  469. redirect: _routes[0].path,
  470. },
  471. ],
  472. };
  473. // debugger
  474. basePath.routes = [...basePath.routes, baseRedirect];
  475. }
  476. }