import { ElNotification, ElMessage } from "element-plus";
import { downloadFile } from "@/utils";
import { ResultEnum } from "@/enums/httpEnum";

/**
 * @description 接收数据流生成 blob，创建链接，下载文件
 * @param {Function} api 导出表格的api方法 (必传)
 * @param {String} tempName 导出的文件名 (必传)
 * @param {Object} params 导出的参数 (默认{})
 * @param {Boolean} isNotify 是否有导出消息提示 (默认为 true)
 * @param {String} fileType 导出的文件格式 (默认为.xlsx)
 * */
export const useDownload = async (
  api: (param: any) => Promise<any>,
  tempName: string,
  params: any = {},
  isNotify: boolean = true,
  fileType: string = ".xlsx"
) => {
  if (isNotify) {
    ElNotification({
      title: "温馨提示",
      message: "如果数据庞大会导致下载缓慢哦，请您耐心等待！",
      type: "info",
      duration: 3000
    });
  }
  const res = await api(params);
  if (res.data instanceof Blob && res.data.type.includes("application/json")) {
    const resJsonStr = await res.data.text();
    const resJson = JSON.parse(resJsonStr);
    if (resJson.code !== ResultEnum.SUCCESS) {
      ElMessage.error(resJson.msg);
      throw new Error(resJson.msg);
    }
  }
  let fileName;
  if (tempName) {
    fileName = `${tempName}${fileType}`;
  } else {
    fileName = extractFilenameFromContentDisposition(res.headers["content-disposition"]);
  }
  const blob = res.data instanceof Blob ? res.data : new Blob([res]);
  // 兼容 edge 不支持 createObjectURL 方法
  if ("msSaveOrOpenBlob" in navigator) return window.navigator.msSaveOrOpenBlob(blob, fileName);
  downloadFile(blob, fileName);
};

function extractFilenameFromContentDisposition(contentDisposition: string) {
  // 使用正则表达式匹配filename部分
  const match = /filename\*?=['"]?(?:UTF-\d['"]*)?([^;\r\n"']*)['"]?;?/i.exec(contentDisposition);

  // 如果找到匹配项，则解码并返回filename的值
  if (match && match[1]) {
    return decodeURIComponent(match[1]);
  }

  // 如果没有找到匹配项，则返回空字符串或其他默认值
  return "";
}
