import { message } from "antd";
import dayjs from "dayjs";
import { useState } from "react";

/**
 * 下载Blob流文件
 */
export default function useDownloadBlob(returnType = "object") {
  // loading状态
  const [loading, setLoading] = useState(false);
  // 用于跟踪进行中的请求数量（不暴露给外部）
  let requestCount = 0;

  // 下载Blob流文件
  const downloadBlob = (url, options) => {
    // 增加请求数量并设置loading状态
    requestCount++;
    if (requestCount > 0) {
      setLoading(true);
    }

    if (!url) {
      console.error("【downloadBlob】 缺少 url 参数");
      return;
    }

    return new Promise((resolve, reject) => {
      const { name = "", type = "", params = {} } = options;
      const finalUrl = new URL((process.env.app.API_HOST || window.__JJB_ENVIRONMENT__.API_HOST) + url);
      Object.entries(params).forEach(([key, value]) => {
        finalUrl.searchParams.append(key, value);
      });
      fetch(finalUrl, {
        method: "GET",
        mode: "cors",
        headers: {
          "Content-Type": "application/json",
          "token": window.sessionStorage["token"],
        },
      })
        .then((response) => {
          if (!response.ok) {
            console.error("【downloadBlob】 网络响应异常");
            return;
          }
          return response.blob();
        })
        .then((blob) => {
          const finalBlob = new Blob([blob], {
            type: type || "application/vnd.ms-excel",
          });
          const downloadElement = document.createElement("a");
          const href = window.URL.createObjectURL(finalBlob);
          downloadElement.style.display = "none";
          downloadElement.href = href;
          downloadElement.download
            = name || dayjs().format("YYYY-MM-DD HH:mm:ss");
          document.body.appendChild(downloadElement);
          downloadElement.click();
          document.body.removeChild(downloadElement);
          window.URL.revokeObjectURL(href);
          resolve({ data: finalBlob });
        })
        .catch((err) => {
          message.error("导出失败");
          reject(err);
        })
        .finally(() => {
          // 减少请求数量并在没有进行中的请求时设置loading为false
          requestCount--;
          if (requestCount <= 0) {
            setLoading(false);
          }
        });
    });
  };

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