package com.emr.util;


import com.emr.entity.emrPdfWaterSet.EmrPdfWaterSet;
import com.emr.vo.commomSearch.ScanPathVo;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.twelvemonkeys.imageio.metadata.tiff.IFD;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.emr.util.img2PdfUtil.addWaterMark;

/**
 * @ClassName imgToPdfUtil
 * @Description
 * @Author linjj
 * @Date 2024/4/8 9:13
 * @Version 1.0
 */
public class imgToPdfUtil {


    public static void imageToPdf(HttpServletResponse response, List<ScanPathVo> scanPathVos, String pdfName, EmrPdfWaterSet pdfWaterSet, EmrPdfWaterSet pdfWaterSet1) {
        Document document = new Document(PageSize.A4, 0, 0, 0, 0); //创建文档容器
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PdfWriter writer;
        //是否启用水印
        Short effective = pdfWaterSet.getEffective();
        Short isImg = pdfWaterSet.getIsImg();
        try {
            if (effective == 1 || isImg == 1) {
                writer = PdfWriter.getInstance(document, bos);//创建编写器（PDF类型）
            } else {
                writer = PdfWriter.getInstance(document, response.getOutputStream());//创建编写器（PDF类型）
            }
            pdfName = java.net.URLEncoder.encode(pdfName, "UTF-8");
            response.reset();
            response.setCharacterEncoding("utf-8");
            response.setContentType("x-www-form-urlencoded"); // word格式
            response.setHeader("Content-Disposition", "attachment; filename=" + pdfName + ".pdf");
            imgToPdf(document, writer, scanPathVos);
            if (effective == 1 || isImg == 1) {
                addWaterMark(bos, response, pdfWaterSet.getUpOrUnder(), pdfWaterSet.getTransparent(), pdfWaterSet.getText(), pdfWaterSet.getTextX(), pdfWaterSet.getTextY(), pdfWaterSet.getTextColor(), pdfWaterSet.getTextSize(), pdfWaterSet.getTextRotation(), pdfWaterSet.getEffective(), pdfWaterSet.getIsImg(), pdfWaterSet.getImgFile(), pdfWaterSet.getImgWidth(), pdfWaterSet.getImgHeight(), pdfWaterSet.getImgX(), pdfWaterSet.getImgY(), pdfWaterSet1.getText());
            }
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        } finally {
            try {
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            document.close();
        }
    }


    //图片合成pdf增加目录
    public static void imgToPdf(Document document, PdfWriter writer, List<ScanPathVo> scanPathVos) throws Exception {
        //上一个目录名称
        String lastOutline = null;
        //是否增加标签
        boolean outFlag = true;
        //标签顺序
        Integer outNum = 1;
        // 添加目录
        document.open(); //打开容器
        PdfContentByte cb = writer.getDirectContent();
        cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12);
        cb.beginText();
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "目录", 300, 780, 0);
        cb.endText();
        // 创建目录
        PdfOutline root = cb.getRootOutline();
        // 添加图片到PDF
        for (int i = 0; i < scanPathVos.size(); i++) {
            String assortName = scanPathVos.get(i).getAssortName();
            if(!ObjectUtils.isEmpty(assortName)){
                if (StringUtils.isNotBlank(lastOutline) && lastOutline.equals(assortName)) {
                    outFlag = false;
                }
                if (StringUtils.isBlank(lastOutline)) {
                    lastOutline = assortName;
                    outFlag=true;
                }
                if (!lastOutline.equals(assortName)){
                    lastOutline = assortName;
                    outFlag=true;
                }
            }
            String imagePath = scanPathVos.get(i).getFileRealPath();
            Image image = Image.getInstance(imagePath);

            image.setAlignment(Image.MIDDLE);
            image.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight());
            // 等比例缩放图片以填满PDF页面

            image.scaleAbsolute(document.getPageSize());
            // 创建新页面并添加图片
            //document.newPage();
            document.add(image);
            if (outFlag) {
                //目录跳转页面内容设置。
                PdfAction action = PdfAction.gotoLocalPage(i+1, new PdfDestination(PdfDestination.FIT), writer);
                //标题目录
                String title = outNum + "." + scanPathVos.get(i).getAssortName();
                new PdfOutline(root, action, title, false);
                outNum++;
            }
        }
        document.close(); //关闭容器
    }
}
