import axios from "axios";
import { userinfo } from "@/store/store.ts";
import { getCookie } from "@/utils/cookie.ts";

// 自定义请求方法
export const myRequest = async (
  api: string,
  token: string = "",
  data: object = {},
  method: "get" | "post" | "put" | "delete" = "get",
) => {
  // 未获取到token，返回登录
  if (!getCookie("token")) {
    userinfo.login = false;
    userinfo.token = "";
  }
  // 调用请求
  if (method === "post") {
    const res = await axios.post(api, data, {
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
    });
    return res.data;
  } else if (method === "get") {
    const res = await axios.get(api, {
      params: data,
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
    });
    return res.data;
  } else if (method === "put") {
    const res = await axios.put(api, data, {
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
    });
    return res.data;
  } else if (method === "delete") {
    const res = await axios.delete(api, {
      data: data,
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
    });
    return res.data;
  } else return Promise.reject("暂不支持的请求");
};
