const BASEURL = import.meta.env.VITE_API_BASEURL;

export default function downloadExcel(res) {
  let disposition = res.headers.get("Content-Disposition");
  let sDowName = "";
  if (disposition) {
    // 解析出名稱
    sDowName = disposition.split(/filename\*=(?:utf-8'')?(.*)/gi)[1];
    if (sDowName.toLowerCase().startsWith("utf-8''"))
      sDowName = decodeURIComponent(sDowName.replace(/utf-8''/i, ""));
    else sDowName = sDowName.replace(/['"]/g, "");
    sDowName = decodeURIComponent(sDowName);
  }

  let blob = res.data;

  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, sDowName);
  } else {
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = sDowName;
    document.body.appendChild(link);
    link.click();
    // 釋放內存
    window.URL.revokeObjectURL(link.link);
    document.body.removeChild(link);
  }
}

export const downloadExcelByHref = async (url, filename) => {
  const response = await fetch(url);
  const blob = await response.blob();

  const link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.setAttribute("download", filename);
  // link.setAttribute("target", "_blank");
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
