import { request } from "@cqsjjb/jjb-common-lib/http.js";
import { useState } from "react";
import { getBaseGateway } from "../../utils";

/**
 * 获取用户信息
 */
function useGetUserInfo(returnType = "object") {
  // loading状态
  const [loading, setLoading] = useState(false);
  // 用于跟踪进行中的请求数量（不暴露给外部）
  let requestCount = 0;

  // 获取用户信息
  const getUserInfo = () => {
    // 增加请求数量并设置loading状态
    requestCount++;
    if (requestCount > 0) {
      setLoading(true);
    }

    return new Promise((resolve, reject) => {
      // 发送请求
      request(
        `/${getBaseGateway()}/user/getInfo`,
        "get",
        {},
      )
        .then((res) => {
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        })
        .finally(() => {
          // 减少请求数量并在没有进行中的请求时设置loading为false
          requestCount--;
          if (requestCount <= 0) {
            setLoading(false);
          }
        });
    });
  };

  if (returnType === "array")
    return [loading, getUserInfo];
  return { loading, getUserInfo };
}

export default useGetUserInfo;
