import { useStudentStore } from "@/stores/modules/studentStore";
import { useTeachStore } from "@/stores/modules/teachStore";
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 studentStore = useStudentStore();
const teachStore = useTeachStore();

// 封装公共申请办法
function request(
  url: string,
  method: "GET" | "POST" | "PUT" | "DELETE",
  data?: object | any,
  responseType?: string,
  returnError?: boolean
) {
  // 判断是否在微信浏览器
  let en: any = window.navigator.userAgent.toLowerCase();
  // 匹配en中是否含有MicroMessenger字符串
  if (en.match(/MicroMessenger/i) != "micromessenger") {
    studentStore.$reset();
    teachStore.$reset();
    // return "普通浏览器";
    return uni.reLaunch({ url: "/pages/prompt/index" });
  }

  const header = { "Content-Type": "application/json" };
  const pages = getCurrentPages();
  const page = pages[pages.length - 1]; // 当前页面

  if (
    (page.route?.split("/")[0] === "pages" &&
      page.route !== "pages/login/index" &&
      page.route !== "pages/login/register" &&
      page.route !== "pages/home/index" &&
      JSON.stringify(studentStore.infoData) === "{}") ||
    (page.route?.split("/")[0] !== "pages" &&
      page.route !== "pagesTeach/login/index" &&
      page.route !== "pagesTeach/home/index" &&
      JSON.stringify(teachStore.infoData) === "{}")
  ) {
    uni.reLaunch({
      url:
        page.route?.split("/")[0] === "pages"
          ? "/pages/login/index"
          : "/pagesTeach/login/index",
    });
    return Promise.reject(new Error("Redirecting to login"));
  }

  const requestOptions = {
    url: baseUrl + url,
    method,
    data,
    header,
    responseType,
  };

  sLoading();

  return new Promise((resolve, reject) => {
    uni.request({
      ...requestOptions,
      success(res: any) {
        hLoading();
        if (res.data.code == 200 || res.data.code == 501 || returnError) {
          if (returnError) {
            resolve(res);
            toast(res.data.msg);
          } else 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;
