package com.pusong.common.doc.util;


import java.io.IOException;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.pusong.common.core.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 设置页面附加属性
 *
 */
public class PDFBuilder extends PdfPageEventHelper {

    private static final Logger log = LoggerFactory.getLogger(PDFBuilder.class);
    /**
     * 页眉
     */
    public String header ;
    /**
     * 是否签章
     */
    public Boolean isSign ;
    /**
     * 是否签章
     */
    public String imagepath ;
    // 利用基础字体生成的字体对象，一般用于生成中文文字
    public static Font fontDetail = null;
    // 基础字体对象
    private static BaseFont baseFont;
    // 生成下划线空白占位符
    private static String Blank;
    static {
        try {
            // 中文字体依赖itext得itext-asian包
            baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 212; i++) {
                sb.append("\u00a0");
            }
            Blank = sb.toString();
            fontDetail = new Font(baseFont,8);
        } catch (DocumentException e) {
            log.error("初始化字体失败", e);
        } catch (IOException e) {
            log.error("初始化字体失败", e);
        }
    }

    /**
     *
     * Creates a new instance of PdfReportM1HeaderFooter 无参构造方法.
     *
     */
    public PDFBuilder(Object header,Object isSign,String imagepath) {
        this.header = header == null?null:header.toString();
        this.isSign = isSign == null?null:(Boolean)isSign;
        this.imagepath = imagepath;
    }

    /**
     *
     * TODO 文档打开时创建模板
     *
     * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(com.itextpdf.text.pdf.PdfWriter,
     *      com.itextpdf.text.Document)
     */
    public void onOpenDocument(PdfWriter writer, Document document) {
    }

    @Override

    public void onStartPage(PdfWriter writer, Document document) {
        super.onStartPage(writer, document);

    }

    /**
     *
     * TODO 关闭每页的时候，写入页眉，写入'第几页共'这几个字。
     *
     * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter,
     *      com.itextpdf.text.Document)
     */
    public void onEndPage(PdfWriter writer, Document document) {
        //是否添加页眉
        if(StringUtils.isNotBlank(header)){
            this.addPage(writer, document);
        }
        //是否签章
        if(isSign){
            this.addSign(writer);
        }

    }

    //加分页
    public void addPage(PdfWriter writer, Document document) {
        //页眉没有数据的话直接return
        if(StringUtils.isBlank(header)){
            return;
        }
        //生成下划线，使用空格占位
        ColumnText.showTextAligned(writer.getDirectContent(),
                Element.ALIGN_LEFT, new Phrase(PDFBuilder.Blank, new Font(PDFBuilder.baseFont, Font.DEFAULTSIZE, Font.UNDERLINE)),
                document.left(-1), document.top()+10, 0);
        // 1.写入页眉
        ColumnText.showTextAligned(writer.getDirectContent(),
                Element.ALIGN_LEFT, new Phrase(header, fontDetail),
                document.right()/2+20, document.top()+10 , 0);
    }

    //加半章图片
    public void addSign(PdfWriter writer){
        String psth;
        if(writer.getPageNumber()%2 == 1){
            psth = imagepath+"/doc/image/leftZ.png";
        }else/* if (writer.getPageNumber() == 2)*/{
            psth = imagepath+"/doc/image/rightZ.png";
        }/*else{
            return;
        }*/
        // 加半章图片
        Image image;
        try {
            image = Image.getInstance(psth);
            image.scaleAbsolute(75,150);
            PdfContentByte content = writer.getDirectContentUnder();
            content.beginText();
            image.setAbsolutePosition(450+75,400);
            content.addImage(image);
            content.endText();
        } catch (IOException | DocumentException e) {
            log.error("加半章图片异常",e);
        }
    }

    /**
     *
     * TODO 关闭文档时，替换模板，完成整个页眉页脚组件
     *
     * @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(com.itextpdf.text.pdf.PdfWriter,
     *      com.itextpdf.text.Document)
     */
   /* public void onCloseDocument(PdfWriter writer, Document document) {
        // 7.最后一步了，就是关闭文档的时候，将模板替换成实际的 Y 值,至此，page x of y 制作完毕，完美兼容各种文档size。
        total.beginText();
        total.setFontAndSize(bf, presentFontSize);// 生成的模版的字体、颜色
        String foot2 = " " + (writer.getPageNumber()-1) + " 页";
        total.showText(foot2);// 模版显示的内容
        total.endText();
        total.closePath();
    }*/
}
