package com.yifu.cloud.plus.v1.yifu.social.util;

import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import org.apache.poi.xwpf.usermodel.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

/**
 * @author hgw2
 * @description word工具类
 * @date 2025/5/15
 */
public class WordUtil {

	public static void replaceTextInWord(String filePath, String outputFilePath, Map<String, String> replacements
			) throws IOException {
		try (FileInputStream fis = new FileInputStream(filePath);
			 XWPFDocument document = new XWPFDocument(fis)) {
			// 替换段落中的文本
			for (XWPFParagraph paragraph : document.getParagraphs()) {
				for (String key : replacements.keySet()) {
					if (paragraph.getText().contains(key)) {
						String newText = paragraph.getText().replace(key, replacements.get(key));
						paragraph.getRuns().clear();
						XWPFRun newRun = paragraph.createRun();
						newRun.setText(newText);
					}
				}
			}
			String text;
			// 替换表格中的文本
			for (XWPFTable table : document.getTables()) {
				for (XWPFTableRow row : table.getRows()) {
					for (XWPFTableCell cell : row.getTableCells()) {
						for (XWPFParagraph p : cell.getParagraphs()) {
							for (XWPFRun run : p.getRuns()) {
								text = run.getText(0);
								if (Common.isNotNull(text) && replacements.get(text) != null) {
									run.setText(replacements.get(text), 0);
								}
							}
						}
					}
				}
			}
			// 保存输出文件
			try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
				document.write(fos);
			}
		}
	}

}
