import axios from "axios";
import { message } from "@/utils/resetMessage.js";

let errTimer = null;
let setErrorMsg = function (err) {
  let err_msg = "请求失败";
  if (err.message.includes("timeout")) {
    err_msg = "请求超时，请刷新后重试！";
  } else if (err.message.includes("Network Error")) {
    err_msg = "网络连接错误,请刷新后重试！";
  }
  if (errTimer) {
    clearTimeout(errTimer);
    errTimer = null;
  }
  errTimer = setTimeout(() => {
    message.error(err_msg);
  }, 1500);
  err.message = err_msg;
  return err;
};
const http = axios.create({
  retry: 2,
  retryDelay: 1000,
  timeout: 1000 * window._config.axiosApiTimeout,
  validateStatus: function (status) {
    return status >= 200 && status <= 500; // 默认的
  },
  headers: {
    "Content-Type": "application/json"
  }
});

/**
 * HTTP request拦截
 */
http.interceptors.request.use(
  (config) => {
    return config;
  },
  (err) => {
    err.message = "请求失败";
    return Promise.reject(err);
  }
);

/**
 * HTTP response拦截
 */
http.interceptors.response.use(
  (response) => {
    let resData = response.data;
    if (resData.code === 2) {
      window.vue.$router.push("/login");
    }
    return resData;
  },
  function axiosRetryInterceptor(err) {
    let config = (err && err.config) || {};
    if (!config.retry) {
      return Promise.reject(setErrorMsg(err));
    }
    config.__retryCount = config.__retryCount || 0;
    if (config.__retryCount >= config.retry) {
      return Promise.reject(setErrorMsg(err));
    }
    config.__retryCount += 1;
    let backoff = new Promise(function (resolve) {
      setTimeout(function () {
        resolve();
      }, config.retryDelay || 1);
    });
    return backoff.then(function () {
      return http(config);
    });
  }
);

export default http;
