package com.emr.util;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @ProjectName:
 * @Description:
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/6/6 9:07
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/6/6 9:07
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class Jpg2PdfUtil {
    private static Logger log = Logger.getLogger("myMsg");
    /**
     * 利用itext打开pdf文档
     */
    private PdfReader check(String file) {
        if(StringUtils.isNotBlank(file)) {
            PdfReader pdfReader = null;
            try {
                pdfReader = new PdfReader(file);
                if (pdfReader.getNumberOfPages() != 0) {
                    return pdfReader;
                }
            } catch (Exception e) {
                SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String logStr = "'"+ file + "'"+"文件损坏或不存在";
                log.info(logStr);
                System.out.println(fmt.format(new Date()) + ":" + logStr);
            } finally {
                if (null != pdfReader) {
                    pdfReader.close();
                }
            }
        }
        return null;
    }

    private Jpg2PdfUtil(){};

    public static Jpg2PdfUtil getInstance(){
        return ContainerHolder.HOLDER.jpg2PdfUtil;
    }

    private enum ContainerHolder{
        HOLDER;
        private Jpg2PdfUtil jpg2PdfUtil;
        ContainerHolder(){
            jpg2PdfUtil = new Jpg2PdfUtil();
        }
    }

    public void mulFile2One(HttpServletResponse response, List<String> files, String waterMarkName) {
        List<PdfReader> list = new ArrayList<>();
        //遍历删除,除去损坏，文件不存在，抛异常就是空白页
        Iterator<String> iterator = files.iterator();
        while (iterator.hasNext()) {
            PdfReader check = check(iterator.next());
            if(null != check){
                list.add(check);
            }
        }
        if (!CollectionUtils.isEmpty(list)) {
            // pdf合并工具类
            Document document = null;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            PdfCopy copy = null;
            try {
                response.reset();
                document = new Document(list.get(0).getPageSize(1));
                copy = new PdfCopy(document, response.getOutputStream());
                document.open();
                for (PdfReader reader : list) {
                    bos.flush();
                    //判断是否加水印
                    if (StringUtils.isNotBlank(waterMarkName)) {
                        setWatermark(bos, reader, waterMarkName, null);
                        reader = new PdfReader(bos.toByteArray());
                    }
                    int n = reader.getNumberOfPages();
                    for (int j = 1; j <= n; j++) {
                        document.newPage();
                        PdfImportedPage page = null;
                        if (StringUtils.isNotBlank(waterMarkName)) {
                            page = copy.getImportedPage(reader, j);
                        } else {
                            page = copy.getImportedPage(reader, j);
                        }
                        copy.addPage(page);
                    }
                    reader.close();
                }
            } catch (Exception e) {
                //e.printStackTrace();
            } finally {
                if (null != copy) {
                    copy.close();
                }
                try {
                    bos.flush();
                    bos.close();
                } catch (Exception e) {
                    //e.printStackTrace();
                }
                if (null != document) {
                    document.close();
                }
            }
        }
    }


    //加水印
    private  void setWatermark(ByteArrayOutputStream bos, PdfReader reader, String waterMarkName, String imgPath) {
        PdfStamper stamper = null;
        try {
            stamper = new PdfStamper(reader, bos);
            //stamper.setEncryption(null, null, ~(PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING), PdfWriter.STANDARD_ENCRYPTION_128);
            int total = reader.getNumberOfPages() + 1;
            PdfContentByte content;
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            PdfGState gs = new PdfGState();
            for (int i = 1; i < total; i++) {
                content = stamper.getOverContent(i);// 在内容上方加水印
                //加文字水印
                if (StringUtils.isNotBlank(waterMarkName)) {
                    gs.setFillOpacity(0.3f);
                    gs.setStrokeOpacity(0.3f);
                    content.setGState(gs);
                    content.beginText();
                    content.setColorFill(Color.LIGHT_GRAY);
                    content.setFontAndSize(base, 50);
                    content.setTextMatrix(70, 200);
                    //v:距左 v1:距下 v2:
                    content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 600, 40);
                    content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 200, 40);
                    content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 800, 600, 40);
                    content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 800, 200, 40);
                    content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 1100, 40);
                    content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 1500, 40);
                    content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 800, 1100, 40);
                    content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 800, 1500, 40);
                    content.endText();
                }
                if (StringUtils.isNotBlank(imgPath)) {
                    Image image = Image.getInstance(imgPath);
                    image.setAbsolutePosition(200, 206); // set the first background
                    image.scaleToFit(200, 200);
                    content.addImage(image);
                }
                content.setColorFill(Color.BLACK);
                content.setFontAndSize(base, 8);
            }
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        } finally {
            try {
                assert stamper != null;
                stamper.close();
            } catch (DocumentException | IOException e) {
                e.printStackTrace();
            }
        }
    }
}