import { useAuthStore } from "@/stores/auth.store"

export function useReportExport() {
  const authStore = useAuthStore()

  // async function download(name: string, id: number) {
  //   return reportExportService.download(id).then((resp) => {
  //     if (!resp) {
  //       return
  //     }
  //     const url = window.URL.createObjectURL(new Blob([resp]))
  //     const a = document.createElement('a')
  //     a.style.display = 'none'
  //     a.setAttribute('download', name + '.docx')
  //     a.href = url
  //     document.body.appendChild(a)
  //     a.click()
  //     window.URL.revokeObjectURL(a.href)
  //     document.body.removeChild(a)
  //   })
  // }

  function download(name: string, id: number) {
    const href = link(id, authStore.token)
    if (!href) {
      return
    }
    const a = document.createElement("a")
    a.setAttribute("download", name + '.docx')
    a.setAttribute("href", href)
    a.style.display = 'none'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
  }

  /**
   * 生成报告下载链接
   * @param id 报告ID
   * @param token 用户token
   * @returns 报告下载的链接字符串或者null
   */
  function link(id: number, token: string | null) {
    if (!token || !id) {
      return null
    }
    return `/gw/user/reportExport/${id}?token=${token}`
  }

  return { download, link }
}
