import { message } from 'antd'

const downloadFile = async ({ src, fileName }: { src: string; fileName?: string }) => {
  const response = await fetch(src)

  const blob = await response.blob()

  const url = window.URL.createObjectURL(blob)

  const anchorElement = document.createElement('a')

  anchorElement.style.display = 'none'

  anchorElement.href = url

  anchorElement.download = fileName ?? src.match(/[^/]+$/)?.[0] ?? 'unknow'

  document.body.appendChild(anchorElement)

  anchorElement.click()

  message.success('文件下载完成')

  document.body.removeChild(anchorElement)

  window.URL.revokeObjectURL(url)
}

export { downloadFile }
