import { ElLoading, ElMessage } from "element-plus";
import dayjs from "dayjs";
import axios from "axios";

export default function useDownloadBlob(
  url,
  option = {
    name: dayjs().format("YYYY-MM-DD HH:mm:ss"),
    type: "application/vnd.ms-excel",
  }
) {
  return new Promise((resolve, reject) => {
    const loading = ElLoading.service({
      lock: true,
      text: "加载中...",
      background: "rgba(0, 0, 0, 0.5)",
    });
    axios
      .get(url, { responseType: "blob" })
      .then((resData) => {
        if (resData.data.type === "application/json") {
          throw new Error("导出失败");
        }
        const blob = new Blob([resData.data], {
          type: option.type,
        });
        const downloadElement = document.createElement("a");
        const href = window.URL.createObjectURL(blob);
        downloadElement.style.display = "none";
        downloadElement.href = href;
        downloadElement.download = option.name;
        document.body.appendChild(downloadElement);
        downloadElement.click();
        document.body.removeChild(downloadElement);
        window.URL.revokeObjectURL(href);
        loading.close();
        resolve(resData);
      })
      .catch((err) => {
        ElMessage.error("导出失败");
        loading.close();
        reject(err);
      });
  });
}
