/**
 * 使用 html-to-image 库实现打印功能
 */
import { processElement } from './core'

const createPrintIframe = (dataUrl, title) => {
  const iframe = document.createElement('iframe')
  iframe.style.position = 'absolute'
  iframe.style.width = '0'
  iframe.style.height = '0'
  iframe.style.border = 'none'
  iframe.style.left = '-9999px'

  document.body.appendChild(iframe)

  const iframeDoc = iframe.contentWindow.document

  iframeDoc.open()
  iframeDoc.write(`
    <!DOCTYPE html>
    <html>
      <head>
        <title>${title}</title>
        <style>
          @media print { body { margin: 0; padding: 0; } img { width: 100%; height: auto; max-width: 100%; } }
          body { margin: 0; padding: 0; text-align: center; }
          img { width: 100%; height: auto; }
        </style>
      </head>
      <body><img src="${dataUrl}" /></body>
    </html>
  `)
  iframeDoc.close()

  iframe.onload = () => {
    setTimeout(() => {
      try {
        iframe.contentWindow.focus()
        iframe.contentWindow.print()
      } catch (e) {
        console.error('打印失败:', e)
      }
      setTimeout(() => {
        document.body.removeChild(iframe)
      }, 1000)
    }, 500)
  }
}

/**
 * 使用 html-to-image 打印（PNG格式）
 * @param {String} elementId - 需要打印的元素ID（不带#）
 * @param {String} title - 打印页面标题
 * @param {Object} options - 可选配置
 */
export const printWithHtmlToImage = async (elementId, title = '打印内容', options = {}) => {
  const backgroundColor = options.backgroundColor || '#f0f2f5'
  const dataUrl = await processElement(elementId, {
    beforeProcess: options.beforePrint,
    afterProcess: options.afterPrint,
    format: options.format || 'png',
    quality: options.quality || 0.95,
    pixelRatio: options.pixelRatio ?? 2,
    backgroundColor
  })
  createPrintIframe(dataUrl, title)
  return Promise.resolve()
}

/**
 * 使用 html-to-image 打印（JPEG格式）
 */
export const printWithHtmlToImageJpeg = async (elementId, title = '打印内容', options = {}) => {
  return printWithHtmlToImage(elementId, title, { ...options, format: 'jpeg' })
}
