import { ElMessageBox } from "element-plus";
import { getFileName, getFileSuffix } from "@/assets/js/utils.js";

export default async function useDownloadFile(url, name) {
  if (!url) throw new Error("没有下载地址");
  await ElMessageBox.confirm("确定要下载此文件吗？", { type: "warning" });
  const FILE_URL = import.meta.env.VITE_FILE_URL;
  name = name ? name + getFileSuffix(url) : getFileName(url);
  fetch(FILE_URL + url)
    .then((res) => res.blob())
    .then((blob) => {
      const a = document.createElement("a");
      document.body.appendChild(a);
      a.style.display = "none";
      const url = window.URL.createObjectURL(blob);
      a.href = url;
      a.download = `${name}`;
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    });
}
