import { message } from "antd";
import axios, { AxiosProgressEvent, GenericAbortSignal } from "axios";
import { getLocalStorage, removeLocalStorage } from "../utils/local";
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;
const codeMessage: { [key: number]: string } = {
  200: "服务器成功返回请求的数据。",
  201: "新建或修改数据成功。",
  202: "一个请求已经进入后台排队（异步任务）。",
  204: "删除数据成功。",
  // 400: "发出的请求有错误，服务器没有进行新建或修改数据的操作。",
  401: "用户没有权限（令牌、用户名、密码错误）。",
  403: "用户得到授权，但是访问是被禁止的。",
  404: "发出的请求针对的是不存在的记录，服务器没有进行操作。",
  406: "请求的格式不可得。",
  410: "请求的资源被永久删除，且不会再得到的。",
  422: "当创建一个对象时，发生一个验证错误。",
  500: "服务器发生错误，请检查服务器日志。",
  502: "网关错误。",
  503: "服务不可用，服务器暂时过载或维护。",
  504: "网关超时。",
  511: "没有权限 , 非法操作",
};

// 忽略错误处理的url
const neglectUrl = ["/configs/info/web", "/stats", "/online/log"];

const headers = {
  "Content-Type": "application/json",
};

const baseURL = `${window.location.origin}${apiBaseUrl}`;

export const service = axios.create({
  baseURL,
  timeout: 120000,
  headers: headers,
  responseType: "json",
});

service.interceptors.request.use((config) => {
  const token = getLocalStorage<string>("token");
  if (!token) return config;
  config.headers["authorization"] = `Bearer ${token}`;
  return config;
});

service.interceptors.response.use(
  (resp) => resp,
  (error) => {
    if (!error) {
      message.error("Network Error");
      return Promise.reject(error);
    }

    const resp = error.response;
    const errTips = resp?.data["msg"];

    let errorText = "";
    if (resp?.status) {
      errorText = codeMessage[resp?.status] || resp.statusText;
    }

    if (neglectUrl.includes(error.config.url)) {
      return Promise.reject(error);
    }
    switch (resp?.status) {
      case 401:
        removeLocalStorage("token");
        window.location.href = "/extensions/easyvqd/web/login";
        break;
      case 500:
        message.error(errorText ?? "Server Error");
        break;
      case 504:
        message.error(errorText ?? errTips ?? "Network Error");
        break;
      default:
        console.log(
          "🚀 ~ file: http.ts ~ line 50 ~ service.interceptors.response.use",
          errorText
        );
        break;
    }

    return Promise.reject(error);
  }
);

service.interceptors.request.use((config) => {
  return config;
});

async function request<T>(
  url: string,
  method: string,
  data?: object,
  signal?: GenericAbortSignal,
  timeOut?: number,
  responseType?: "json" | "blob" | "arraybuffer",
  headers?: { [key: string]: string },
  onUploadProgress?: (progressEvent: AxiosProgressEvent) => void
) {
  return await service.request<T>({
    url,
    method,
    data: method == "GET" ? {} : data,
    params: method == "GET" ? data : {},
    signal: signal,
    timeout: timeOut,
    responseType: responseType || "json",
    headers: headers,
    onUploadProgress: (progressEvent) => {
      if (onUploadProgress) {
        onUploadProgress(progressEvent);
      }
    },
  });
}
// 查询
export async function GET<T>(
  url: string,
  params?: any,
  signal?: GenericAbortSignal,
  timeOut?: number,
  responseType?: "json" | "blob" | "arraybuffer",
  headers?: { [key: string]: string }
) {
  return request<T>(url, "GET", params, signal, timeOut, responseType, headers);
}

// 添加
export async function POST<T>(
  url: string,
  params?: any,
  signal?: GenericAbortSignal,
  timeOut?: number,
  responseType?: "json" | "blob" | "arraybuffer",
  headers?: { [key: string]: string },
  onUploadProgress?: (progressEvent: AxiosProgressEvent) => void
) {
  return request<T>(
    url,
    "POST",
    params,
    signal,
    timeOut,
    responseType,
    headers,
    onUploadProgress
  );
}

// 更新
export async function PUT<T>(url: string, params?: any) {
  return request<T>(url, "PUT", params);
}

// 删除
export async function DELETE<T>(url: string, params?: any) {
  return request<T>(url, "DELETE", params);
}
