import axios from "axios";
import history from "./history";
import { getTokenInfo, removeTokenInfo } from "./storage";
import { message } from "antd";
// 请求基地址
export const baseURL =
  // 线下的图片地址需要加上/api/
  process.env.NODE_ENV === "development"
    ? "http://192.168.20.55:8038/api/"
    : "";
// process.env.NODE_ENV === "development" ? "http://192.168.20.55:8038" : "";

// 创建 axios 实例
const http = axios.create({
  // 线下的地址不用加/api/
  baseURL: baseURL,
  // baseURL: baseURL + "/api/",
  timeout: 5000,
});

let axajInd = 0;
const lodingDom: any = document.querySelector("#AsyncSpinLoding");

// 请求拦截器
http.interceptors.request.use(
  function (config: any) {
    // 发请求前打开加载提示
    lodingDom.style.opacity = 1;
    lodingDom.style.pointerEvents = "auto";
    axajInd++;

    const { token } = getTokenInfo();
    if (token) config.headers.token = token;
    return config;
  },
  function (err) {
    return Promise.reject(err);
  }
);

// 响应拦截器
http.interceptors.response.use(
  function (response) {
    // 请求回来的关闭加载提示
    axajInd--;
    if (axajInd === 0) {
      setTimeout(() => {
        lodingDom.style.opacity = 0;
        lodingDom.style.pointerEvents = "none";
      }, 200);
    }

    if (response.data.code === 5001 || response.data.code === 5002) {
      removeTokenInfo();
      message.warning("登录失效!");
      history.push("/login");
    } else if (response.data.code === 0) {
      // message.success(response.data.msg);
    } else message.warning(response.data.msg);
    return response.data;
  },
  async function (err) {
    setTimeout(() => {
      lodingDom.style.opacity = 0;
      lodingDom.style.pointerEvents = "none";
    }, 100);
    // 如果因为网络原因，response没有，给提示消息
    if (!err.response) {
      message.warning("网络繁忙，请稍后重试!");
    } else {
      message.warning("错误!");
    }

    return Promise.reject(err);
  }
);

// 导出 axios 实例
export default http;
