123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285 |
- import React from 'react';
- import { BasicLayoutProps, Settings as LayoutSettings, MenuDataItem } from '@ant-design/pro-layout';
- import { Button, notification, Result } from 'antd';
- import { history, RequestConfig } from 'umi';
- import RightContent from '@/components/RightContent';
- import { ResponseError } from 'umi-request';
- import { queryCurrent, getMenu } from './services/user';
- import defaultSettings from '../config/defaultSettings';
- import { DesktopOutlined, MessageOutlined, SendOutlined, TeamOutlined, QrcodeOutlined, DatabaseOutlined, ReadOutlined, MobileOutlined, FundViewOutlined, RadarChartOutlined, BarChartOutlined, WechatOutlined, BookOutlined, FileImageOutlined, EyeOutlined, UserOutlined } from '@ant-design/icons';
- import { getMyMenu, headrRouter } from '../config/routerConfig';
- import { ReactComponent as LaunchSvg } from '@/assets/launch.svg'
- import { ReactComponent as AdLaunchSvg } from '@/assets/adLaunch.svg'
- import { ReactComponent as MaterialSvg } from '@/assets/material.svg'
- import versions from './utils/versions';
- interface CurrentUser {
- avatar?: string;
- name?: string;
- title?: string;
- group?: string;
- signature?: string;
- tags?: {
- key: string;
- label: string;
- }[];
- userId?: string;
- powerLevel?: number;
- access?: 'user' | 'guest' | 'admin' | any;
- unreadCount?: number;
- companyList?: any[],
- onlineCompanyId?: number
- }
- export async function getInitialState(): Promise<{
- currentUser?: CurrentUser;
- settings?: LayoutSettings;
- menu?: any,
- loading?: boolean,
- collapsed?: string,
- onCollapse?: (onCollapse: boolean) => void
- }> {
- // 如果是登录页面,不执行
- if (sessionStorage.getItem('Admin-Token')) {
- //开始版本号对比
- versions()
- try {
- sessionStorage.removeItem('msg')
- let currentUser = {}
- let userInfo: any = await queryCurrent();//用户信息
- let companyInfo = userInfo?.data?.companyRelationInfo?.filter((item: { companyId: number }) => item.companyId !== 4 && item.companyId !== 3)
- 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 }//处理个人信息
- let menu: any = await getMenu().then(async (res: any) => {//获取菜单并处理
- let { code, data } = res
- let path = getMyMenu(code, data)
- if (userInfo?.data?.userInfo?.account === 'admin' && path.length > 0) {//假如是ADMIN加入api测试
- path[0].routes.push({ key: 0, path: '/operatePage/apitest', name: 'api测试', icon: '', component: './operatePage/apitest', roles: 'admin' })
- }
- return { data: path }
- });
- localStorage.setItem('sex', userInfo?.data?.userInfo?.sex)
- localStorage.setItem('userId', userInfo?.data?.userInfo?.userId)
- localStorage.setItem('name', userInfo?.data?.userInfo?.nickname)
- return {
- currentUser,
- settings: { ...defaultSettings },
- loading: false,
- menu,
- collapsed: '0',
- onCollapse: (collapsed: boolean) => {
- let v = collapsed ? '1' : '0'
- localStorage.setItem('collapsed', v)
- }
- };
- } catch (error) {
- console.log(111111, error)
- history.push('/user/login');
- }
- }
- return {
- settings: defaultSettings,
- };
- }
- // 枚举转译服务端菜单icon
- const IconMap = {
- desktop: <DesktopOutlined />,
- message: <MessageOutlined />,
- send: <SendOutlined />,
- team: <TeamOutlined />,
- database: <DatabaseOutlined />,
- qrcode: <QrcodeOutlined />,
- read: <ReadOutlined />,
- mobile: <MobileOutlined />,
- fundView: <FundViewOutlined />,
- radarChart: <RadarChartOutlined />,
- barChart: <BarChartOutlined />,
- wechat: <WechatOutlined />,
- book: <BookOutlined />,
- peoples: <UserOutlined />,
- 'file-image': <FileImageOutlined />,
- launch: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><LaunchSvg /></span>,
- adLaunch: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><AdLaunchSvg /></span>,
- material: <span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><MaterialSvg /></span>,
- eye: <EyeOutlined />
- };
- //处理菜单
- const loopMenuItem = (menus: MenuDataItem[],): MenuDataItem[] => {
- let menu = menus?.map(({ icon, routes, roles, ...item }) => {
- let newItem = JSON.parse(JSON.stringify(item))
- newItem.key = item?.path || item?.key
- return {
- ...newItem,
- hideInMenu: false,//校验隐藏菜单
- icon: icon && IconMap[icon as string],
- children: routes && loopMenuItem(routes),
- }
- })
- return menu
- }
- export const layout = ({
- initialState
- }: {
- initialState: { settings?: LayoutSettings; currentUser?: CurrentUser; menu?: any; loading: boolean, collapsed: string, onCollapse: any };
- }): BasicLayoutProps => {
- return {
- menuDataRender: () => {
- return loopMenuItem(initialState?.menu?.data || [])
- },//解析服务端菜单
- rightContentRender: () => <RightContent />,
- disableContentMargin: false,
- collapsed: localStorage.collapsed === '1',
- onCollapse: initialState.onCollapse,
- breakpoint: false,
- // footerRender: () => <Footer />,
- onPageChange: () => {
- headrRouter(initialState, history)
- let { pathname, query } = history.location
- if (query?.t) {//带token直接进入对应页面
- sessionStorage.setItem('Admin-Token', decodeURIComponent(query.t as any))
- location.href = window.location.origin + '/#' + pathname
- location.reload()
- } else if (!initialState?.currentUser?.name && history.location.pathname !== '/user/login') {
- history.push('/user/login');
- }
- },
- splitMenus: true,//配合mix分割菜单
- menuHeaderRender: undefined,
- ...initialState?.settings,
- };
- };
- const codeMessage = {
- 200: '服务器成功返回请求的数据。',
- 201: '新建或修改数据成功。',
- 202: '一个请求已经进入后台排队(异步任务)。',
- 204: '删除数据成功。',
- 400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
- 401: '用户没有权限(令牌、用户名、密码错误)。',
- 403: '用户得到授权,但是访问是被禁止的。',
- 404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
- 405: '请求方法不被允许。',
- 406: '请求的格式不可得。',
- 410: '请求的资源被永久删除,且不会再得到的。',
- 422: '当创建一个对象时,发生一个验证错误。',
- 500: '服务器发生错误,请检查服务器。',
- 502: '网关错误。',
- 503: '服务不可用,服务器暂时过载或维护。',
- 504: '网关超时。',
- };
- /**
- * 异常处理程序
- */
- const errorHandler = (error: ResponseError) => {
- const { response } = error;
- if (response && response.status) {
- const errorText = codeMessage[response.status] || response.statusText;
- const { status, url } = response;
- notification.error({
- message: `请求错误 ${status}: ${url}`,
- description: errorText,
- });
- }
- if (!response) {
- notification.error({
- description: '您的网络发生异常,无法连接服务器',
- message: '网络异常',
- });
- }
- throw error;
- };
- //请求处理
- export const request: RequestConfig = {
- errorHandler,
- timeout: 300000,
- headers: { ['Authorization']: 'Bearer ' + sessionStorage.getItem('Admin-Token') },
- errorConfig: {
- adaptor: (resData: any) => {
- let div: any
- // if (!document.getElementById('notificationPop')) {
- // div = document.createElement('div')
- // div.id = 'notificationPop'
- // }
- if (resData.code === 500) {
- let msg = sessionStorage.getItem('msg')
- if (resData.msg === '令牌验证失败') {//
- if (history.location.pathname !== '/user/login') {
- if (!msg) {
- // document.body.appendChild(div)
- const key = `open${Date.now()}`;
- const btn = (
- <Button type="primary" onClick={() => {
- // setCookie('Admin-Token', '1', -300)
- sessionStorage.removeItem('Admin-Token')
- history.push('/user/login')
- notification.close(key)
- sessionStorage.removeItem('msg')
- // document.body.removeChild(div)
- }}>
- 重新登录
- </Button>
- );
- const description = (
- <Result
- status="500"
- title='令牌验证失败!'
- subTitle="长时间没有操作,令牌失效请重新登录!"
- extra={btn}
- />
- )
- sessionStorage.setItem('msg', 'true')
- notification.open({
- message: '',
- description,
- duration: null,
- getContainer: () => document.getElementById('notificationPop') || document.getElementById('root') as HTMLElement,
- key,
- style: { zIndex: 999999, right: '50%', top: '50%', transform: 'translate(50%, -50%)', position: 'fixed', transition: 'all 0s' },
- onClose: () => {
- // setCookie('Admin-Token', '1', -300)
- sessionStorage.removeItem('Admin-Token')
- history.push('/user/login')
- sessionStorage.removeItem('msg')
- // document.body.removeChild(div)
- }
- });
- }
- return { ...resData }
- } else {
- sessionStorage.removeItem('Admin-Token')
- }
- }
- if (!msg) {
- sessionStorage.setItem('msg', 'true')
- notification.error({
- message: resData.msg,
- onClose: () => {
- sessionStorage.removeItem('msg')
- }
- });
- }
- }
- if (resData.code === 310) {//权限错误
- let msg = sessionStorage.getItem('msg')
- sessionStorage.removeItem('Admin-Token')
- history.push('/user/login')
- if (!msg) {
- sessionStorage.setItem('msg', 'true')
- notification.error({
- message: resData.msg,
- onClose: () => {
- sessionStorage.removeItem('msg')
- }
- });
- }
- }
- return {
- ...resData,
- }
- },
- },
- };
|