app.tsx 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. import { useState } from 'react';
  2. import { PageLoading } from '@ant-design/pro-layout';
  3. import { notification, Modal } from 'antd';
  4. import { RequestConfig, history } from 'umi';
  5. import type { RequestOptionsInit } from 'umi-request';
  6. import { getHospSubSystemList, UserDataType } from '@/service/login';
  7. import { BasicLayoutProps } from '@ant-design/pro-layout';
  8. import { logoutHandle } from './global';
  9. import { Platforms } from './constant';
  10. import { SpacicalPageParamsType } from './typings';
  11. const loginPath = '/login';
  12. let hospSign: string = ''; //医院标识
  13. if (history && history.location.query) {
  14. hospSign = history.location.query.hospSign as string;
  15. if (!hospSign) {
  16. const localHospSign = localStorage.getItem('hospSign');
  17. hospSign = localHospSign ? localHospSign : '';
  18. }
  19. }
  20. /** 获取用户信息比较慢的时候会展示一个 loading */
  21. export const initialStateConfig = {
  22. loading: <PageLoading />,
  23. };
  24. type InitialStateType = {
  25. userData?: UserDataType;
  26. systemLists?: TopBar.Tab[]; //当前医院可选子系统列表
  27. openedSysLists?: TopBar.Tab[]; //当前已打开的系统列表
  28. currentSelectedSys?: TopBar.Tab; //当前选中的tab
  29. logout?: () => Promise<boolean>;
  30. childAppIsShowMenu?: boolean;
  31. spacicalPageParamsType?: SpacicalPageParamsType[];
  32. getHospSubSystemListFunc?: () => Promise<any[]>;
  33. };
  34. export async function getInitialState(): Promise<InitialStateType> {
  35. const fetchUserInfo = async () => {
  36. try {
  37. const userData = localStorage.getItem('userData');
  38. if (userData) {
  39. return JSON.parse(userData);
  40. }
  41. throw Error;
  42. } catch (error) {
  43. history.push(`${loginPath}?hospSign=${hospSign}`);
  44. }
  45. return undefined;
  46. };
  47. const getAppIcon = (name: string) => {
  48. return Platforms.filter((i) => i.name == name).length > 0 ? Platforms.filter((i) => i.name == name)[0].logo : '';
  49. };
  50. //获取当前账号所有子应用列表
  51. const getHospSubSystemListFunc = async () => {
  52. const data = await getHospSubSystemList();
  53. if (data) {
  54. const _data = data.map((t) => ({
  55. ...t,
  56. icon: getAppIcon(t.name),
  57. path: t.path,
  58. }));
  59. return _data;
  60. }
  61. return [];
  62. };
  63. const logout = logoutHandle;
  64. const userData = await fetchUserInfo();
  65. let systemLists: userRelationInfo.OwnAppsItem[] = [];
  66. if (userData) {
  67. systemLists = await getHospSubSystemListFunc();
  68. }
  69. const localInitData = localStorage.getItem('initialState');
  70. return {
  71. currentSelectedSys: undefined,
  72. openedSysLists: [],
  73. ...JSON.parse(localInitData ? localInitData : '{}'), //覆盖,恢复tab状态
  74. userData,
  75. logout,
  76. spacicalPageParamsType: [],
  77. getHospSubSystemListFunc,
  78. systemLists: systemLists,
  79. };
  80. }
  81. const requestInterceptorsHandle = (url: string, options: RequestOptionsInit) => {
  82. const userData = localStorage.getItem('userData');
  83. let authHeader = { token: '' };
  84. if (userData) {
  85. const { token } = JSON.parse(userData);
  86. authHeader.token = token;
  87. }
  88. return {
  89. url: `/gateway${url}`,
  90. options: { ...options, interceptors: true, headers: authHeader, timeout: 100000000, },
  91. };
  92. };
  93. const responseInterceptorsHandle = async (response: Response, options: RequestOptionsInit) => {
  94. const _response: {
  95. message: any;
  96. data?: any;
  97. status: number;
  98. success?: boolean;
  99. msg?: string;
  100. } = await response.clone().json();
  101. if (_response.status == 200) {
  102. if (_response.data) {
  103. return _response.data;
  104. }
  105. notification.success({
  106. message: `操作成功!`,
  107. });
  108. return {
  109. status: _response.status,
  110. success: true,
  111. };
  112. } else {
  113. notification.error({
  114. message: `${_response.msg?_response.msg:_response.message}`,
  115. });
  116. return false
  117. }
  118. };
  119. interface ErrorInfoStructure {
  120. success: boolean; // if request is success
  121. data?: any; // response data
  122. status?: number;
  123. errorCode: number;
  124. errorMessage: string;
  125. showType?: number;
  126. traceId?: string;
  127. host?: string;
  128. }
  129. interface ResponseErr extends Error {
  130. data?: any; // 这里是后端返回的原始数据
  131. info: ErrorInfoStructure;
  132. }
  133. const errorHandlerFunc = (error: ResponseErr) => {
  134. try {
  135. const { info } = error;
  136. const { errorCode, errorMessage } = info;
  137. if (errorCode == 499) {
  138. //token过期
  139. Modal.confirm({
  140. title: '抱歉,你的登录已过期,请重新登录!',
  141. // closable:false,
  142. maskClosable: false,
  143. // cancelButtonProps:
  144. onOk: () => {
  145. logoutHandle();
  146. return Promise.resolve(true);
  147. },
  148. });
  149. return;
  150. }
  151. if (errorMessage.length > 20) {
  152. notification.error({
  153. message: ` ${errorCode}:出现错误!`,
  154. description: errorMessage,
  155. });
  156. } else if(false){
  157. }else{
  158. notification.error({
  159. message: ` ${errorCode}:${errorMessage}`,
  160. });
  161. }
  162. } catch (err) {
  163. console.log({ errorHandlerFunc: err });
  164. notification.error({
  165. message: '遇到未知错误,查看控制台!',
  166. });
  167. }
  168. };
  169. export const request: RequestConfig = {
  170. timeout: 10000,
  171. errorConfig: {
  172. adaptor: (resData) => {
  173. if (!resData.success && resData.status != 200) {
  174. return {
  175. ...resData,
  176. };
  177. } else {
  178. return {
  179. success: true,
  180. status: 200,
  181. };
  182. }
  183. },
  184. },
  185. errorHandler: (err: any) => errorHandlerFunc(err),
  186. middlewares: [
  187. async function middlewareA(ctx, next) {
  188. await next();
  189. },
  190. async function middlewareB(ctx, next) {
  191. await next();
  192. },
  193. ],
  194. requestInterceptors: [requestInterceptorsHandle],
  195. responseInterceptors: [responseInterceptorsHandle],
  196. };
  197. // 从接口中获取子应用配置,export 出的 qiankun 变量是一个 promise
  198. export const qiankun = fetch('/config').then(() => ({
  199. // 注册子应用信息
  200. apps: [
  201. // {
  202. // name: 'microApp', // 唯一 id
  203. // entry: '//localhost:8808', // 开发
  204. // },
  205. // {
  206. // name: 'app1', // 唯一 id
  207. // entry: '//120.27.235.181:8804', //测试
  208. // },
  209. // {
  210. // name: 'reviewMana', // 唯一 id
  211. // entry: '//120.27.235.181:8807',
  212. // //entry: '//localhost:8804', //本地调试
  213. // },
  214. {
  215. name: 'budgetManaSystem', // 唯一 id
  216. //entry: '//localhost:8001',
  217. //entry: '//120.27.235.181:5000/perform/', //开发
  218. entry: '//47.96.149.190:5000/perform/', //演示
  219. },
  220. {
  221. name: 'PFMBackC', // 唯一 id
  222. entry: '//120.27.235.181:5000/pfmManager/index.html'
  223. //entry: '//112.124.59.133:5000/perform/', // 开发
  224. },
  225. ],
  226. // 完整生命周期钩子请看 https://qiankun.umijs.org/zh/api/#registermicroapps-apps-lifecycles
  227. lifeCycles: {
  228. afterMount: (props: any) => { },
  229. },
  230. // 支持更多的其他配置,详细看这里 https://qiankun.umijs.org/zh/api/#start-opts
  231. }));
  232. //向子应用透传
  233. export function useQiankunStateForSlave() {
  234. const [masterState, setMasterState] = useState({});
  235. return {
  236. masterState,
  237. setMasterState,
  238. };
  239. }
  240. // //@/pages/platform/setting/reports/index
  241. export function patchRoutes({ routes }: { routes: any }) {
  242. const treeLoop = (treeData: any) => {
  243. if (treeData.path == '/platform') {
  244. if (treeData.routes) {
  245. const paths = [...new Array(100).keys()].map((a, index) => ({
  246. path: `${treeData.path == '/' ? '' : treeData.path}/reports/${index}`,
  247. exact: true,
  248. component: require('@/pages/platform/setting/reports/index.tsx').default,
  249. }));
  250. const lanhuPagePaths = [...new Array(100).keys()].map((a, index) => ({
  251. path: `${treeData.path == '/' ? '' : treeData.path}/static/${index}`,
  252. exact: true,
  253. component:require('@/pages/platform/setting/static/index.tsx').default,
  254. }));
  255. //console.log({paths});
  256. paths.forEach((a: any) => {
  257. treeData.routes.push(a);
  258. });
  259. lanhuPagePaths.forEach((a: any) => {
  260. treeData.routes.push(a);
  261. });
  262. }
  263. }
  264. if (treeData.routes && treeData.routes.length > 0) {
  265. treeData.routes.forEach((a: any) => {
  266. treeLoop(a);
  267. })
  268. }
  269. }
  270. treeLoop(routes[0]);
  271. }
  272. export const layout = ({ initialState: { userData } }: { initialState: InitialStateType }): BasicLayoutProps => {
  273. return {
  274. headerRender: false,
  275. rightContentRender: () => <>right</>,
  276. footerRender: () => null,
  277. onPageChange: () => {
  278. //如果没有登录,重定向到 login
  279. if (!userData && location.pathname !== '/login') {
  280. // history.push('/login');
  281. }
  282. },
  283. menuHeaderRender: undefined,
  284. // ...initialState?.settings,
  285. };
  286. };