import { AxiosResponse } from "axios";

const parseDownloadFilename = (dispositionInfo: string): string => {
  if (!dispositionInfo) return "";
  const matchs = dispositionInfo.match(/attachment;filename=(.*)/) || [];
  const filename = matchs[1];
  return filename ? decodeURI(filename) : "";
};

interface ApiFunc {
  (): Promise<AxiosResponse<Blob, any>>;
}
/**
 * 通过api下载文件
 * @param axiosFetchFunc axios请求方法
 * @param fileName 文件保存名称
 * @returns
 */
export function downloadBlobByApi(axiosFetchFunc: ApiFunc, fileName?: string) {
  return axiosFetchFunc().then((res: AxiosResponse) => {
    // console.log(res);

    const filename =
      fileName || parseDownloadFilename(res.headers["content-disposition"]);
    downloadByBlob(new Blob([res.data]), filename);
    return true;
  });
}

/**
 * 下载blob
 * @param {Blob} data blob对象
 * @param {String} filename 文件名
 */
export function downloadByBlob(data: Blob, filename?: string) {
  const blobUrl = window.URL.createObjectURL(data);
  downloadByUrl(blobUrl, filename);
}

/**
 * 下载url
 * @param {String} url 文件下载地址
 * @param {String}} filename 文件名
 */
export function downloadByUrl(url: string, filename?: string) {
  const tempLink = document.createElement("a");
  tempLink.style.display = "none";
  tempLink.href = url;
  let fileName = filename;
  if (!fileName) {
    const strs = url.split("/").pop() || "";
    fileName = strs.split("?")[0];
  }
  tempLink.setAttribute("download", fileName);
  if (tempLink.download === "undefined") {
    tempLink.setAttribute("target", "_blank");
  }
  document.body.appendChild(tempLink);
  tempLink.click();
  document.body.removeChild(tempLink);
  window.URL.revokeObjectURL(url);
}

/**
 * 通过url获得blob
 * @param url 链接
 */
export function toBlobByUrl(url: string) {
  return fetch(url).then((response) => {
    return response.blob();
  });
}
