import { extend } from "umi-request";
import cleanDeep from "clean-deep";

export interface SearchInitParams {
  rows?: string | number;
  page?: string | number;
}

const request = extend({
  // requestType: 'form',
  hideLoading: true, // 默认都不显示加载
  timeout: 20000,
  timeoutMessage: "请求超时",
});

request.interceptors.request.use(
  (url, options: any) => {
    const Authorization = sessionStorage.getItem("Authorization") || "";
    const authHeaders: any = {};
    if (Authorization) {
      authHeaders.Authorization = Authorization;
    }

    return {
      url,
      options: {
        ...options,
        params: cleanDeep(options.params),
        data: cleanDeep(options.data),
        headers: {
          ...options.headers,
          ...authHeaders,
        },
      },
    };
  },
  { global: false }
);

request.interceptors.response.use(
  async (res: any) => {
    if (res.status > 299 || res.status < 200) {
      const msg = "服务器错误，状态码" + res.status;
      throw new Error(msg);
    }
    const data = await res.clone().json();
    if (data.code === 401 || data.code === 4001 || data.code == 403 || data.code == 5000) {
      sessionStorage.removeItem("Authorization");
      return;
    }

    if (data.code !== 200 && data.errCode !== 0) {
      const msg = data.msg || data.message || "处理失败，请重试";
      if (!(data.code === 403 || data.code === 401)) {
      }
      throw new Error(msg);
    }
    return res;
  },
  { global: false }
);

export default request;
