import axios from "axios";
import { loadProgressBar } from "axios-progress-bar";
import axiosRetry from "axios-retry";
import { message } from "ant-design-vue";

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

const _axiosNoAuth = axios.create(config);
axiosRetry(_axiosNoAuth);

/**
 * 本应用的无auth api，或者第三方的api
 * 1. 统一使用的http api，方便使用，无需fetch
 * 2. 无默认headers
 */

_axiosNoAuth.interceptors.request.use(
  function (config) {
    return config;
  },
  function (error) {
    void message.error({ content: error, duration: 10 });
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axiosNoAuth.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (!error.response) {
      // "Network Error" 网络不通，直接返回
      void message.error({
        content: "网络连接异常，请检查网络设置。",
        duration: 10,
      });
      return Promise.reject(error);
    }

    const data = error.response.data;
    if (data && data.desc) {
      void message.error({ content: data.desc, duration: 10 });
    } else {
      void message.error({
        content: `异常(${error.response.status}): ${error.config.url}`,
        duration: 10,
      });
    }
    return Promise.reject(error);
  }
);

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

export const httpNoAuth = _axiosNoAuth;
