package com.hotwj.platform.reportStatistics.pdf;

import com.hotwj.platform.common.utils.PdfWatermarkUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * 信息化印章 PDF 后处理器
 * 从 classpath 加载印章图片，并在 PDF 每页右上角追加绘制。
 */
@Slf4j
@Component
public class OfficialInformationSealPostProcessor implements PdfPostProcessor {

    private static final String SEAL_RESOURCE = "images/officialInformationSeal.png";
    private static volatile byte[] cachedSealBytes;

    @Override
    public byte[] process(byte[] pdfBytes) {
        byte[] sealBytes = getSealBytes();
        if (sealBytes == null || sealBytes.length == 0) {
            return pdfBytes;
        }
        return PdfWatermarkUtil.addImageTopRight(pdfBytes, sealBytes);
    }

    private byte[] getSealBytes() {
        if (cachedSealBytes != null) {
            return cachedSealBytes;
        }
        synchronized (OfficialInformationSealPostProcessor.class) {
            if (cachedSealBytes != null) {
                return cachedSealBytes;
            }
            try {
                ClassPathResource resource = new ClassPathResource(SEAL_RESOURCE);
                if (!resource.exists()) {
                    return null;
                }
                try (InputStream is = resource.getInputStream()) {
                    cachedSealBytes = is.readAllBytes();
                }
                return cachedSealBytes;
            } catch (Exception e) {
                log.error("Failed to load official information seal image", e);
                return null;
            }
        }
    }
}
