import axios, { AxiosRequestConfig } from "axios";
import { loadProgressBar } from "axios-progress-bar";
import axiosRetry from "axios-retry";

const config = {
  timeout: 60 * 1000, // Timeout
};

const _axiosNoAuth = axios.create(config);
axiosRetry(_axiosNoAuth, {
  retries: 0,
  // eslint-disable-next-line @typescript-eslint/unbound-method
  retryDelay: axiosRetry.exponentialDelay,
});

/**
 * 本应用的无auth api，或者第三方的api
 * 1. 统一使用的http api，方便使用，无需fetch
 * 2. 无默认headers
 */
_axiosNoAuth.interceptors.request.use(
  function (config) {
    return config;
  },
  function (error) {
    $message.error(JSON.stringify(error));
    logger({
      key: "网络请求request error",
      cnl: ["console", "local", "server"],
      pgu: "AUTO",
      aul: error.config?.url,
    });
    return Promise.reject(error);
  }
);

// Add a response interceptor
// 这个用途是为了retry网络请求不要疯狂的报错，如果最后没成功，只报第一次的错误
let lastRequestTimeForRetry = 0;
_axiosNoAuth.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    const config: AxiosRequestConfig = error.config;
    logger({
      key: "网络请求response error",
      cnl: ["console", "local", "server"],
      pgu: "AUTO",
      aul: config?.url,
      emsg: error.response?.data?.desc,
    });
    logger({
      key: "网络请求response error",
      cnl: ["console", "local", "server"],
      pgu: "AUTO",
      lvl: "debug",
      aul: config?.url,
      emsg: error.response?.data?.desc,
      possibleError: error,
    });
    if (config?.["axios-retry"]) {
      // @ts-expect-error lastRequestTime 并没有声明在它公共的api上
      const thisTime = config["axios-retry"].lastRequestTime;
      if (lastRequestTimeForRetry === thisTime) {
        return Promise.reject(error);
      } else {
        lastRequestTimeForRetry = thisTime;
      }
    }
    const showErrorMessage = !config?.noErrorMessage;
    if (!error.response) {
      // "Network Error" 网络不通，直接返回
      showErrorMessage && $message.error("网络连接异常，请检查网络设置。");
      return Promise.reject(error);
    }

    const data = error.response.data;
    if (data && data.desc) {
      showErrorMessage && $message.error(data.desc + "");
    } else {
      showErrorMessage &&
        $message.error(`异常(${error.response.status}): ${error.config.url}`);
    }
    return Promise.reject(error);
  }
);

// eslint-disable-next-line
loadProgressBar(null, _axiosNoAuth);

export const httpNoAuth = _axiosNoAuth;
