import { objTypeOf, blobToText } from "./utils";

function parseDownloadFilename(dispositionInfo) {
  // console.log(dispositionInfo);
  const strs = dispositionInfo.split(";");
  let filename = "";
  strs
    .map((item) => item.split("="))
    .find((item) => {
      if (item[0].indexOf("filename") !== -1) {
        filename = decodeURI(item[1]);
      }
    });
  return filename;
}

/**
 * 通过api下载文件
 * @param {AxiosPromise} fetchFunc 下载接口
 * @param {String}} fileName 文件名
 * @returns Promise<Boolean>
 */
export async function downloadByApi(fetchFunc, fileName) {
  let errorInfo = null;
  const res = await fetchFunc().catch((e) => {
    errorInfo = e;
  });

  // 展示后台错误信息
  if (errorInfo && objTypeOf(errorInfo) === "blob") {
    const res = await blobToText(errorInfo).catch(() => {});
    if (!res) return Promise.reject("下载失败！");
    const resJson = JSON.parse(res);
    return Promise.reject(resJson.message);
  }

  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, filename) {
  const blobUrl = URL.createObjectURL(data);
  downloadByUrl(blobUrl, filename);
}

/**
 * 下载url
 * @param {String} url 文件下载地址
 * @param {String}} filename 文件名
 */
export function downloadByUrl(url, filename) {
  const tempLink = document.createElement("a");
  tempLink.style.display = "none";
  tempLink.href = url;
  const fileName = filename || url.split("/").pop().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);
}

/**
 * 下载图片
 * @param {String} url 图片地址
 * @param {String} filename 下载的文件名
 * @returns Promise<Boolean>
 */
export function downloadByImgUrl(url, filename) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    // 跨域支持，需要服务端辅助配置
    img.crossOrigin = "";
    img.onload = function () {
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");

      if (!canvas || !ctx) {
        return reject("不支持下载!");
      }

      canvas.width = img.width;
      canvas.height = img.height;
      ctx.drawImage(img, 0, 0);
      canvas.toBlob((blob) => {
        downloadByBlob(blob, filename);
        resolve(true);
      });
    };
    img.onerror = function (e) {
      reject(e);
    };
    img.src = url;
  });
}
