import { useGlobalStore } from "@/store/useStore";
import { hLoading, sLoading, toast } from "./util";

export const baseUrl = "/k3cloud";
// 部署到iis上用的
// export const baseUrl = "https://weixin.lingqingkeji.com:86/k3cloud"
// export const baseUrl = "/XiBU"

const globalStore = useGlobalStore();
// 封装公共申请办法
function request(
  url: string,
  method: "GET" | "POST" | "PUT" | "DELETE",
  data?: object | any,
  responseType?: string
) {
  return new Promise<any>(function (resolve, reject) {
    let header: any;
    sLoading();
    let pages = getCurrentPages();
    let page = pages[pages.length - 1]; // 当前页面
    if (
      page.route !== "pages/login/index" &&
      page.route !== "pages/login/register" &&
      page.route !== "pages/home/index" &&
      JSON.stringify(globalStore.infoData) === "{}"
    ) {
      uni.reLaunch({ url: "/pages/login/index" });
    }
    header = { "Content-Type": "application/json" };
    url = baseUrl + url;

    uni.request({
      url,
      method,
      data,
      header,
      responseType,
      success(res: any) {
        hLoading();
        if (res.data.code == 200 || res.data.code == 501) {
          resolve(res);
        } else if (res.data.code == 500 || res.data.code === 401) {
          toast(res.data.msg);
          reject(res);
        } else {
          console.log(res, "非200错误");
          //其余异样
          reject(res);
        }
      },
      fail(err: any) {
        hLoading();
        //申请失败
        uni.showToast({
          title: "连接服务器失败",
          icon: "none",
        });
        reject(err);
      },
    });
  });
}

export default request;
