// src/utils/print.ts

export const usePrint = (target: HTMLElement) => {
  const printWindow = window.open('', '_blank')
  if (!printWindow) return

  const style = `
    <style>
      @page { size: A4; margin: 10mm; }
      body { margin: 0; padding: 0; }
    </style>
  `
  const content = target.innerHTML
  printWindow.document.write(`<html><head><title>打印</title>${style}</head><body>${content}</body></html>`)
  printWindow.document.close()

  const images = printWindow.document.images
  let loaded = 0
  const onload = () => {
    loaded++
    if (loaded === images.length) {
      printWindow.print()
      printWindow.close()
    }
  }

  if (images.length === 0) {
    printWindow.print()
    printWindow.close()
  } else {
    Array.from(images).forEach(img => {
      img.onload = img.onerror = onload
    })
  }
}
