import type { RequestConfig, RequestOptions } from 'umi';
import Global, { CODE_MESSAGE } from '@/appConfig';
import { message } from 'antd';
import { showNotification } from '@/utils';


export const http: RequestConfig = {
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json; charset=utf-8',
  },
  timeout: 20000,
  errorConfig: {
    //错误接收及处理
    errorHandler(error: any) {
      const { response, code } = error;
      if (code === 'ECONNABORTED') {
        return showNotification('error', '提示', '请求超时，请检查网络稍后再试！');
      }
      if (response) {
        const { status } = response;
        if (status === 401) {
          // 登录失效
          message.error(response.statusText || '登录失效');
          // login(); // 回到登录页
        };
        if (status === 0) {
          return showNotification('error', `当前无网络`);
        }
        if (status !== 200) {
          const errorText = CODE_MESSAGE[status] || response.statusText;
          showNotification('error', `请求错误 ${status}`, errorText);
        }
      }
    },
  },
  // 请求拦截器
  requestInterceptors: [
    (config: RequestOptions) => {
      const { headers, url } = config;
      config.headers = {
        ...headers,
        token: sessionStorage.getItem('accessToken') as string,
      };
      config.url = `${Global.apiBasePath}${url}`;
      return { ...config };
    },
  ],
  // 响应拦截器
  responseInterceptors: [
    (response) => {
      const data: API.HttpResult = response.data as unknown as API.HttpResult;
      if (data && !data.success && data.msg) {
        showNotification('error', '提示', data.msg);
      }
      return response;
    },
  ],
};