app.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. import React from 'react';
  2. import { BasicLayoutProps, Settings as LayoutSettings, MenuDataItem } from '@ant-design/pro-layout';
  3. import { Button, notification, Result } from 'antd';
  4. import { history } from 'umi';
  5. import RightContent from '@/components/RightContent';
  6. import { ResponseError } from 'umi-request';
  7. import { queryCurrent, getMenu } from './services/user';
  8. import defaultSettings from '../config/defaultSettings';
  9. import { DesktopOutlined, MessageOutlined, SendOutlined, TeamOutlined, QrcodeOutlined, DatabaseOutlined, ReadOutlined, MobileOutlined, FundViewOutlined, RadarChartOutlined, BarChartOutlined, WechatOutlined, BookOutlined, FileImageOutlined, EyeOutlined, UserOutlined } from '@ant-design/icons';
  10. import { getMyMenu, headrRouter } from '../config/routerConfig';
  11. import { ReactComponent as LaunchSvg } from '@/assets/launch.svg'
  12. import { ReactComponent as AdLaunchSvg } from '@/assets/adLaunch.svg'
  13. import { ReactComponent as MaterialSvg } from '@/assets/material.svg'
  14. import { ReactComponent as NumberSvg } from '@/assets/number.svg'
  15. import { ReactComponent as GameSvg } from '@/assets/game.svg'
  16. import versions from './utils/versions';
  17. interface CurrentUser {
  18. avatar?: string;
  19. name?: string;
  20. title?: string;
  21. group?: string;
  22. signature?: string;
  23. tags?: {
  24. key: string;
  25. label: string;
  26. }[];
  27. userId?: string;
  28. powerLevel?: number;
  29. access?: 'user' | 'guest' | 'admin' | any;
  30. unreadCount?: number;
  31. companyList?: any[],
  32. onlineCompanyId?: number
  33. }
  34. export async function getInitialState(): Promise<{
  35. currentUser?: CurrentUser;
  36. settings?: LayoutSettings;
  37. menu?: any,
  38. loading?: boolean,
  39. collapsed?: string,
  40. onCollapse?: (onCollapse: boolean) => void
  41. }> {
  42. // 如果是登录页面,不执行
  43. if (localStorage.getItem('Admin-Token')) {
  44. //开始版本号对比
  45. versions()
  46. try {
  47. sessionStorage.removeItem('msg')
  48. let currentUser = {}
  49. let userInfo: any = await queryCurrent();//用户信息
  50. let companyInfo = userInfo?.data?.companyRelationInfo?.filter((item: { companyId: number }) => item.companyId !== 4 && item.companyId !== 3)
  51. currentUser = { access: 'admin', powerLevel: userInfo?.data?.userInfo?.powerLevel, name: userInfo?.data?.userInfo?.nickname || '', userId: userInfo?.data?.userInfo?.userId, phone: userInfo?.data?.userInfo?.phone || '', companyList: companyInfo, onlineCompanyId: userInfo?.data?.onlineCompanyId }//处理个人信息
  52. let menu: any = await getMenu().then((res: any) => {//获取菜单并处理
  53. let { code, data } = res
  54. let path = getMyMenu(code, data)
  55. return { data: path }
  56. });
  57. localStorage.setItem('sex', userInfo?.data?.userInfo?.sex)
  58. localStorage.setItem('userId', userInfo?.data?.userInfo?.userId)
  59. localStorage.setItem('name', userInfo?.data?.userInfo?.nickname)
  60. return {
  61. currentUser,
  62. settings: { ...defaultSettings },
  63. loading: false,
  64. menu,
  65. collapsed: '0',
  66. onCollapse: (collapsed: boolean) => {
  67. let v = collapsed ? '1' : '0'
  68. localStorage.setItem('collapsed', v)
  69. }
  70. };
  71. } catch (error) {
  72. console.log(111111, error)
  73. history.push('/user/login');
  74. }
  75. }
  76. return {
  77. settings: defaultSettings,
  78. };
  79. }
  80. // 枚举转译服务端菜单icon
  81. const IconMap = {
  82. desktop: <DesktopOutlined />,
  83. message: <MessageOutlined />,
  84. send: <SendOutlined />,
  85. team: <TeamOutlined />,
  86. database: <DatabaseOutlined />,
  87. qrcode: <QrcodeOutlined />,
  88. read: <ReadOutlined />,
  89. mobile: <MobileOutlined />,
  90. fundView: <FundViewOutlined />,
  91. radarChart: <RadarChartOutlined />,
  92. barChart: <BarChartOutlined />,
  93. wechat: <WechatOutlined />,
  94. book: <BookOutlined />,
  95. peoples: <UserOutlined />,
  96. 'file-image': <FileImageOutlined />,
  97. launch: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><LaunchSvg /></span>,
  98. adLaunch: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><AdLaunchSvg /></span>,
  99. material: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><MaterialSvg /></span>,
  100. number: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><NumberSvg /></span>,
  101. game: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><GameSvg /></span>,
  102. eye: <EyeOutlined />
  103. };
  104. //处理菜单
  105. const loopMenuItem = (menus: MenuDataItem[],): MenuDataItem[] => {
  106. let menu = menus?.map(({ icon, routes, roles, ...item }) => {
  107. let newItem = JSON.parse(JSON.stringify(item))
  108. newItem.key = item?.path || item?.key
  109. return {
  110. ...newItem,
  111. hideInMenu: false,//校验隐藏菜单
  112. icon: icon && IconMap[icon as string],
  113. children: routes && loopMenuItem(routes),
  114. }
  115. })
  116. return menu
  117. }
  118. export const layout = ({
  119. initialState
  120. }: {
  121. initialState: { settings?: LayoutSettings; currentUser?: CurrentUser; menu?: any; loading: boolean, collapsed: string, onCollapse: any };
  122. }): BasicLayoutProps => {
  123. return {
  124. menuDataRender: () => {
  125. return loopMenuItem(initialState?.menu?.data || [])
  126. },//解析服务端菜单
  127. rightContentRender: () => <RightContent />,
  128. disableContentMargin: false,
  129. collapsed: localStorage.collapsed === '1',
  130. onCollapse: initialState.onCollapse,
  131. breakpoint: false,
  132. // footerRender: () => <Footer />,
  133. onPageChange: () => {
  134. headrRouter(initialState, history)
  135. let { pathname, query } = history.location
  136. if (query?.t) {//带token直接进入对应页面
  137. localStorage.setItem('Admin-Token', decodeURIComponent(query.t as any))
  138. location.href = window.location.origin + '/#' + pathname
  139. location.reload()
  140. } else if (!initialState?.currentUser?.name && history.location.pathname !== '/user/login') {
  141. history.push('/user/login');
  142. }
  143. },
  144. splitMenus: true,//配合mix分割菜单
  145. menuHeaderRender: undefined,
  146. ...initialState?.settings,
  147. };
  148. };
  149. const codeMessage = {
  150. 200: '服务器成功返回请求的数据。',
  151. 201: '新建或修改数据成功。',
  152. 202: '一个请求已经进入后台排队(异步任务)。',
  153. 204: '删除数据成功。',
  154. 400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
  155. 401: '用户没有权限(令牌、用户名、密码错误)。',
  156. 403: '用户得到授权,但是访问是被禁止的。',
  157. 404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
  158. 405: '请求方法不被允许。',
  159. 406: '请求的格式不可得。',
  160. 410: '请求的资源被永久删除,且不会再得到的。',
  161. 422: '当创建一个对象时,发生一个验证错误。',
  162. 500: '服务器发生错误,请检查服务器。',
  163. 502: '网关错误。',
  164. 503: '服务不可用,服务器暂时过载或维护。',
  165. 504: '网关超时。',
  166. };
  167. /**
  168. * 异常处理程序
  169. */
  170. const errorHandler = (error: ResponseError) => {
  171. const { response } = error;
  172. if (response && response.status) {
  173. const errorText = codeMessage[response.status] || response.statusText;
  174. const { status, url } = response;
  175. notification.error({
  176. message: `请求错误 ${status}: ${url}`,
  177. description: errorText,
  178. });
  179. }
  180. if (!response) {
  181. notification.error({
  182. description: '您的网络发生异常,无法连接服务器',
  183. message: '网络异常',
  184. });
  185. }
  186. throw error;
  187. };
  188. //请求处理
  189. export const request: any = {
  190. errorHandler,
  191. timeout: 300000,
  192. headers: { ['Authorization']: 'Bearer ' + localStorage.getItem('Admin-Token') },
  193. errorConfig: {
  194. adaptor: (resData: any) => {
  195. if (resData.code === 500) {
  196. let msg = sessionStorage.getItem('msg')
  197. if (resData.msg === '令牌验证失败') {//
  198. if (history.location.pathname !== '/user/login') {
  199. if (!msg) {
  200. const key = `open${Date.now()}`;
  201. const btn = (
  202. <Button type="primary" onClick={() => {
  203. localStorage.removeItem('Admin-Token')
  204. history.push('/user/login')
  205. notification.close(key)
  206. sessionStorage.removeItem('msg')
  207. }}>重新登录</Button>
  208. );
  209. const description = (
  210. <Result
  211. status="500"
  212. title='令牌验证失败!'
  213. subTitle="长时间没有操作,令牌失效请重新登录!"
  214. extra={btn}
  215. />
  216. )
  217. sessionStorage.setItem('msg', 'true')
  218. notification.open({
  219. message: '',
  220. description,
  221. duration: null,
  222. getContainer: () => document.getElementById('notificationPop') || document.getElementById('root') as HTMLElement,
  223. key,
  224. style: { zIndex: 999999, right: '50%', top: '50%', transform: 'translate(50%, -50%)', position: 'fixed', transition: 'all 0s' },
  225. onClose: () => {
  226. localStorage.removeItem('Admin-Token')
  227. history.push('/user/login')
  228. sessionStorage.removeItem('msg')
  229. }
  230. });
  231. }
  232. return { ...resData }
  233. } else {
  234. localStorage.removeItem('Admin-Token')
  235. }
  236. }
  237. if (!msg) {
  238. sessionStorage.setItem('msg', 'true')
  239. notification.error({
  240. message: resData.msg,
  241. onClose: () => {
  242. sessionStorage.removeItem('msg')
  243. }
  244. });
  245. }
  246. }
  247. if (resData.code === 310) {//权限错误
  248. let msg = sessionStorage.getItem('msg')
  249. localStorage.removeItem('Admin-Token')
  250. history.push('/user/login')
  251. if (!msg) {
  252. sessionStorage.setItem('msg', 'true')
  253. notification.error({
  254. message: resData.msg,
  255. onClose: () => {
  256. sessionStorage.removeItem('msg')
  257. }
  258. });
  259. }
  260. }
  261. return {
  262. ...resData,
  263. }
  264. },
  265. },
  266. };