<template>
  <a-tooltip content="导出" position="bottom">
    <a-button 
      size="small"
      type="outline"
      @click="exportPDF"
      :loading="exporting"
    >
      <template #icon>
        <icon-file-pdf />
      </template>
    </a-button>
  </a-tooltip>
</template>

<script>
import { ref } from 'vue'
import { Message } from '@arco-design/web-vue'

export default {
  name: 'PdfExportButton',
  emits: ['export-start', 'export-complete'],
  props: {
    title: {
      type: String,
      default: '文档'
    },
    containerSelector: {
      type: String,
      default: '.markdown-body'
    }
  },
  setup(props, { emit }) {
    const exporting = ref(false)

    function escapeHtml(str) {
      const map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' }
      return str.replace(/[&<>"']/g, c => map[c])
    }

    function stripScripts(html) {
      return html
        .replace(/<script[\s\S]*?<\/script>/gi, '')
        .replace(/<script[^>]*>/gi, '')
        .replace(/\son\w+\s*=\s*("[^"]*"|'[^']*'|[^\s>]*)/gi, '')
        .replace(/<iframe[\s\S]*?<\/iframe>/gi, '')
        .replace(/<object[\s\S]*?<\/object>/gi, '')
        .replace(/<embed[^>]*>/gi, '')
    }

    const exportPDF = async () => {
      if (exporting.value) return
      
      exporting.value = true
      emit('export-start')
      
      try {
        // 获取渲染后的 Markdown 内容
        const contentElement = document.querySelector(props.containerSelector)
        
        if (!contentElement) {
          Message.error('没有可导出的内容')
          exporting.value = false
          return
        }
        
        const htmlContent = stripScripts(contentElement.innerHTML)

        if (!htmlContent || !htmlContent.trim()) {
          Message.error('内容为空，无法导出')
          exporting.value = false
          return
        }
        
        // 打开打印窗口
        const printWindow = window.open('', '_blank', 'width=800,height=600')
        
        if (!printWindow) {
          Message.error('无法打开打印窗口，请检查浏览器弹窗设置')
          exporting.value = false
          return
        }
        
        // 写入打印内容
        printWindow.document.write(`
          <!DOCTYPE html>
          <html>
          <head>
            <meta charset="UTF-8">
            <title>${escapeHtml(props.title)}</title>
            <style>
              * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
              }
              
              body {
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
                font-size: 14px;
                line-height: 1.6;
                color: #333;
                padding: 40px;
                max-width: 800px;
                margin: 0 auto;
              }
              
              h1, h2, h3, h4, h5, h6 {
                margin-top: 24px;
                margin-bottom: 16px;
                font-weight: 600;
                line-height: 1.25;
                page-break-after: avoid;
              }
              
              h1 { font-size: 2em; border-bottom: 1px solid #eaecef; padding-bottom: 0.3em; }
              h2 { font-size: 1.5em; border-bottom: 1px solid #eaecef; padding-bottom: 0.3em; }
              h3 { font-size: 1.25em; }
              h4 { font-size: 1em; }
              h5 { font-size: 0.875em; }
              h6 { font-size: 0.85em; color: #6a737d; }
              
              p {
                margin-top: 0;
                margin-bottom: 16px;
              }
              
              ul, ol {
                padding-left: 2em;
                margin-top: 0;
                margin-bottom: 16px;
              }
              
              li {
                margin-top: 0.25em;
                margin-bottom: 0.25em;
              }
              
              blockquote {
                padding: 0 1em;
                color: #6a737d;
                border-left: 0.25em solid #dfe2e5;
                margin: 0 0 16px 0;
              }
              
              code {
                padding: 0.2em 0.4em;
                margin: 0;
                font-size: 85%;
                background-color: rgba(27, 31, 35, 0.05);
                border-radius: 3px;
                font-family: 'SF Mono', Monaco, Consolas, 'Courier New', monospace;
              }
              
              pre {
                padding: 16px;
                overflow: auto;
                font-size: 85%;
                line-height: 1.45;
                background-color: #f6f8fa;
                border-radius: 6px;
                margin-top: 0;
                margin-bottom: 16px;
                page-break-inside: avoid;
              }
              
              pre code {
                padding: 0;
                margin: 0;
                background-color: transparent;
                border: 0;
              }
              
              table {
                border-spacing: 0;
                border-collapse: collapse;
                margin-top: 0;
                margin-bottom: 16px;
                width: 100%;
                page-break-inside: avoid;
              }
              
              table th,
              table td {
                padding: 6px 13px;
                border: 1px solid #dfe2e5;
              }
              
              table th {
                font-weight: 600;
                background-color: #f6f8fa;
              }
              
              table tr:nth-child(even) {
                background-color: #f8f8f8;
              }
              
              img {
                max-width: 100%;
                page-break-inside: avoid;
              }
              
              hr {
                height: 0.25em;
                padding: 0;
                margin: 24px 0;
                background-color: #e1e4e8;
                border: 0;
              }
              
              @media print {
                body {
                  padding: 0;
                }
                
                @page {
                  margin: 15mm;
                  size: A4;
                }
              }
            </style>
          </head>
          <body>
            ${htmlContent}
          </body>
          </html>
        `)
        
        printWindow.document.close()
        
        // 等待内容加载完成后自动打印
        let printTriggered = false
        printWindow.onload = () => {
          printTriggered = true
          printWindow.print()
        }

        // 兼容性处理：如果 onload 未触发
        setTimeout(() => {
          if (!printTriggered && printWindow && !printWindow.closed) {
            printWindow.print()
          }
        }, 500)
        
        Message.success('请在打印对话框中选择"另存为 PDF"')
        emit('export-complete')
        
      } catch (error) {
        console.error('PDF导出失败:', error)
        Message.error(`PDF导出失败：${error.message || '未知错误'}`)
      } finally {
        exporting.value = false
      }
    }
    
    return {
      exporting,
      exportPDF
    }
  }
}
</script>
