package com.emr.util;

import com.emr.entity.emrPdfWaterSet.EmrPdfWaterSet;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.pdf.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
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 img2PdfUtil {
    final private  static float A4_weight = 595-60; //标准A4的宽
    final private static float A4_height = 842-60; //标准A4的高
    static Logger  logger = LoggerFactory.getLogger(img2PdfUtil.class);
    public static void imageToPdf(HttpServletResponse response, List<String> filePaths, String pdfName, EmrPdfWaterSet pdfWaterSet) throws Exception{
        Document document = new Document(PageSize.A4,30,30,30,30); //创建文档容器
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //是否启用水印
        Short effective = pdfWaterSet.getEffective();
        Short isImg = pdfWaterSet.getIsImg();
        if(effective == 1 || isImg == 1){
            PdfWriter.getInstance(document,bos); //创建编写器（PDF类型）
        }else{
            PdfWriter.getInstance(document,response.getOutputStream()); //创建编写器（PDF类型）
        }
        pdfName = java.net.URLEncoder.encode(pdfName, "UTF-8");
        response.reset();
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/pdf"); // word格式
        response.setHeader("Content-Disposition", "attachment; filename=" + pdfName +".pdf");
        //图片合成pdf
        imgToPdf(document,filePaths);
        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());
        }
    }

    //脐血库下载批量
    public static void imageToPdfToBuffOut(ByteArrayOutputStream bos, List<String> filePaths, String pdfName,EmrPdfWaterSet pdfWaterSet) throws Exception{
        // 实例化图牿
        Document document = new Document(PageSize.A4,30,30,30,30); //创建文档容器
        //是否启用水印
        PdfWriter.getInstance(document,bos);
        //图片合成pdf
        imgToPdf(document,filePaths);
        //是否启用水印
        Short effective = pdfWaterSet.getDownloadEffective();
        Short isImg = pdfWaterSet.getDownloadIsImg();
        if(effective == 1 || isImg == 1) {
            addWaterMark(bos, null, pdfWaterSet.getUpOrUnder(), pdfWaterSet.getTransparent(),
                    pdfWaterSet.getText(), pdfWaterSet.getTextX(), pdfWaterSet.getTextY(),
                    pdfWaterSet.getTextColor(), pdfWaterSet.getTextSize(), pdfWaterSet.getTextRotation(),
                    effective,isImg,pdfWaterSet.getImgFile(), pdfWaterSet.getImgWidth(),
                    pdfWaterSet.getImgHeight(), pdfWaterSet.getImgX(), pdfWaterSet.getImgY());
        }
    }

    //图片合成pdf
    private static void imgToPdf(Document document,List<String> filePaths) throws Exception{
        document.open(); //打开容器
        float percent=100;
        float w,h;
        for(int i=0;i<filePaths.size();i++){
            File file = new File(filePaths.get(i));
            if(file.isFile()) {
                Image img = Image.getInstance(filePaths.get(i));
                /*处理图片缩放比例*/
                w = img.getWidth();
                h = img.getHeight();
                if ((w > A4_weight) && (h < A4_height))
                    percent = (A4_weight * 100) / w;
                else if ((w < A4_weight) && (h > A4_height))
                    percent = (A4_height * 100) / h;
                else if ((w > A4_weight) && (h > A4_height)) {

                    percent = (A4_weight * 100) / w;
                    h = (h * percent) / 100;
                    if (h > A4_height)
                        percent = (A4_height * 100) / h;
                }
                img.setAlignment(com.lowagie.text.Image.ALIGN_CENTER);
                img.scalePercent(percent);
                document.add(img);
            }
        }
        document.close(); //关闭容器
    }
    /**
     * 添加图片和文字水印
     *
     * @param
     * @param response 输出前台
     * @param upOrUnder 加水印后存放地址
     * @param transparent 加水印透明度
     * @param text 加水印的文本内容
     * @param textX 文字横坐标
     * @param textY 文字纵坐标
     * @param textColor 文字颜色
     * @param textSize 文字字号
     * @param textRotation 文字旋转角度
     * @param imgFile 加水印图片文件
     * @param imgWidth 图片宽
     * @param imgHeight 图片高
     * @param imgX 图片横坐标
     * @param imgY 图片纵坐标
     * @throws IOException
     * @throws DocumentException
     */
    public static void addWaterMark(ByteArrayOutputStream bos,HttpServletResponse response,int upOrUnder,float transparent, String text, int textX, int textY,
                                    String textColor,int textSize,int textRotation,Short effective,Short isImg,
                                    String imgFile, int imgWidth, int imgHeight,int imgX,int imgY) throws IOException, DocumentException {

        //ByteArrayInputStream fileToUpload = new ByteArrayInputStream(bos.toByteArray());
        // 待加水印的文件
        //String fileStr = "e:\\11111.pdf";
        PdfReader reader = new PdfReader(bos.toByteArray());
        // 加完水印的文件
        PdfStamper stamper = null;
        if(null != response){
            stamper = new PdfStamper(reader,response.getOutputStream());
        }else{
            stamper = new PdfStamper(reader,bos);
        }
        // 设置字体
        BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
        // PDF总页数
        int total = reader.getNumberOfPages() + 1;
        // 循环对每页插入水印
        PdfContentByte content;
        PdfGState gs = new PdfGState();
        for (int i = 1; i < total; i++) {
            //upOrUnder = 1为在文本之上
            if(upOrUnder == 1){
                // 水印在之前文本之上
                content = stamper.getOverContent(i);
            }else{
                // 水印在文本之下
                content = stamper.getUnderContent(i);
            }
            //设置填充字体不透明度为0.2f
            gs.setFillOpacity(transparent);
            content.setGState(gs);
            // 图片水印
            if (null != isImg && isImg == 1) {
                HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
                String tomcatPath = request.getSession().getServletContext().getRealPath("/");
                String imgStr = tomcatPath + "static\\pdfWaterSet\\upload\\" + imgFile;
                com.lowagie.text.Image image = null;
                if (imgStr != null && new File(imgStr).isFile()) {
                    image = com.lowagie.text.Image.getInstance(imgStr);
                    //位置
                    image.setAbsolutePosition(imgX, imgY);
                    // 设置图片的显示大小
                    image.scaleToFit(imgWidth, imgHeight);
                    content.addImage(image);
                }
            }
            // 文字水印
            if (effective == 1 && StringUtils.isNotBlank(text)) {
                content.beginText();
                //16进制颜色转color
                Color color = toColorFromString(textColor);
                content.setColorFill(color);
                // 设置字体及字号
                content.setFontAndSize(font, textSize);
                // 设置起始位置
                content.setTextMatrix(textX, textY);
                // 中间水印
                content.showTextAligned(Element.ALIGN_LEFT, text, textX, textY, textRotation);
                // 底部水印
                /*for (int k = 0; k < text.length(); k++) {
                    // 距离底边的距离
                    content.setTextRise(10);
                    // 将char转成字符串
                    content.showText(String.valueOf(text.charAt(k)));
                }*/
                content.endText();
            }
        }
        stamper.close();
    }
    /**
     * Color对象转换成字符串
     * @param color Color对象
     * @return 16进制颜色字符串
     * */
    private static String toHexFromColor(Color color){
        String r,g,b;
        StringBuilder su = new StringBuilder();
        r = Integer.toHexString(color.getRed());
        g = Integer.toHexString(color.getGreen());
        b = Integer.toHexString(color.getBlue());
        r = r.length() == 1 ? "0" + r : r;
        g = g.length() ==1 ? "0" +g : g;
        b = b.length() == 1 ? "0" + b : b;
        r = r.toUpperCase();
        g = g.toUpperCase();
        b = b.toUpperCase();
        su.append("0xFF");
        su.append(r);
        su.append(g);
        su.append(b);
        //0xFF0000FF
        return su.toString();
    }
    /**
     * 字符串转换成Color对象
     * @param colorStr 16进制颜色字符串
     * @return Color对象
     * */
    public static Color toColorFromString(String colorStr){
        int r= Integer.valueOf( colorStr.substring( 1, 3 ), 16 );
        int g= Integer.valueOf( colorStr.substring( 3, 5 ), 16 );
        int b= Integer.valueOf( colorStr.substring( 5, 7 ), 16 );
        Color color =  new Color(r,g,b) ;
        //java.awt.Color[r=0,g=0,b=255]
        return color;
    }

}
