import { Message } from "element-ui";

export default {
  async fileDownload(url, fileName) {
    try {
      // 检查URL是否合法
      if (!url) {
        Message.error("下载地址不能为空");
        return false;
      }
      // 检查文件类型
      const fileType = url
        .toLowerCase()
        .split(".")
        .pop();
      if (!["jpg", "jpeg", "png", "gif", "webp","mp4","mov","mp3"].includes(fileType)) {
        Message.error("该文件的格式不支持下载");
        return false;
      }
      const response = await fetch(url, {
        method: "GET",
        credentials: "include" // 包含 cookies
      });

      if (!response.ok) {
        Message.error("下载失败");
        return false;
      }

      const blob = await response.blob();
      const $link = document.createElement("a");
      $link.href = URL.createObjectURL(blob);
      
      // 确保文件名包含正确的后缀
      let finalFileName = fileName || url.split("/").pop() || "download";
      if (!finalFileName.toLowerCase().endsWith(`.${fileType}`)) {
        finalFileName = `${finalFileName}.${fileType}`;
      }
      $link.download = finalFileName;
      
      document.body.appendChild($link);
      $link.click();
      document.body.removeChild($link);
      URL.revokeObjectURL($link.href);
      return true;
    } catch (error) {
      Message.error(error);
      return false;
    }
  }
};
