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

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.jodconverter.core.document.DefaultDocumentFormatRegistry;
import org.jodconverter.core.office.OfficeException;
import org.jodconverter.core.office.OfficeManager;
import org.jodconverter.local.LocalConverter;
import org.jodconverter.local.office.LocalOfficeManager;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author hgw2
 * @description word转图片
 * @date 2025/5/15
 */
public class WordToImageWithSeal {

	// 主方法用于测试或外部调用
	/*public static void main(String[] args) {
		String inputDocx = "D:/test/document.docx";
		String sealImagePath = "D:/seal/seal.png";
		String outputImagePath = "D:/output/document_with_seal.png";

		try {
			convertAndAddSeal(inputDocx, sealImagePath, outputImagePath);
			System.out.println("转换并加盖公章成功！");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}*/
	// 在生产环境中，建议在整个应用生命周期中共享一个OfficeManager：
	public static OfficeManager OFFICE_MANAGER;
	static {
		OFFICE_MANAGER = LocalOfficeManager.builder()
				.portNumbers(2002)
				.build();
		try {
			OFFICE_MANAGER.start();
		} catch (OfficeException e) {
			e.printStackTrace();
		}
	}
	public static void convertAndAddSeal(String inputDocx, InputStream sealImagePath, String outputImagePath) throws IOException, OfficeException {

		// Step 1: Word 转为 PDF（中间格式）
		File pdfFile = new File(inputDocx.replace(".docx", ".pdf"));
		/*converter.convert(new File(inputDocx)).as(DocumentType.DOCX)
				.to(pdfFile).as(DocumentType.PDF).execute();*/
		Map<String, Object> pdfProps = new HashMap<>();
		pdfProps.put("FilterName", "writer_pdf_Export");
		pdfProps.put("SelectPdfVersion", 1); // PDF/A-1
		LocalConverter.builder()
				.officeManager(OFFICE_MANAGER)
				.storeProperties(pdfProps)
				.build()
				.convert(new File(inputDocx))
				.to(pdfFile)
				.execute();

		// Step 2: PDF 转为 PNG 图片（可使用 Apache PDFBox 或 ImageMagick 转换）
		BufferedImage pageImage = convertPdfToImage(pdfFile.getAbsolutePath());

		// Step 3: 加盖公章
		BufferedImage sealedImage = addSealToImage(pageImage, sealImagePath);

		// Step 4: 输出图片
		ImageIO.write(sealedImage, "png", new File(outputImagePath));
		//ImageIO.write(sealedImage, "png", new File(outputImagePath));
	}

	private static BufferedImage convertPdfToImage(String pdfPath) throws IOException {
		try (PDDocument document = PDDocument.load(new File(pdfPath))) {
			PDFRenderer pdfRenderer = new PDFRenderer(document);
			// 渲染第一页为图像，分辨率为 300 DPI
			return pdfRenderer.renderImageWithDPI(0, 300, ImageType.RGB);
		}
	}

	private static BufferedImage addSealToImage(BufferedImage image, InputStream sealImagePath) throws IOException {
		BufferedImage seal = ImageIO.read(sealImagePath);

		BufferedImage combined = new BufferedImage(
				image.getWidth(),
				image.getHeight(),
				BufferedImage.TYPE_INT_ARGB);

		Graphics2D g = combined.createGraphics();
		g.drawImage(image, 0, 0, null);

		// 设置公章位置（右下角）
		int x = 1600;
		int y = 1150;

		g.drawImage(seal, x, y, null);
		g.dispose();

		return combined;
	}
}

