package com.emr.util;

import com.emr.entity.emrPdfWaterSet.EmrPdfWaterSet;
import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.*;
import com.lowagie.text.pdf.codec.TiffImage;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
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 {
    static Logger logger = LoggerFactory.getLogger(Jpg2PdfUtil.class);

    public static void imageToPdf(HttpServletResponse response, List<String> filePaths, String pdfName) throws Exception {
        // 实例化图牿
        Image image = null;
        pdfName = java.net.URLEncoder.encode(pdfName, "UTF-8");
        Document doc = new Document();
        response.reset();
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/pdf"); // word格式
        response.setHeader("Content-Disposition", "attachment; filename=" + pdfName + "(" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ").pdf");
        PdfWriter writer = PdfWriter.getInstance(doc, response.getOutputStream());
        // 开启文桿
        doc.open();
        try {
            for (String filePath : filePaths) {
                File file1 = new File(filePath);
                if (file1.exists()) {
                    if (file1.getName().endsWith(".tif") || file1.getName().endsWith(".tiff")) {
                        Object localObject1 = null;
                        Object localObject2 = null;
                        URL paramURL = Utilities.toURL(filePath);
                        try {
                            if (paramURL.getProtocol().equals("file")) {
                                localObject2 = paramURL.getFile();
                                localObject2 = Utilities
                                        .unEscapeURL((String) localObject2);
                                localObject1 = new RandomAccessFileOrArray(
                                        (String) localObject2);
                            } else {
                                localObject1 = new RandomAccessFileOrArray(paramURL);
                            }

                            int pageNums = TiffImage
                                    .getNumberOfPages((RandomAccessFileOrArray) localObject1);
                            if (pageNums > 0) {
                                for (int i = 1; i <= pageNums; i++) {
                                    localObject2 = TiffImage.getTiffImage(
                                            (RandomAccessFileOrArray) localObject1, i);
                                    image = (Image) localObject2;
                                }
                            }
                            if (localObject1 != null)
                                ((RandomAccessFileOrArray) localObject1).close();

                        } finally {
                            if (localObject1 != null) {
                                ((RandomAccessFileOrArray) localObject1).close();
                            }
                        }
                    } else if (file1.getName().endsWith(".png")
                            || file1.getName().endsWith(".jpg")
                            || file1.getName().endsWith(".gif")
                            || file1.getName().endsWith(".jpeg")
                    ) {
                        // 实例化图牿
                        image = Image.getInstance(filePath);
                    }
                    // 获得图片的高庿
                    float heigth = image.getHeight();
                    float width = image.getWidth();
                    // 合理压缩，h>w，按w压缩，否则按w压缩
                    int percent = getPercent(heigth, width);

                    // 设置图片居中显示
                    //image.setAlignment(Image.MIDDLE);
                    image.setAlignment(Image.ALIGN_CENTER);
                    //image.scaleAbsolute(500, 400);
                    // 按百分比显示图片的比便
                    if (width > 1024 || heigth > 786) {
                        image.scalePercent(percent + 5);
                    }
                    PdfContentByte canvas = writer.getDirectContent();
                    //pdf文档中中文字体的设置，注意一定要添加iTextAsian.jar包
                    BaseFont bfChinese = BaseFont.createFont("STSong-Light",
                            "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                    Font fontChinese = new Font(bfChinese, 50, Font.NORMAL, Color.blue);
                    Phrase phrase = new Phrase("老客户看黑科技好客户客户客户客户客户客户看黑科技", fontChinese);
                    ColumnText.showTextAligned(
                            canvas, Element.ALIGN_UNDEFINED, phrase, 200, 200, 50);
                    Image image1 = null;
                    image1 = Image.getInstance("D:\\出差准备文档\\pdf\\9d17f073c61adfaf79438401bc6ffb7.jpg");
                    //位置
                    image1.setAbsolutePosition(200, 200);
                    // 设置图片的显示大小
                    image1.scaleToFit(200, 200);
                    canvas.addImage(image1);
                    doc.add(image);
                    phrase.clear();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (doc.isOpen()) {
                doc.close();
            }
            writer.flush();
            writer.close();
        }
    }

    public static boolean check(String file) {
        PdfReader pdfReader = null;
        try {
            File f = new File(file);
            if (f.isFile()) {
                pdfReader = new PdfReader(file);
                if (pdfReader.getNumberOfPages() != 0) {
                    return true;
                }
            }
        } catch (Exception e) {
        } finally {
            if (null != pdfReader) {
                pdfReader.close();
            }
        }
        return false;
    }


    public static void mulFile2One(HttpServletResponse response, List<String> filePaths, String waterMarkName) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //遍历删除,除去损坏，文件不存在，抛异常就是空白页
        Iterator<String> iterator = filePaths.iterator();
        while (iterator.hasNext()) {
            String fileStr = iterator.next();
            File file = new File(fileStr);
            if (file.isFile()) {
                boolean flag = check(fileStr);
                if (!flag) {
                    iterator.remove();
                    System.out.println(fmt.format(new Date()) + ":" + file + "文件损坏");
                }
            } else {
                iterator.remove();
                System.out.println(fmt.format(new Date()) + ":" + file + "文件不存在");
            }
        }
        if (!filePaths.isEmpty()) {
            // pdf合并工具类
            Document document = null;
            PdfCopy copy = null;
            try {
                document = new Document(new PdfReader(filePaths.get(0)).getPageSize(1));
                copy = new PdfCopy(document, response.getOutputStream());
                document.open();
                for (String file : filePaths) {
                    PdfReader reader = new PdfReader(file);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    PdfReader pdfReader = null;
                    //判断是否加水印
                    if (StringUtils.isNotBlank(waterMarkName)) {
                        setWatermark(bos, reader, waterMarkName, null);
                        pdfReader = 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(pdfReader, j);
                        } else {
                            page = copy.getImportedPage(reader, j);
                        }
                        copy.addPage(page);
                    }
                    if (null != pdfReader) {
                        pdfReader.close();
                    }
                    reader.close();
                    try {
                        bos.flush();
                        bos.close();
                    } catch (Exception e) {
                        //e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                //e.printStackTrace();
            } finally {
                if (null != document) {
                    document.close();
                }
            }

        }
    }

    public static void setWatermark(ByteArrayOutputStream bos, PdfReader reader, String waterMarkName, String imgPath) {
        PdfStamper stamper = null;
        try {
            stamper = new PdfStamper(reader, bos);
            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);
                    String[] waterMarks = waterMarkName.split("&");
                    //v:距左 v1:距下 v2:
                    content.showTextAligned(Element.ALIGN_CENTER, waterMarks[0], 250, 600, 40);
                    /*content.showTextAligned(Element.ALIGN_CENTER, waterMarks[0], 250, 200, 40);
                    content.showTextAligned(Element.ALIGN_CENTER, waterMarks[0], 800, 600, 40);
                    content.showTextAligned(Element.ALIGN_CENTER, waterMarks[0], 800, 200, 40);
                    content.showTextAligned(Element.ALIGN_CENTER, waterMarks[0], 250, 1100, 40);
                    content.showTextAligned(Element.ALIGN_CENTER, waterMarks[0], 250, 1500, 40);
                    content.showTextAligned(Element.ALIGN_CENTER, waterMarks[0], 800, 1100, 40);
                    content.showTextAligned(Element.ALIGN_CENTER, waterMarks[0], 800, 1500, 40);*/
                    if (waterMarks.length > 1) {
                        //v:距左 v1:距下 v2:
                        content.showTextAligned(Element.ALIGN_CENTER, waterMarks[1], 310, 400, 40);
                        /* content.showTextAligned(Element.ALIGN_CENTER, waterMarks[1], 310, 150, 40);*/
                        /*content.showTextAligned(Element.ALIGN_CENTER, waterMarks[1], 860, 550, 40);
                        content.showTextAligned(Element.ALIGN_CENTER, waterMarks[1], 860, 150, 40);*/
                       /* content.showTextAligned(Element.ALIGN_CENTER, waterMarks[1], 300, 900, 40);
                        content.showTextAligned(Element.ALIGN_CENTER, waterMarks[1], 300, 1300, 40);
                        content.showTextAligned(Element.ALIGN_CENTER, waterMarks[1], 800, 900, 40);
                        content.showTextAligned(Element.ALIGN_CENTER, waterMarks[1], 800, 1300, 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.red);
                content.setFontAndSize(base, 8);
            }
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        } finally {
            try {
                assert stamper != null;
                stamper.close();
            } catch (DocumentException | IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void mulFile2One3(HttpServletResponse response, List<String> filePaths, String filename, EmrPdfWaterSet emrPdfWaterSet) {
        String waterMarkName = "";
        SimpleDateFormat  fmt= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //遍历删除,除去损坏，文件不存在，抛异常就是空白页
        Iterator<String> iterator = filePaths.iterator();
        while (iterator.hasNext()) {
            String fileStr = iterator.next();
            File file = new File(fileStr);
            if (file.isFile()) {
                boolean flag = check(fileStr);
                if (!flag) {
                    iterator.remove();
                    System.out.println(fmt.format(new Date()) + ":" + file + "文件损坏");
                }
            } else {
                iterator.remove();
                System.out.println(fmt.format(new Date()) + ":" + file + "文件不存在");
            }
        }
        if (!filePaths.isEmpty()) {
            // pdf合并工具类
            Document document = null;
            PdfCopy copy = null;
            try {
                filename = java.net.URLEncoder.encode(filename, "UTF-8");
                response.reset();
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/pdf");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename + ".pdf");
                document = new Document(new PdfReader(filePaths.get(0)).getPageSize(1));
                copy = new PdfCopy(document, response.getOutputStream());
                document.open();
                for (String file : filePaths) {
                    PdfReader reader = new PdfReader(file);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    PdfReader pdfReader = null;
                    //判断是否加水印
                    if (emrPdfWaterSet.getDownloadEffective() == 1) {
                        setWatermark(bos, reader, emrPdfWaterSet.getText(), null);
                        pdfReader = new PdfReader(bos.toByteArray());
                    }
                    int n = reader.getNumberOfPages();
                    for (int j = 1; j <= n; j++) {
                        document.newPage();
                        PdfImportedPage page = null;
                        if (emrPdfWaterSet.getDownloadEffective() == 1) {
                            page = copy.getImportedPage(pdfReader, j);
                        } else {
                            page = copy.getImportedPage(reader, j);
                        }
                        copy.addPage(page);
                    }
                    if (null != pdfReader) {
                        pdfReader.close();
                    }
                    reader.close();
                    try {
                        bos.flush();
                        bos.close();
                    } catch (Exception e) {
                        //e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                //e.printStackTrace();
            } finally {
                if (null != document) {
                    document.close();
                }
            }

        }
    }


    public static void mulFile2One4(HttpServletResponse response, List<String> filePath, String filename) {
        // pdf合并工具类
        Document document = null;
        PdfCopy copy = null;
        try {
            filename = java.net.URLEncoder.encode(filename, "UTF-8");
            response.reset();
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=" + filename + ".pdf");
            document = new Document(new PdfReader(filePath.get(0)).getPageSize(1));
            copy = new PdfCopy(document, response.getOutputStream());
            document.open();
            for (String file : filePath) {
                PdfReader reader = new PdfReader(file);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                PdfReader pdfReader = null;
                //判断是否加水印
                int n = reader.getNumberOfPages();
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = null;
                    page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }
                if (null != pdfReader) {
                    pdfReader.close();
                }
                reader.close();
                try {
                    bos.flush();
                    bos.close();
                } catch (Exception e) {
                    //e.printStackTrace();
                }
            }
        } catch (Exception e) {
            //e.printStackTrace();
        } finally {
            if (null != document) {
                document.close();
            }
        }


    }

    public static void mulFile2One2(HttpServletResponse response, List<String> filePaths, String filename, EmrPdfWaterSet emrPdfWaterSet) {
        //是否启用水印
        Short effective = emrPdfWaterSet.getEffective();
        Short isImg = emrPdfWaterSet.getIsImg();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //遍历删除,除去损坏，文件不存在，抛异常就是空白页
        Iterator<String> iterator = filePaths.iterator();
        while (iterator.hasNext()) {
            String fileStr = iterator.next();
            File file = new File(fileStr);
            if (file.isFile()) {
                boolean flag = check(fileStr);
                if (!flag) {
                    iterator.remove();
                    System.out.println(fmt.format(new Date()) + ":" + file + "文件损坏");
                }
            } else {
                iterator.remove();
                System.out.println(fmt.format(new Date()) + ":" + file + "文件不存在");
            }
        }
        if (!filePaths.isEmpty()) {
            // pdf合并工具类
            Document document = null;
            PdfCopy copy = null;
            try {
                response.reset();
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/pdf");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename + ".pdf");
                document = new Document(new PdfReader(filePaths.get(0)).getPageSize(1));
                copy = new PdfCopy(document, response.getOutputStream());
                document.open();
                for (String file : filePaths) {
                    PdfReader reader = new PdfReader(file);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    PdfReader pdfReader = null;
                    //判断是否加水印
                    if (effective == 1 || isImg == 1) {
                        setWatermark(bos, reader, emrPdfWaterSet.getText(), null);
                        pdfReader = new PdfReader(bos.toByteArray());
                    }
                    int n = reader.getNumberOfPages();
                    for (int j = 1; j <= n; j++) {
                        document.newPage();
                        PdfImportedPage page = null;
                        if (effective == 1 || isImg == 1) {
                            page = copy.getImportedPage(pdfReader, j);
                        } else {
                            page = copy.getImportedPage(reader, j);
                        }
                        copy.addPage(page);
                    }
                    if (null != pdfReader) {
                        pdfReader.close();
                    }
                    reader.close();
                    try {
                        bos.flush();
                        bos.close();
                    } catch (Exception e) {
                        //e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                //e.printStackTrace();
            } finally {
                if (null != document) {
                    document.close();
                }
            }

        }
    }


    /**
     * 在不改变图片形状的同时，判断，如果h>w，则按h压缩，否则在w>h或w=h的情况下，按宽度压缩
     *
     * @param h
     * @param w
     * @return
     */
    public static int getPercent(float h, float w) {
        int p = 0;
        float p2 = 0.0f;
        if (h > w) {
            p2 = 210 / h * 279;
        } else {
            p2 = 210 / w * 279;
        }
        p = Math.round(p2);
        return p;
    }


    public static void mulFile2OneOne(HttpServletResponse response, String filePaths, String waterMarkName) {
        if (!filePaths.isEmpty()) {
            // pdf合并工具类
            Document document = null;
            PdfCopy copy = null;
            try {
                document = new Document(new PdfReader(filePaths).getPageSize(1));
                copy = new PdfCopy(document, response.getOutputStream());
                document.open();
                PdfReader reader = new PdfReader(filePaths);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                PdfReader pdfReader = null;
                //判断是否加水印
                if (StringUtils.isNotBlank(waterMarkName)) {
                    setWatermark(bos, reader, waterMarkName, null);
                    pdfReader = 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(pdfReader, j);
                    } else {
                        page = copy.getImportedPage(reader, j);
                    }
                    copy.addPage(page);
                }
                if (null != pdfReader) {
                    pdfReader.close();
                }
                reader.close();
                try {
                    bos.flush();
                    bos.close();
                } catch (Exception e) {
                    //e.printStackTrace();
                }
            } catch (Exception e) {
                //e.printStackTrace();
            } finally {
                if (null != document) {
                    document.close();
                }
            }

        }
    }
}
