app.tsx 12 KB

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