// src/components/FilePreviewModal/DocxPreview.tsx
import React, { useEffect, useRef } from 'react'
import { renderAsync } from 'docx-preview'
import './DocxPreview.css' // 导入样式文件

interface DocxPreviewProps {
  src: string
  className?: string
  onRendered?: () => void
  onError?: (error: any) => void
}

export const DocxPreview: React.FC<DocxPreviewProps> = ({ src, className = '', onRendered, onError }) => {
  const containerRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (src && containerRef.current) {
      fetch(src)
        .then(response => response.arrayBuffer())
        .then((arrayBuffer) => {
          const blob = new Blob([arrayBuffer], {
            type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          })

          // 清空容器
          if (containerRef.current) {
            containerRef.current.innerHTML = ''
          }

          return renderAsync(blob, containerRef.current!, undefined, {
            className: 'docx-document', // 使用特定类名避免样式冲突
            inWrapper: true,
            breakPages: true,
            ignoreWidth: false,
            ignoreHeight: false,
            ignoreFonts: false,
            // 添加更多配置以改善渲染效果
            renderHeaders: true,
            renderFooters: true,
            renderFootnotes: true,
          })
        })
        .then(() => {
          onRendered?.()
        })
        .catch((error) => {
          console.error('DOCX 渲染失败:')
          onError?.(error)
        })
    }
  }, [src, className, onRendered, onError])

  return (
    <div
      ref={containerRef}
      className={className}
      style={{
        overflow: 'auto',
        height: '100%',
        padding: '1rem',
        backgroundColor: '#fff',
        maxWidth: '100%',
        boxSizing: 'border-box',
        // 添加以下样式以改善显示效果
        lineHeight: '1.6',
        wordWrap: 'break-word',
        wordBreak: 'break-word',
      }}
    />
  )
}
