import { message, Modal } from "antd";
import { useState } from "react";
import { getFileName, getFileSuffix, getFileUrl } from "../../utils";

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

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

    const { url, name: fileName } = options;
    if (!url) {
      console.error("【downloadFile】 缺少 url 参数");
      return;
    }

    Modal.confirm({
      title: "提示",
      content: "确定要下载此文件吗？",
      onOk: () => {
        const fileUrl = getFileUrl();
        let name = fileName;

        if (name) {
          if (!getFileSuffix(name) && getFileSuffix(url)) {
            name = `${name}.${getFileSuffix(url)}`;
          }
        }
        else {
          name = getFileName(url);
        }

        fetch(!url.includes(fileUrl) ? fileUrl + url : url)
          .then(res => res.blob())
          .then((blob) => {
            const a = document.createElement("a");
            document.body.appendChild(a);
            a.style.display = "none";
            const urlObject = window.URL.createObjectURL(blob);
            a.href = urlObject;
            a.download = `${name}`;
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(urlObject);
          })
          .catch(() => {
            message.error("下载失败");
          })
          .finally(() => {
            // 减少请求数量并在没有进行中的请求时设置loading为false
            requestCount--;
            if (requestCount <= 0) {
              setLoading(false);
            }
          });
      },
      onCancel: () => {
        // 减少请求数量并在没有进行中的请求时设置loading为false
        requestCount--;
        if (requestCount <= 0) {
          setLoading(false);
        }
      },
    });
  };

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