import axios, {
  AxiosError,
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from "axios";
import { message } from "ant-design-vue";
import { useUserStore } from "@/stores/modules/userStore";
import { CLIENT_TYPE } from "@/config/constant";
export interface JsonResult<T> {
  code: number;
  message: string;
  data?: T;
}

const axiosConfig: AxiosRequestConfig = {
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: import.meta.env.VITE_APP_ENV === "production" ? 10000 : 60000,
  timeoutErrorMessage: "请求超时......",
};

class RequestHttp {
  service: AxiosInstance;

  public constructor(config: AxiosRequestConfig) {
    this.service = axios.create(config);
    //1.添加请求拦截
    this.service.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        //默认带上用户token
        config.headers.set("token", useUserStore().userInfo?.tokenValue);
        config.headers.set("Client-Type", CLIENT_TYPE);
        return config;
      },
      (error: AxiosError): Promise<string> => {
        message.error(error.message).then((r) => {});
        return Promise.reject(error);
      }
    );
    //2.添加响应拦截
    this.service.interceptors.response.use(
      (response: AxiosResponse): Promise<any> => {
        const jsonResult: JsonResult<unknown> = response.data;
        if (jsonResult.code !== 200) {
          //todo 一些特定的错误需要重新登录 这里暂时没处理
          message.error(jsonResult.message).then((r) => {});
          return Promise.reject(jsonResult);
        }
        return Promise.resolve(jsonResult);
      },
      (error: AxiosError): Promise<string> => {
        message.error(error.message).then((r) => {});
        return Promise.reject(error);
      }
    );
  }

  /**
   *  常用请求方法封装
   */
  get<T>(
    url: string,
    params?: object,
    _object: AxiosRequestConfig = {}
  ): Promise<JsonResult<T>> {
    return this.service.get(url, { params, ..._object });
  }

  post<T>(
    url: string,
    params?: object | object[],
    _object: AxiosRequestConfig = {}
  ): Promise<JsonResult<T>> {
    return this.service.post(url, params, _object);
  }

  put<T>(
    url: string,
    params?: object | object[],
    _object: AxiosRequestConfig = {}
  ): Promise<JsonResult<T>> {
    return this.service.put(url, params, _object);
  }

  delete<T>(
    url: string,
    params?: object,
    _object: AxiosRequestConfig = {}
  ): Promise<JsonResult<T>> {
    return this.service.delete(url, { params, ..._object });
  }

  download(
    url: string,
    params?: object,
    _object: AxiosRequestConfig = {}
  ): Promise<BlobPart> {
    return this.service.post(url, params, { ..._object, responseType: "blob" });
  }
}

const api = new RequestHttp(axiosConfig);
export default api;
