import { ElMessageBox } from "element-plus"
import axios from "axios"

/**
 * 导出
 * @param params 查询参数
 * @param exportApi 导出的 api 方法
 * @param isToast 是否弹出确认提示
 * @returns
 */
const onExportUtil = async (
  params: any, // 导出参数
  exportApi: ((params: any) => Promise<any>) | null = null, // 导出接口方法，可选
  isToast: boolean = true // 是否显示确认提示框，默认显示
) => {
  if (!exportApi) {
    // 未配置导出接口
    return await ElMessageBox.alert("未配置导出地址", "提示")
  }

  if (isToast) {
    try {
      // 确认导出；用户点击取消/关闭时 confirm 会 reject，需要捕获
      await ElMessageBox.confirm("是否确认导出 ？", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
    } catch {
      // 用户取消，直接返回
      return
    }
  }

  try {
    // 调用导出接口获取文件信息
    const res: any = await exportApi(params)

    // 后端可能没有返回 body，或 body 为 null，使用可选链兜底
    const fileName: string | undefined = res?.body?.fileName
    const filePath: string | undefined = res?.body?.filePath
    const fileUrl = filePath || fileName

    if (!fileUrl) {
      await ElMessageBox.alert("没有可用的文件下载地址", "下载失败")
      return Promise.reject(false)
    }

    if (fileUrl.startsWith("data:")) {
      await downolad2FileUrl(fileUrl, (filePath && fileName) || "导出文件")
      return
    }

    // 使用 HEAD 方法检查文件是否存在
    const headRes = await fetch(fileUrl, { method: "HEAD" })
    if (headRes.ok) {
      await downloadFileUtil(fileUrl, (filePath && fileName) || getFileName(fileUrl))
    } else {
      console.error("下载文件不存在")
      await ElMessageBox.alert("下载文件不存在", "下载失败")
      return Promise.reject(false)
    }
  } catch (e: any) {
    console.error(e)
    return Promise.reject(false)
  }
}

/**
 * 通过文件的服务器路径获取文件名
 * @param url
 * @returns
 */
const getFileName = (url: string): string => {
  // 去掉查询参数和 hash，再取最后一段
  const pureUrl = url.split("?")[0].split("#")[0]
  const parts = pureUrl.split("/")
  const filename = parts[parts.length - 1]
  try {
    return decodeURIComponent(filename)
  } catch {
    return filename
  }
}

/**
 * 下载文件
 * @param url
 * @param fileName
 */
export const downloadFileUtil = async (url: string, fileName: string) => {
  // 参数验证
  if (!url || typeof url !== "string") {
    return await ElMessageBox.alert("URL不能为空且必须是字符串")
  }

  if (!fileName || typeof fileName !== "string") {
    return await ElMessageBox.alert("文件名不能为空且必须是字符串")
  }

  const res = await axios.get(url, {
    responseType: "blob",
    onDownloadProgress: (e) => {
      if (e.total) {
        const percent = Math.round((e.loaded / e.total) * 100)
        console.log("下载进度:", percent + "%")
      } else {
        console.log("已下载:", e.loaded)
      }
    }
  })

  // 创建下载
  const blob = new Blob([res.data])
  const objectUrl = URL.createObjectURL(blob)
  const link = document.createElement("a")
  link.href = objectUrl
  link.download = fileName
  document.body.appendChild(link) // 必须先添加到 DOM，后面才能 remove
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(objectUrl)
  return true
}

/**
 * 通过地址下载文件
 * @param url 文件下载地址
 * @param fileName 可选的保存文件名，默认从 URL 提取
 */
export const downolad2FileUrl = async (url: string, fileName = getFileName(url)) => {
  const a = document.createElement("a")
  a.href = url
  a.download = fileName
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

export default onExportUtil
