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

import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.social.config.SocialFriendConfig;
import com.yifu.cloud.plus.v1.yifu.social.entity.TSocialFriendBackLog;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.util.Base64;
import java.util.Map;

/**
 * @author hgw
 * @description word工具类
 * @date 2025-5-26 16:03:05
 */
@Component
public class WordToImageUtil {

	private static final String  PDF_TEMP ="\\test126666.docx";
	private static final String  IMAGE_TEMP ="\\document_with_seal.png";
	private static final String  TO_IMAGE_TEMP ="\\ToImgTemp.png";
	public String replaceTextInWord(InputStream templateFile, Map<String, String> replacements
			, InputStream imageStream, RestTemplate restTemplate, SocialFriendConfig socialFriendConfig
			, TSocialFriendBackLog backLog) {
		String projectRoot = System.getProperty(CommonConstants.USER_DIR);
		String outputFilePath = projectRoot + PDF_TEMP;
		String outputImagePath = projectRoot + IMAGE_TEMP;
		try (XWPFDocument document = new XWPFDocument(templateFile)) {
			// 替换段落中的文本
			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);
			}
			return convertAndAddSeal(outputFilePath, imageStream, outputImagePath, projectRoot, restTemplate
					, socialFriendConfig, backLog);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (imageStream != null) {
				try {
					imageStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return "-";
	}

	public String convertAndAddSeal(String inputDocx, InputStream sealImagePath, String outputImagePath
			, String projectRoot, RestTemplate restTemplate, SocialFriendConfig socialFriendConfig
			, TSocialFriendBackLog backLog) throws Exception {

		File pdfFile = null;
		Document doc = null;
		File tempImgFile = null;
		File imgFile = null;
		try {

			pdfFile = new File(inputDocx);
			String filename = pdfFile.getName();
			// 打开生成的 Word 文件
			doc = new Document(new FileInputStream(pdfFile));
			String pathPre = filename.substring(0, filename.lastIndexOf("."));
			// 逐页将 Word 文件保存为图片（PNG格式）
			String path = pathPre + ".png";
			if (doc.getPageCount() > 0) {
				Document extractedPage = doc.extractPages(0,1);
				// 拼接上文件名 test1.png
				// 将 Word 文件保存为图片PNG格式
				extractedPage.save(path, SaveFormat.PNG);
			}

			tempImgFile = new File(path);
			BufferedImage pageImage = ImageIO.read(tempImgFile);
			// Step 3: 加盖公章
			BufferedImage sealedImage = addSealToImage(pageImage, sealImagePath);

			imgFile = new File(outputImagePath);
			// Step 4: 输出图片
			ImageIO.write(sealedImage, "png", imgFile);
			if (imgFile.exists()) {
				// file 压缩到1M以内
				imgFile = compressImage(projectRoot, imgFile);
				String key  = System.currentTimeMillis() + imgFile.getName();
				byte[] fileContent = Files.readAllBytes(imgFile.toPath());
				String base64String = Base64.getEncoder().encodeToString(fileContent);
				String url = socialFriendConfig.uploadPng(restTemplate, key, base64String, backLog);
				if (Common.isEmpty(url)){
					return "--";
				}
				return url;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (tempImgFile != null) {
				tempImgFile.delete();
			}
			if (doc != null) {
				doc.cleanup();
			}
			if (pdfFile != null) {
				pdfFile.delete();
			}
			if (imgFile != null) {
				imgFile.delete();
			}

		}
		return "---";
	}

	private File compressImage(String projectRoot, File originalFile) throws IOException {
		BufferedImage image = ImageIO.read(originalFile);
		int quality = 100; // 从100%开始
		File compressedFile = new File(projectRoot, TO_IMAGE_TEMP);
		int maxSize = 1024 * 1024;
		try {
			while (originalFile.length() > maxSize && quality > 10) {
				quality -= 5;
				ImageIO.write(image, "png", compressedFile);
				if (compressedFile.length() < maxSize) {
					originalFile.delete();
					compressedFile.renameTo(originalFile);
					break;
				}
				compressedFile.delete();
			}
		} catch (Exception e) {
			if (compressedFile != null && compressedFile.exists()) {
				compressedFile.delete();
			}
		}
		return originalFile;
	}


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

		// 设置公章目标大小
		int targetWidth = 200;  // 宽度
		int targetHeight = 200; // 高度

		// 创建缩放后的公章图像
		Image scaledSeal = seal.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);
		BufferedImage resizedSeal = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_ARGB);
		Graphics2D g2d = resizedSeal.createGraphics();
		g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		g2d.drawImage(scaledSeal, 0, 0, null);
		g2d.dispose();
		// 合成最终图像
		BufferedImage combined = new BufferedImage(
				image.getWidth(),
				image.getHeight(),
				BufferedImage.TYPE_INT_ARGB);

		Graphics2D g = combined.createGraphics();
		g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
		g.drawImage(image, 0, 0, null);

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

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

		return combined;
	}

}
