package cn.iocoder.yudao.module.order.util;

import cn.hutool.core.io.FileUtil;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.BlockElement;
import com.itextpdf.layout.element.IElement;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.font.FontProvider;
import com.itextpdf.layout.property.VerticalAlignment;
import lombok.SneakyThrows;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.util.List;

public class AirHtmlToPdfUtil {
    public static final String leftLogoPath = "static\\image\\leftlogo.png";
    public static final String rightLogoPath = "static\\image\\rightlogo.png";
    public static final String bottomLogoPath = "static\\image\\bottomlogo.png";

    public static ImageData getLeftLogo() throws IOException {
        ClassPathResource resources = new ClassPathResource(leftLogoPath);
        return ImageDataFactory.create(resources.getURI().toString());
    }

    public static ImageData getRightLogo() throws IOException {
        ClassPathResource resources = new ClassPathResource(rightLogoPath);
        return ImageDataFactory.create(resources.getURI().toString());
    }

    public static ImageData getBottomLogo() throws IOException {
        ClassPathResource resources = new ClassPathResource(bottomLogoPath);
        return ImageDataFactory.create(resources.getURI().toString());
    }

    protected static class HeaderFooterHanlder implements IEventHandler {
        @SneakyThrows
        @Override
        public void handleEvent(Event event) {
            PdfDocumentEvent pdfDocumentEvent = (PdfDocumentEvent) event;
            PdfPage page = pdfDocumentEvent.getPage();
            PdfDocument pdfDocument = pdfDocumentEvent.getDocument();
            Document doc = new Document(pdfDocument);
            int pageNumber = pdfDocument.getPageNumber(page);//当前页码
            if (pageNumber != 1) {//表示不是首页
                this.addPageHeader(doc, pdfDocument);
                //this.addPageFooter(doc, pdfDocument);
            } else {
                //this.addPageFooter(doc, pdfDocument);
            }
        }

        /**
         * 页眉
         */
        private void addPageHeader(Document doc, PdfDocument pdfDocument) throws Exception {
            Rectangle pageSize = pdfDocument.getDefaultPageSize();
            float pdfWidth = pageSize.getWidth();
            float pdfHeight = pageSize.getHeight();

            Image leftLogo = new Image(AirHtmlToPdfUtil.getLeftLogo());
            leftLogo.scaleToFit(120, 180);
            Paragraph leftPageNameParagraph = new Paragraph();
            leftPageNameParagraph.setVerticalAlignment(VerticalAlignment.BOTTOM);
            leftPageNameParagraph.add(leftLogo);
            leftPageNameParagraph.setFixedPosition(0, pdfHeight - 100, 120);
            doc.add(leftPageNameParagraph);

            Image rightLogo = new Image(AirHtmlToPdfUtil.getRightLogo());
            leftLogo.scaleToFit(120, 180);
            Paragraph rightPageNameParagraph = new Paragraph();
            rightPageNameParagraph.setVerticalAlignment(VerticalAlignment.BOTTOM);
            rightPageNameParagraph.add(rightLogo);
            rightPageNameParagraph.setFixedPosition(pdfWidth - 120, pdfHeight - 120, 120);
            doc.add(rightPageNameParagraph);
        }

        /**
         * 页角
         */
        private void addPageFooter(Document doc, PdfDocument pdfDocument) throws Exception {
            Rectangle pageSize = pdfDocument.getDefaultPageSize();
            Image bottomLogo = new Image(AirHtmlToPdfUtil.getBottomLogo());
            bottomLogo.scaleToFit(120, 180);
            Paragraph pageNameParagraph = new Paragraph();
            pageNameParagraph.setVerticalAlignment(VerticalAlignment.BOTTOM);
            pageNameParagraph.add(bottomLogo);
            pageNameParagraph.setFixedPosition(pageSize.getWidth() - 120, 0, 120);
            doc.add(pageNameParagraph);
        }


    }

    public static Document convertHtmlToPdf(String html, String pdfPath) throws Exception {
        if (!FileUtil.exist(pdfPath)) {
            FileUtil.touch(pdfPath);
        }
        PdfWriter writer = new PdfWriter(pdfPath);
        PdfDocument pdf = new PdfDocument(writer);
        pdf.setDefaultPageSize(PageSize.A4);
        pdf.addEventHandler(PdfDocumentEvent.END_PAGE, new AirHtmlToPdfUtil.HeaderFooterHanlder());
        //转换器属性设置
        ConverterProperties props = new ConverterProperties();

        /*//解决中文无法显示
        FontProvider fontProvider = new DefaultFontProvider();
        //FontConstants.TIMES_ROMAN 可以做到英文一样,但是不支持中文
        FontProgram fontProgram = FontProgramFactory.createFont("static/image/msyh.ttf");
        fontProvider.addFont(fontProgram);*/


     /*   FontProvider fontProvider = new FontProvider();
        PdfFont sysFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
        fontProvider.addFont(sysFont.getFontProgram(), "UniGB-UCS2-H");*/



        FontProvider fontProvider = new FontProvider();
        //PdfFont sysFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
        //fontProvider.addFont(sysFont.getFontProgram(), "UniGB-UCS2-H");
        fontProvider.addStandardPdfFonts();
        fontProvider.addFont("static/image/simsun.ttf");
        props.setFontProvider(fontProvider);
        props.setCharset("utf-8");

        props.setFontProvider(fontProvider);
        List<IElement> elements = HtmlConverter.convertToElements(html, props);

        // 1-创建文本对象 Document
        Document document = new Document(pdf);

        // 4-往 Document 添加内容
        for (IElement e : elements) {
            if (document.getPdfDocument().getNumberOfPages() == 0) {
                document.setMargins(0, 10, 200, 10);
            } else {
                document.setMargins(130, 10, 200, 10);
            }

            BlockElement blockElement = (BlockElement) e;
            //blockElement.setMargins(1, 0, 1, 0);
           // blockElement.setFontSize(12);
            document.add(blockElement);
        }
        // 5-关闭 Document
        document.close();
        return document;
    }

    public static void convertToPdf(String html, String pdfPath) throws Exception {
        PdfWriter writer = new PdfWriter(pdfPath);
        PdfDocument pdf = new PdfDocument(writer);
        pdf.setDefaultPageSize(PageSize.A4);
        pdf.addEventHandler(PdfDocumentEvent.END_PAGE, new AirHtmlToPdfUtil.HeaderFooterHanlder());
        Document document = new Document(pdf);
        //转换器属性设置
        ConverterProperties props = new ConverterProperties();
        //字体
        props.setFontProvider(new FontProvider());
        props.getFontProvider().addFont("static/image/STHeiti.ttf");
        props.setCharset("utf-8");
        HtmlConverter.convertToDocument(html, pdf, props);
        document.close();
    }

    public static void main(String[] args) throws Exception {
        StringBuffer htmlSb = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\abc.html")), "utf-8"));
            while (br.ready()) {
                htmlSb.append(br.readLine());
            }
            br.close();
            // 删除临时文件
            //file.delete();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        convertHtmlToPdf(htmlSb.toString(), "C:\\Users\\Administrator\\Desktop\\test\\test.pdf");
    }


}
