package com.goafanti.common.utils;

import com.goafanti.common.utils.excel.FileUtils;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTable;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Word文档合并为PDF工具类
 */
public class WordToPDFMerger {

    /**
     * 将两个Word文档合并为一个PDF文件并提供下载
     * 
     * @param wordFile1 第一个Word文件路径
     * @param wordFile2 第二个Word文件路径
     * @param response  HttpServletResponse对象
     * @param pdfFileName 生成的PDF文件名
     * @param uploadPath 上传路径
     */
    public static void mergeWordDocumentsToPdf(String wordFile1, String wordFile2, 
                                               HttpServletResponse response, String pdfFileName, String uploadPath) {
        String realFileName = uploadPath + "/tmp/" + System.currentTimeMillis() + ".pdf";
        
        Document document = new Document(PageSize.A4);
        
        try {
            // 设置响应头，用于文件下载
            FileUtils.setAttachmentResponseHeader(response, pdfFileName, pdfFileName + ".pdf");
            
            // 创建PDF写入器
            FileOutputStream outputStream = new FileOutputStream(realFileName);
            PdfWriter.getInstance(document, outputStream);
            
            document.open();
            
            // 处理第一个Word文档
            processWordDocument(wordFile1, document);
            
            // 添加分页
            document.newPage();
            
            // 处理第二个Word文档
            processWordDocument(wordFile2, document);
            
            document.close();
            outputStream.close();
            
            // 提供文件下载
            FileUtils.writeBytes(realFileName, response.getOutputStream());
            FileUtils.deleteFile(realFileName);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 处理单个Word文档并将其内容添加到PDF文档中
     * 
     * @param wordFilePath Word文件路径
     * @param document PDF文档对象
     * @throws IOException
     * @throws DocumentException
     */
    private static void processWordDocument(String wordFilePath, Document document) 
            throws IOException, DocumentException {
        
        try (InputStream in = new FileInputStream(wordFilePath)) {
            XWPFDocument xwpfDocument = new XWPFDocument(in);
            
            // 获取文档中的所有段落
            List<XWPFParagraph> paragraphs = xwpfDocument.getParagraphs();
            
            for (XWPFParagraph paragraph : paragraphs) {
                // 创建PDF段落
                String text = paragraph.getText();
                if (text != null && !text.isEmpty()) {
                    document.add(new Paragraph(text));
                }
            }
            
            // 处理表格（如果有）
            List<XWPFTable> tables = xwpfDocument.getTables();
            for (XWPFTable table : tables) {
                // 添加表格标识（实际项目中可以进一步处理表格内容）
                document.add(new Paragraph("[表格内容]"));
            }
        }
    }


}
