app.tsx 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import { useState } from 'react';
  2. import { PageLoading } from '@ant-design/pro-layout';
  3. import { notification, Modal } from 'antd';
  4. import { RequestConfig, history, useModel } 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: `${url}`,
  90. options: { ...options, interceptors: true, headers: authHeader },
  91. };
  92. };
  93. const responseInterceptorsHandle = async (response: Response, options: RequestOptionsInit) => {
  94. const _response: {
  95. data?: any;
  96. status: number;
  97. success?: boolean;
  98. msg?: string;
  99. } = await response.clone().json();
  100. if (_response.status == 200) {
  101. if (_response.data) {
  102. return _response.data;
  103. }
  104. notification.success({
  105. message: `操作成功!`,
  106. });
  107. return {
  108. status: _response.status,
  109. success: true,
  110. };
  111. } else {
  112. return {
  113. ..._response,
  114. };
  115. }
  116. };
  117. interface ErrorInfoStructure {
  118. success: boolean; // if request is success
  119. data?: any; // response data
  120. status?: number;
  121. errorCode: number;
  122. errorMessage: string;
  123. showType?: number;
  124. traceId?: string;
  125. host?: string;
  126. }
  127. interface ResponseErr extends Error {
  128. data?: any; // 这里是后端返回的原始数据
  129. info: ErrorInfoStructure;
  130. }
  131. const errorHandlerFunc = (error: ResponseErr) => {
  132. try {
  133. const { info } = error;
  134. const { errorCode , errorMessage } = info;
  135. if (errorCode == 499) {
  136. //token过期
  137. Modal.confirm({
  138. title: '抱歉,你的登录已过期,请重新登录!',
  139. // closable:false,
  140. maskClosable: false,
  141. // cancelButtonProps:
  142. onOk: () => {
  143. logoutHandle();
  144. return Promise.resolve(true);
  145. },
  146. });
  147. return;
  148. }
  149. if (errorMessage.length > 20) {
  150. notification.error({
  151. message: ` ${errorCode}:出现错误!`,
  152. description: errorMessage,
  153. });
  154. } else {
  155. notification.error({
  156. message: ` ${errorCode}:${errorMessage}`,
  157. });
  158. }
  159. } catch (err) {
  160. console.log({ errorHandlerFunc: err });
  161. notification.error({
  162. message: '遇到未知错误,查看控制台!',
  163. });
  164. }
  165. };
  166. export const request: RequestConfig = {
  167. timeout: 10000,
  168. errorConfig: {
  169. adaptor: (resData) => {
  170. if (!resData.success && resData.status != 200) {
  171. return {
  172. ...resData,
  173. };
  174. } else {
  175. return {
  176. success: true,
  177. status: 200,
  178. };
  179. }
  180. },
  181. },
  182. errorHandler: (err: any) => errorHandlerFunc(err),
  183. middlewares: [
  184. async function middlewareA(ctx, next) {
  185. await next();
  186. },
  187. async function middlewareB(ctx, next) {
  188. await next();
  189. },
  190. ],
  191. requestInterceptors: [requestInterceptorsHandle],
  192. responseInterceptors: [responseInterceptorsHandle],
  193. };
  194. // 从接口中获取子应用配置,export 出的 qiankun 变量是一个 promise
  195. export const qiankun = fetch('/config').then(() => ({
  196. // 注册子应用信息
  197. apps: [
  198. {
  199. name: 'app1', // 唯一 id
  200. //entry: '//112.124.59.133:8804', //测试
  201. entry: '//118.31.245.65:8804', //线上
  202. //entry:'//192.168.50.143:8804',//本机
  203. //entry: '//localhost:8804', // 开发
  204. },
  205. {
  206. name: 'reviewMana', // 唯一 id
  207. //entry: '//112.124.59.133:8807', //测试
  208. entry: '//118.31.245.65:8807', //线上
  209. //entry:'//192.168.50.143:8804',//本机
  210. //entry: '//localhost:8804', // 开发
  211. },
  212. ],
  213. // 完整生命周期钩子请看 https://qiankun.umijs.org/zh/api/#registermicroapps-apps-lifecycles
  214. lifeCycles: {
  215. afterMount: (props: any) => {},
  216. },
  217. // 支持更多的其他配置,详细看这里 https://qiankun.umijs.org/zh/api/#start-opts
  218. }));
  219. //向子应用透传
  220. export function useQiankunStateForSlave() {
  221. const [masterState, setMasterState] = useState({});
  222. return {
  223. masterState,
  224. setMasterState,
  225. };
  226. }
  227. export const layout = ({ initialState: { userData } }: { initialState: InitialStateType }): BasicLayoutProps => {
  228. return {
  229. headerRender: false,
  230. rightContentRender: () => <>right</>,
  231. footerRender: () => null,
  232. onPageChange: () => {
  233. //如果没有登录,重定向到 login
  234. if (!userData && location.pathname !== '/login') {
  235. // history.push('/login');
  236. }
  237. },
  238. menuHeaderRender: undefined,
  239. // ...initialState?.settings,
  240. };
  241. };