app.tsx 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. /*
  2. * @Author: your name
  3. * @Date: 2021-09-03 14:28:27
  4. * @LastEditTime: 2021-10-18 11:43:58
  5. * @LastEditors: Please set LastEditors
  6. * @Description: In User Settings Edit
  7. * @FilePath: /MedicalWisdomCheckSys/src/app.tsx
  8. */
  9. import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
  10. import { PageLoading } from '@ant-design/pro-layout';
  11. import { RunTimeLayoutConfig } from 'umi';
  12. import { history, Link } from 'umi';
  13. import { notification, Modal } from 'antd';
  14. import RightContent from '@/components/RightContent';
  15. // import Footer from '@/components/Footer';
  16. // import { currentUser as queryCurrentUser } from './services/ant-design-pro/api';
  17. import { BookOutlined, LinkOutlined } from '@ant-design/icons';
  18. import iconEnum from './menuIcons';
  19. import {loginOut} from '@/utils';
  20. import logoIcon from '../public/logo.png';
  21. import { getMenus } from './services/user';
  22. import {updateUserInfo} from '@/pages/user/Login/service';
  23. const isDev = process.env.NODE_ENV === 'development';
  24. const loginPath = '/user/login';
  25. let hospSign:any='';
  26. if(history){
  27. hospSign = history.location.query?.hospSign;
  28. if(!hospSign){
  29. hospSign = localStorage.getItem('hospSign');
  30. }
  31. }
  32. /** 获取用户信息比较慢的时候会展示一个 loading */
  33. export const initialStateConfig = {
  34. loading: <PageLoading />,
  35. };
  36. type menuDataItemType = {
  37. path:string,
  38. name:string,
  39. icon:any,
  40. component:string,
  41. children?:menuDataItemType[]
  42. }
  43. /**
  44. * @see https://umijs.org/zh-CN/plugins/plugin-initial-state
  45. * */
  46. export async function getInitialState(): Promise<{
  47. settings?: Partial<LayoutSettings>;
  48. currentUser?: API.CurrentUserData;
  49. logo?:String;
  50. isDev?:boolean,
  51. goSetting?:boolean,//设置栏触发
  52. resetPasswordHandle?:(formData:any)=>Promise<boolean>,
  53. fetchUserMenu?:()=>Promise<menuDataItemType[]>,
  54. menu?:menuDataItemType[],
  55. clearUserData?:() => Promise<boolean>; //清空用户数据
  56. fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
  57. }> {
  58. const fetchUserInfo = async () => {
  59. try {
  60. const userData = localStorage.getItem('userData');
  61. if(userData){
  62. return JSON.parse(userData);
  63. }
  64. throw Error;
  65. } catch (error) {
  66. history.push(`${loginPath}?hospSign=${hospSign}`);
  67. }
  68. return undefined;
  69. };
  70. const fetchUserMenu = async ()=>{
  71. const menu = await getMenus();
  72. if(menu){
  73. return menu;
  74. }
  75. }
  76. const resetPasswordHandle = async (data:API.EditUserInfoType)=>{
  77. const resp = await updateUserInfo(data);
  78. if(resp){
  79. return Promise.resolve(true);
  80. }
  81. return Promise.resolve(false);
  82. }
  83. const clearUserData = ()=>{
  84. localStorage.removeItem('userData');
  85. return Promise.resolve(true);
  86. };
  87. // 如果是登录页面,不执行
  88. if (history.location.pathname !== loginPath) {
  89. const currentUser = await fetchUserInfo();
  90. return {
  91. fetchUserInfo,
  92. currentUser,
  93. logo:logoIcon,
  94. clearUserData,
  95. menu:[],
  96. fetchUserMenu,
  97. resetPasswordHandle,
  98. isDev:process.env.NODE_ENV == 'development',
  99. settings: {
  100. navTheme:'dark',
  101. layout:'side'
  102. },
  103. };
  104. }
  105. return {
  106. fetchUserInfo,
  107. settings: {},
  108. };
  109. }
  110. type RequestOptionsInit = {
  111. [propsName:string]:any
  112. }
  113. const authHeaderInterceptor = (url: string, options: RequestOptionsInit) => {
  114. const userData = localStorage.getItem('userData');
  115. let authHeader = {token:''};
  116. if(userData){
  117. const {token}:API.CurrentUserData = JSON.parse(userData);
  118. authHeader.token = token;
  119. }
  120. return {
  121. url: `${url}`,
  122. options: { ...options, interceptors: true, headers: authHeader },
  123. };
  124. };
  125. const responseInterceptors = async (response: Response, options: RequestOptionsInit) => {
  126. // console.log({response,options});
  127. const requestMethod = options.method;
  128. const url = options.url;
  129. try {
  130. const {status} = response;
  131. if(status == 200){
  132. //网络请求成功
  133. const _response = await response.clone().json();
  134. const { status: dataStatus,errorCode,errorMessage,data} = _response;
  135. if(dataStatus == 200){
  136. //接口请求成功
  137. if(requestMethod=='POST'&&url != "/api/pfm/login"){
  138. notification.success({
  139. message:'操作成功!'
  140. });
  141. }
  142. if(data){
  143. return data;
  144. }
  145. return true;
  146. }else if(errorCode == 499){
  147. Modal.confirm({
  148. title: '抱歉,登录已过期请重新登录!',
  149. onOk: () => {
  150. loginOut();
  151. }
  152. });
  153. }else {
  154. //接口请求信息错误
  155. notification.error({
  156. message:errorMessage
  157. });
  158. }
  159. }else {
  160. //网络请求失败
  161. notification.error({
  162. message:'服务器错误!'
  163. });
  164. throw Error;
  165. }
  166. }catch(error){
  167. console.log({error});
  168. }
  169. return response;
  170. };
  171. type RequestConfig = {
  172. [propsName:string]:any
  173. }
  174. export const request: RequestConfig = {
  175. // 新增自动添加AccessToken的请求前拦截器
  176. errorHandler: (error:any) => {
  177. console.log({ error });
  178. throw error;
  179. },
  180. requestInterceptors: [authHeaderInterceptor],
  181. responseInterceptors: [responseInterceptors],
  182. };
  183. //将服务端获取的菜单 icon 字符串映射为对应的 icon Dom
  184. const mappingIcon = (menuData:menuDataItemType[]) => {
  185. if(menuData.length==0){
  186. console.log('空菜单');
  187. return [
  188. {
  189. path:'',
  190. name: '',
  191. icon: '',
  192. component: './404',
  193. }
  194. ]
  195. }else {
  196. const mappingMenu:menuDataItemType[] = menuData.map(item => ({
  197. ...item,
  198. icon: item.icon&&iconEnum[item.icon],
  199. children: item.children ? mappingIcon(item.children) : [],
  200. }));
  201. return mappingMenu;
  202. }
  203. };
  204. // ProLayout 支持的api https://procomponents.ant.design/components/layout
  205. export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  206. return {
  207. logo:initialState?.logo,
  208. rightContentRender: () => <RightContent />,
  209. disableContentMargin: false,
  210. waterMarkProps: {
  211. // content: initialState?.currentUser?.name,
  212. },
  213. // footerRender: () => <Footer />,
  214. onPageChange: () => {
  215. const { location } = history;
  216. // 如果没有登录,重定向到 login
  217. if (!initialState?.currentUser && location.pathname !== loginPath) {
  218. history.push(`${loginPath}?hospSign=${hospSign}`);
  219. }
  220. },
  221. menu: {
  222. params:{
  223. currentUser:initialState?.currentUser
  224. },
  225. request: async () => {
  226. // initialState.currentUser 中包含了所有用户信息
  227. if(initialState){
  228. const { currentUser,isDev} = initialState;
  229. if(isDev){
  230. //开发环境或超级账号
  231. return []
  232. }
  233. if (currentUser) {
  234. const data:menuDataItemType[] = await getMenus();
  235. if(data){
  236. return mappingIcon(data);
  237. }
  238. } else {
  239. return [
  240. {
  241. component: './404',
  242. }
  243. ]
  244. }
  245. }
  246. return []
  247. },
  248. },
  249. links: isDev
  250. ? [
  251. <Link to="/umi/plugin/openapi" target="_blank">
  252. <LinkOutlined />
  253. <span>OpenAPI 文档</span>
  254. </Link>,
  255. <Link to="/~docs">
  256. <BookOutlined />
  257. <span>业务组件文档</span>
  258. </Link>,
  259. ]
  260. : [],
  261. menuHeaderRender: undefined,
  262. // 自定义 403 页面
  263. // unAccessible: <div>unAccessible</div>,
  264. ...initialState?.settings,
  265. };
  266. };