﻿import type { RequestOptions } from '@@/plugin-request/request';
import type { RequestConfig } from '@umijs/max';
import { history } from '@umijs/max';
import { message } from 'antd';

// 错误处理方案： 错误类型
enum ErrorShowType {
  SILENT = 0,
  WARN_MESSAGE = 1,
  ERROR_MESSAGE = 2,
  NOTIFICATION = 3,
  REDIRECT = 9,
}
// 与后端约定的响应数据格式
interface ResponseStructure {
  success: boolean;
  data: any;
  errorCode?: number;
  errorMessage?: string;
  showType?: ErrorShowType;
}

/**
 * @name 错误处理
 * pro 自带的错误处理， 可以在这里做自己的改动
 * @doc https://umijs.org/docs/max/request#配置
 */
export const errorConfig: RequestConfig = {
  // baseURL: 'http://192.168.110.111:9000',
  baseURL: 'https://dollearn.com/api',
  // 请求拦截器
  requestInterceptors: [
    (config: RequestOptions) => {
      const o = config;
      const Authorization = localStorage.getItem('token') || '';
      o.headers = {
        ...config.headers,
        Authorization,
        'Content-Type': 'application/json',
      };
      // 拦截请求配置，进行个性化处理。
      const url = config?.url;

      return { ...config, url };
    },
  ],

  // 响应拦截器
  responseInterceptors: [
    (response: any) => {
      // 拦截响应数据，进行个性化处理
      const { data } = response as unknown as ResponseStructure;
      if (response.request.responseURL == 'https://dollearn.com/api/management/base/oss/upload') {
        return response;
      }
      if (data?.code === 103 || data?.code === 401) {
        history.replace('/login');
        return response;
      }
      if (data?.code != 200 && data?.code != 602) {
        message.error(data.msg);
      }
      return response;
    },
  ],
};
