import axios from "axios";
import { ElLoading, ElMessage } from "element-plus";
import router from "../router";
import QS from "qs";

let loading = null;

function startLoading() {
  loading = ElLoading.service({
    lock: true,
    text: "加载中...",
    background: "rgba(0, 0, 0, 0.5)",
  });
}

function endLoading() {
  loading && loading.close();
}

axios.defaults.baseURL = import.meta.env[
  import.meta.env.DEV ? "VITE_PROXY" : "VITE_BASE_URL"
];
axios.defaults.timeout = 1000 * 60 * 10;
// axios.defaults.withCredentials = true;
axios.interceptors.request.use(
  (config) => {
    if (config.method === "get" || config.method === "GET") {
      if (QS.parse(config.params)?.loading !== "false") startLoading();
    }
    if (config.method === "post" || config.method === "POST") {
      if (QS.parse(config.data)?.loading !== "false") startLoading();
    }
    return config;
  },
  (error) => Promise.reject(error)
);

axios.interceptors.response.use(
  (config) => {
    if (config.config.method === "get" || config.config.method === "GET") {
      if (QS.parse(config.config.params)?.loading !== "false") endLoading();
    }
    if (config.config.method === "post" || config.config.method === "POST") {
      if (QS.parse(config.config.data)?.loading !== "false") endLoading();
    }
    return config;
  },
  (error) => {
    console.log(error);
    if (error && error.response) {
      switch (error.response.status) {
        case 0:
        case 302:
          endLoading();
          ElMessage.error("登录失效，请重新登陆");
          router.push("/login").then();
          break;
        default:
          error.message = `连接错误${error.response.status}`;
          import.meta.env.DEV &&
            ElMessage.error(`连接错误${error.response.status}`);
      }
    } else {
      error.message = "连接到服务器失败";
      endLoading();
      ElMessage.error("登录失效，请重新登陆");
      router.push("/login").then();
    }
    return Promise.reject(error.message);
  }
);

export function post(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, QS.stringify(params), {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      })
      .then((res) => {
        if (res.data.result === "success") {
          resolve(res.data);
        } else {
          ElMessage.error(
            res.data.msg ||
              res.data.resMsg ||
              res.data.resultStr ||
              "系统开小差了"
          );
          reject(res.data);
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
}

export function get(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        params: QS.stringify(params),
      })
      .then((res) => {
        if (res.data.result === "success") {
          resolve(res.data);
        } else {
          ElMessage.error(
            res.data.msg ||
              res.data.resMsg ||
              res.data.resultStr ||
              "系统开小差了"
          );
          reject(res.data);
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
}

export function upload(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, params, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      })
      .then((res) => {
        if (res.data.result === "success") {
          resolve(res.data);
        } else {
          ElMessage.error(
            res.data.msg ||
              res.data.resMsg ||
              res.data.resultStr ||
              "系统开小差了"
          );
          reject(res.data);
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
}
