| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388 |
- import { PageLoading } from '@ant-design/pro-layout';
- import { notification, Modal, message } from 'antd';
- import { history, Link, useModel } from 'umi';
- import RightContent from '@/components/RightContent';
- import Footer from '@/components/Footer';
- import { BookOutlined, LinkOutlined } from '@ant-design/icons';
- import { getQueryString } from './utils';
- import { stringify } from 'querystring';
- import { getSubHosp, getMenus } from './services/user';
- import iconEnum from './menuIcons';
- import { createRef } from 'react';
- import { reject } from 'lodash';
- const layoutActionRef = createRef();
- const { query = {}, pathname } = history.location;
- const { redirect, hospSign = 'dOBHdoPmJgPGnMSH' } = query;
- const isDev = process.env.NODE_ENV === 'development';
- const loginParams = localStorage.getItem('loginParams');
- //医院标识
- let sign = '', isExpired = false;
- if (hospSign) {
- sign = hospSign;
- } else {
- //query里没有就从localstorage里找
- const { hospSign } = JSON.parse(loginParams);
- sign = hospSign;
- }
- const loginPath = `/user/login?hospSign=${sign}`;
- let requestMethod = 'get';
- /** 获取用户信息比较慢的时候会展示一个 loading */
- console.log({ location });
- const { search } = location;
- let urlStr = search.split('?')[1]
- const urlSearchParams = new URLSearchParams(urlStr)
- const urlParamsResult = Object.fromEntries(urlSearchParams.entries());
- const {token:urlToken} = urlParamsResult
- if(urlToken){
- //嵌入中台暂时模拟
- const userData = {
- avatar: "https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png",
- name: "中台管理员",
- token:urlToken,
- userid: 103
- }
- localStorage.setItem('userData', JSON.stringify(userData))
- }
- export const initialStateConfig = {
- loading: <PageLoading />,
- };
- /**
- * @see https://umijs.org/zh-CN/plugins/plugin-initial-state
- * */
- export async function getInitialState() {
- const fetchUserInfo = async () => {
- const userData = localStorage.getItem('userData');
- if (userData) {
- return userData;
- }
- return undefined;
- };
- const getMenuDataFromServer = async () => {
- if (window.location.pathname !== `/user/login`) {
- const resp = await getMenus();
- const { status, data } = resp;
- if (status == 200) {
- return data;
- } else {
- return [{
- component: './404',
- },];
- }
- }
- };
- const fetchSubHosp = async () => {
- return null
- }
- if (history.location.pathname !== loginPath) {
- const currentUser = await fetchUserInfo();
- const menu = await getMenuDataFromServer();
- return {
- fetchUserInfo,
- currentUser,
- settings: {},
- isExpired: false,
- fetchSubHosp,
- sign,
- isDev: process.env.NODE_ENV == 'development',
- menu: menu
- };
- }
- return {
- fetchUserInfo,
- settings: {},
- fetchSubHosp,
- sign
- };
- }
- /**
- * 退出登录,并且将当前的 url 保存
- */
- const loginOut = async () => {
- // await outLogin();
- localStorage.removeItem('userData');
- localStorage.removeItem('menus');
- if (window.location.pathname !== `/user/login` && !redirect) {
- history.replace({
- pathname: `/user/login`,
- search: stringify({
- redirect: pathname,
- hospSign: sign
- }),
- });
- }
- };
- //请求拦截器
- const authHeaderInterceptor = (url, options) => {
- const { method } = options;
- if (method == 'post') {
- requestMethod = 'post'
- } else {
- requestMethod = 'get'
- }
- let authHeader = {};
- const userData = localStorage.getItem('userData');
- if (userData) {
- const { token } = JSON.parse(userData);
- authHeader.token = token;
- }
- return {
- url: `${url}`,
- options: { ...options, interceptors: true, headers: authHeader },
- };
- };
- //响应拦截器
- const demoResponseInterceptors = async (response, options) => {
- try {
- const { status } = response;
- // console.log({response});
- if (status != 200) {
- const { errorCode, } = response;
- if (errorCode == 500) {
- notification.error({
- message: '抱歉,服务器出现错误!'
- });
- }
- if (errorCode == 404) {
- notification.error({
- message: '抱歉,服务器未找到请求!'
- });
- } else {
- notification.error({
- message: `错误 ${status}`
- });
- }
- }
- const _response = await response.clone().json();
- const { status: dataStatus, errorMessage, errorCode } = _response;
- const { url } = options;
- //success返回
- if (dataStatus == 200) {
- if (requestMethod == 'post' && url != '/api/costAccount/login') {
- message.success('操作成功!');
- }
- return response;
- } else {
- // console.log({ isExpired });
- if (errorCode == 499 && !isExpired) {
- isExpired = true;
- Modal.confirm({
- title: '抱歉,登录已过期请重新登录!',
- onOk: () => {
- loginOut();
- }
- });
- } else {
- if (errorMessage) {
- notification.error({
- message: errorMessage,
- duration: 5,
- });
- }
- return;
- }
- }
- return {
- success: true,
- errorMessage: {
- info: errorMessage
- }
- }
- } catch (err) {
- console.log('catch error:', err)
- }
- }
- const errorHandlerFunc = (error) => {
- console.log({ error });
- try {
- const { info } = error;
- const errortext = '';
- const { status, errorMessage } = info;
- notification.error({
- message: ` ${status ? status : ''}: ${errorMessage}`,
- description: errortext,
- });
- } catch (err) {
- console.log({ 'errorHandlerFunc': err });
- notification.error({
- message: '登录遇到未知错误,查看控制台!',
- });
- }
- };
- export const request = {
- errorHandler: errorHandlerFunc,
- // 新增自动添加AccessToken的请求前拦截器
- requestInterceptors: [authHeaderInterceptor],
- responseInterceptors: [demoResponseInterceptors],
- };
- //将服务端获取的菜单 icon 字符串映射为对应的 icon Dom
- const mappingIcon = menuData => {
- const mappingMenu = menuData.map(item => ({
- ...item,
- icon: item.icon && iconEnum[item.icon],
- children: item.children ? mappingIcon(item.children) : [],
- }));
- return mappingMenu;
- };
- export const layout = async ({ initialState }) => {
- return urlToken?{
- headerTitleRender:false,
- headerRender:false,
- rightContentRender: () => <RightContent />,
- disableContentMargin: false,
- waterMarkProps: {
- content: '',
- },
- actionRef: layoutActionRef,
- footerRender: () => <Footer />,
- onPageChange: () => {
- const { location } = history; // 如果没有登录,重定向到 login
- if (!initialState?.currentUser && location.pathname !== '/user/login') {
- history.push(loginPath);
- }
- },
- menu: {
- params: {
- userId: initialState,
- },
- request: async (params, defaultMenuData) => {
- // initialState.currentUser 中包含了所有用户信息
- const { currentUser, isDev } = initialState;
- if (isDev || currentUser.userid == 96) {
- //开发环境或超级账号
- return []
- }
- if (currentUser) {
- const resp = await getMenus();
- const { data: menu } = resp;
- return mappingIcon(menu);
- } else {
- return [
- {
- component: './404',
- }
- ]
- }
- },
- },
- menuHeaderRender: undefined,
- // 自定义 403 页面
- // unAccessible: <div>unAccessible</div>,
- ...initialState?.settings,
- }:{
- rightContentRender: () => <RightContent />,
- disableContentMargin: false,
- waterMarkProps: {
- content: '',
- },
- actionRef: layoutActionRef,
- footerRender: () => <Footer />,
- onPageChange: () => {
- const { location } = history; // 如果没有登录,重定向到 login
- if (!initialState?.currentUser && location.pathname !== '/user/login') {
- history.push(loginPath);
- }
- },
- menu: {
- params: {
- userId: initialState,
- },
- request: async (params, defaultMenuData) => {
- // initialState.currentUser 中包含了所有用户信息
- const { currentUser, isDev } = initialState;
- if (isDev || currentUser.userid == 96) {
- //开发环境或超级账号
- return []
- }
- if (currentUser) {
- const resp = await getMenus();
- const { data: menu } = resp;
- return mappingIcon(menu);
- } else {
- return [
- {
- component: './404',
- }
- ]
- }
- },
- },
- menuHeaderRender: undefined,
- // 自定义 403 页面
- // unAccessible: <div>unAccessible</div>,
- ...initialState?.settings,
- };
- };
|