import {
  HTTP_REQUEST_URL,
  HEADER,
  TOKENNAME,
  HEADERPARAMS,
  WHITELIST,
} from "@/config/app";
import { toLogin, checkLogin } from "@/libs/login";
import { useAppStore } from "@/stores/app";
import { useToast } from "@/hooks/useToast";
/**
 * 发送请求
 */
function baseRequest(
  url,
  method,
  data,
  { noAuth = false, noVerify = false },
  params
) {
  const appStore = useAppStore();
  const { Toast } = useToast();

  let Url = HTTP_REQUEST_URL,
    header = HEADER;
  const TOKEN = appStore.tokenComputed;
  if (params != undefined) {
    header = HEADERPARAMS;
  }
  if (!noAuth) {
    //登录过期自动登录
    const currentPath = getCurrentPagePath();
    if (!TOKEN && !checkLogin() && !WHITELIST.includes(currentPath)) {
      // 未登录时，先判断当前页面是否在白名单
      Toast({ title: "未登录，请前往登录" });
      toLogin();
      return Promise.reject({
        code: 401,
        message: "未登录",
      });
    }
  }
  if (TOKEN) header[TOKENNAME] = TOKEN;
  return new Promise((reslove, reject) => {
    Url = HTTP_REQUEST_URL || "http://api.front.hdq.xbdzz.cn";
    uni.request({
      url: Url + "/api/front/" + url,
      method: method || "GET",
      header: header,
      timeout: 30000,
      data: data || {},
      success: (res) => {
        if (noVerify) reslove(res.data, res);
        else if (res.data.code == 200) reslove(res.data, res);
        else if ([401].indexOf(res.data.code) !== -1) {
          // 401及相关状态码处理：判断当前页面是否在白名单
          const currentPath = getCurrentPagePath();
          if (!WHITELIST.includes(currentPath)) {
            toLogin();
          }
          reject(res.data);
        } else {
          Toast({ title: res.data.message || "系统错误" });
          reject(res.data.message || "系统错误");
        }
      },
      fail: (msg) => {
        Toast({ title: "请求失败" });
        reject("请求失败");
      },
    });
  });
}

// 获取当前页面路径（格式如：/pages/index/index）
function getCurrentPagePath() {
  const pages = getCurrentPages();
  if (pages.length === 0) return "";
  const currentPage = pages[pages.length - 1];
  return `/${currentPage.route}`;
}

const request = {};

["options", "get", "post", "put", "head", "delete", "trace", "connect"].forEach(
  (method) => {
    request[method] = (api, data, opt, params) =>
      baseRequest(api, method, data, opt || {}, params);
  }
);

export default request;
