package com.yingpaipay.common.file.util;

import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFontDescriptor;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class PdfUtils {

    public static File watermark(File file, String remark) throws IOException {
        PDDocument document = PDDocument.load(file);
        PDType1Font font = PDType1Font.HELVETICA_BOLD;
        float fontSize = 10f;

        for (PDPage page : document.getPages()) {
//            PDRectangle pageSize = page.getMediaBox();
            float x = 50;
            float y = 30;

            PDFontDescriptor fontDesc = font.getFontDescriptor();
            float textWidth = font.getStringWidth(remark) / 1000 * fontSize;
            float textHeight = fontDesc != null ? fontDesc.getAscent() / 1000 * fontSize : fontSize;
            float descent = fontDesc != null ? fontDesc.getDescent() / 1000 * fontSize : 0;

            float padding = 4f;
            float rectX = x - padding;
            float rectY = y + descent - padding;
            float rectWidth = textWidth + 2 * padding;
            float rectHeight = textHeight - descent + 2 * padding;

            try (PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true)) {
                Color color = new Color(255, 99, 99);
                cs.setStrokingColor(color);
                cs.setLineWidth(1f);
                cs.addRect(rectX, rectY, rectWidth, rectHeight);
                cs.stroke();

                cs.beginText();
                cs.setFont(font, fontSize);
                cs.setNonStrokingColor(color);
                cs.newLineAtOffset(x, y);
                cs.showText(remark);
                cs.endText();
            }
        }

        File outputFile = File.createTempFile("watermarked_", ".pdf");
        document.save(outputFile);
        document.close();
        return outputFile;
    }

    public static File merge(List<File> files, String fileName) throws IOException {
        if (files == null || files.isEmpty()) {
            throw new IllegalArgumentException("Base64 PDF list is empty or null");
        }

        for (File file : files) {
            if (file == null || !file.exists() || !file.isFile()) {
                throw new IllegalArgumentException("Invalid PDF file: " + (file != null ? file.getAbsolutePath() : "null"));
            }
            if (!file.canRead()) {
                throw new IllegalArgumentException("Cannot read PDF file: " + file.getAbsolutePath());
            }
        }

        Path tempDir = Files.createTempDirectory("pdf_merge_");
        Path outputPath = tempDir.resolve(fileName + ".pdf");

        File outputFile = outputPath.toFile();

        PDFMergerUtility merger = new PDFMergerUtility();
        merger.setDestinationFileName(outputFile.getAbsolutePath());

        for (File file : files) {
            merger.addSource(file);
        }

        merger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());

        return outputFile;

    }

}
