zhongshujie
2025-08-01 07d1135a1913a919679dc23f0a38b9b61987171f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import { AvatarDropdown, AvatarName, Footer, Question } from '@/components';
import { currentUser as queryCurrentUser } from '@/services/ant-design-pro/api';
import { LinkOutlined } from '@ant-design/icons';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { SettingDrawer } from '@ant-design/pro-components';
import '@ant-design/v5-patch-for-react-19';
import type { RequestConfig, RunTimeLayoutConfig } from '@umijs/max';
import { history, Link } from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import { errorConfig } from './requestErrorConfig';
import { postOaAppGetApp } from './services/WebApi/oaApp';
import { postOaRoleGetRoleList } from './services/WebApi/oaRole';
import { postIdentityUserGetCurrentUser } from './services/WebApi/user';
const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';
import { requestCtx } from './assets/js/config';
/**
 * @see https://umijs.org/docs/api/runtime-config#getinitialstate
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: any;
  appInfo?: any;
  roleList?: any;
  selectRole?: any;
  loading?: boolean;
  fetchUserInfo?: () => Promise<any>;
  fetchAppInfo?: () => Promise<any>;
  fetchRoleList?: () => Promise<any>;
}> {
  const fetchAppInfo = async () => {
    try {
      const res = await postOaAppGetApp();
      return res;
    } catch (error) {
      history.push(loginPath);
    }
  };
  const fetchRoleList = async () => {
    try {
      const msg = await postOaRoleGetRoleList({ start: 0, size: 100, orgId: 4 });
      return msg;
    } catch (error) {
      history.push(loginPath);
    }
  };
  const fetchUserInfo = async () => {
    try {
      const msg = await postIdentityUserGetCurrentUser();
      return msg;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
 
 
  // 如果不是登录页面,执行
  const { location } = history;
  const currentUser = await fetchUserInfo();
  const appInfo = await fetchAppInfo();
  const roleList = await fetchRoleList();
  return {
    currentUser,
    appInfo,
    roleList,
    selectRole: {},
    fetchUserInfo,
    settings: defaultSettings as Partial<LayoutSettings>,
  };
  // return {
  //   fetchUserInfo,
  //   settings: defaultSettings as Partial<LayoutSettings>,
  // };
}
 
 
 
const demo1Middleware = async (config: any) => {
  // 声明一个变量,用于存储token
  let token = '';
  // 判断请求的url是否包含'LoginByPassword'
  if (config.url.indexOf('LoginByPassword') === -1) {
    // 如果不包含,则从localStorage中获取token
    token = localStorage.getItem('web-token');
    // 如果token存在,则将token添加到请求头中
    if (token) {
      config.headers.Authorization = 'bearer ' + token;
    }
  }
  // 将请求的url添加到requestCtx中
  config.url = `${requestCtx}${config.url}`;
  // 返回处理后的请求配置
  return config;
};
 
const handleResponse = async (response: any) => {
  if (response.status == 200) {
    return response.data;
  } else {
    const codeMaps = {
      400: '请求错误',
      401: '认证超时',
      403: '账号已禁用',
      500: '系统错误',
      504: '网关超时',
    };
    let msg = '请求发生错误';
    let data = null;
    try {
      data = await response.clone().json();
    } catch (error) {
      data = null;
    }
    if (codeMaps[response.status]) {
      msg = codeMaps[response.status];
    }
    if (data && data.msg) {
      msg = data.msg;
    }
    if (response.status == 401) {
      localStorage.removeItem('bits-token');
      if (history.location.pathname.indexOf('login') == -1) {
        history.replace('/user/login');
      }
    }
  }
};
 
 
export const request = {
  responseInterceptors: [handleResponse],
  requestInterceptors: [demo1Middleware],
};
 
 
// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    actionsRender: () => [<Question key="doc" />],
    avatarProps: {
      src: initialState?.currentUser?.avatar,
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
      },
    },
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录,重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    bgLayoutImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    links: isDev
      ? [
        <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
          <LinkOutlined />
          <span>OpenAPI 文档</span>
        </Link>,
      ]
      : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
          {isDev && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};
 
/**
 * @name request 配置,可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */