package com.hotent.util.wordexcelutils;

import com.hotent.base.util.StringUtil;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.IOUtils;

import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * Word文档处理工具类
 */
public class WordProcessor {
    
    /**
     * 替换Word文档中的占位符（文字和图片）
     * @param templatePath 模板文件路径
     * @param outputPath 输出文件路径
     * @param textReplacements 文字替换映射
     * @param imageReplacements 图片替换映射
     */
    public static void replacePlaceholdersInWord(String templatePath, String outputPath,
                                               Map<String, String> textReplacements,
                                               Map<String, String> imageReplacements) {
        try (FileInputStream fis = new FileInputStream(templatePath);
             XWPFDocument document = new XWPFDocument(fis);
             FileOutputStream fos = new FileOutputStream(outputPath)) {
            
            // 替换段落中的文本占位符
            replaceTextInParagraphs(document.getParagraphs(), textReplacements, imageReplacements);
            
            // 替换表格中的文本占位符
            for (XWPFTable table : document.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        replaceTextInParagraphs(cell.getParagraphs(), textReplacements, imageReplacements);
                    }
                }
            }
            
            document.write(fos);
        } catch (IOException  e) {
            throw new RuntimeException("处理Word文档时出错", e);
        }
    }
    
    /**
     * 替换段落中的占位符
     */
    private static void replaceTextInParagraphs(List<XWPFParagraph> paragraphs,
                                              Map<String, String> textReplacements,
                                              Map<String, String> imageReplacements) {
        for (XWPFParagraph paragraph : paragraphs) {
            for (XWPFRun run : paragraph.getRuns()) {
                String text = run.getText(0);
                if (text != null) {
                    // 替换文本占位符
                    for (Map.Entry<String, String> entry : textReplacements.entrySet()) {
                        if (text.contains(entry.getKey())) {
                            if (StringUtil.isEmpty(entry.getValue())) {
                                continue;
                            }
                            text = text.replace(entry.getKey(), entry.getValue());
                            run.setText(text, 0);
                        }
                    }
                    
                    // 处理图片占位符
                    for (Map.Entry<String, String> entry : imageReplacements.entrySet()) {
                        if (text.contains(entry.getKey())) {
                            // 清除占位符文本
                            run.setText("", 0);
                            
                            // 插入图片
                            try (FileInputStream imageStream = new FileInputStream(entry.getValue())) {
                                byte[] imageBytes = IOUtils.toByteArray(imageStream);
                                int pictureType = getImageType(entry.getValue());
                                String imageName = "image";
                                
                                paragraph.createRun().addPicture(
                                    new ByteArrayInputStream(imageBytes),
                                    pictureType,
                                    imageName,
                                    Units.toEMU(200), // 宽度
                                    Units.toEMU(150)  // 高度
                                );
                            } catch (Exception e) {
                                throw new RuntimeException("插入图片时出错", e);
                            }
                        }
                    }
                }
            }
        }
    }
    
    /**
     * 根据文件扩展名获取图片类型
     */
    private static int getImageType(String imagePath) {
        String extension = imagePath.substring(imagePath.lastIndexOf(".") + 1).toLowerCase();
        switch (extension) {
            case "png": return Document.PICTURE_TYPE_PNG;
            case "jpg":
            case "jpeg": return Document.PICTURE_TYPE_JPEG;
            case "gif": return Document.PICTURE_TYPE_GIF;
            case "bmp": return Document.PICTURE_TYPE_BMP;
            default: return Document.PICTURE_TYPE_JPEG;
        }
    }
}
