import axios from "axios";

import { Loading } from "@/components/UI";

var isProduction = process.env.NODE_ENV === "production";

const serverName = isProduction ? "/api/" : "http://192.168.20.55:8035/api/";

const serverLocation = window.location.hostname;

axios.defaults.baseURL = serverName;
axios.defaults.headers["X-Requested-with"] = "XMLHttpRequest";

axios.interceptors.request.use(
  function (config) {
    Loading.show();

    if (config.headers["Content-Type"] == 'multipart/form-data') {
      return config;
    }

    if (config.method === "post") {
      config.data = {
        ...config.data,
        rnd: Math.random(),
      };
      // config.data = qs.stringify(config.data)
    } else if (config.method === "get") {
      config.params = {
        rnd: Math.random(),
        ...config.params,
      }
      // config.params = qs.stringify(config.params)
    }


    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 配置response拦截器
axios.interceptors.response.use(
  (response) => {
    let data = response.data;
    let code = Number(response.data.code);

    Loading.hide();
    switch (code) {
      case -1:
        break;
      case 5001:

        return
      case 5002:

        return
      case 500:
        return
    }

    if (code !== 0) {
      return
    }
    return data;
  },
  (error) => {
    Loading.hide();
    if (error.response) {

    }
    return Promise.reject(error);
  }
);
export { serverName, axios, serverLocation };
