package com.ruoyi.gysl.utils;



import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PdfUtils {


    // 定义全局的字体静态变量
    private static Font titlefont;
    private static Font headfont;
    private static Font keyfont;
    private static Font textfont;
    // 最大宽度
    private static int maxWidth = 520;

    // 静态代码块
    static {
        try {
            // 不同字体（这里定义为同一种字体：包含不同字号、不同style）
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            titlefont = new Font(bfChinese, 16, Font.BOLD);
            headfont = new Font(bfChinese, 14, Font.BOLD);
            keyfont = new Font(bfChinese, 10, Font.BOLD);
            textfont = new Font(bfChinese, 10, Font.NORMAL);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * html转换成pdf文件
     *
     * @param htmlContent
     * @throws Exception
     */
    public MultipartFile html2Pdf(String htmlArticleTitle, String htmlContent) throws Exception {
        htmlContent = this.content2Html(htmlContent);

        String path = System.getProperty("user.dir");

        //根据日期建文件夹
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String format = formatter.format(date);
        String[] split = format.split("-");
        File dir = new File(path + "/temporary");
        if (!dir.exists()) {
            dir.mkdir();
        }
        File dir2 = new File(path + "/temporary" + "/" + split[0]);
        if (!dir2.exists()) {
            dir2.mkdir();
        }
        File dir3 = new File(path + "/temporary" + "/" + split[0] + "/" + split[1]);
        if (!dir3.exists()) {
            dir3.mkdir();
        }
        File dir4 = new File(path + "/temporary" + "/" + split[0] + "/" + split[1] + "/" + split[2]);
        if (!dir4.exists()) {
            dir4.mkdir();
        }
        File pdfFile = new File(dir4 + "/pdf" + "-" + System.currentTimeMillis() + ".pdf");
        //1 打开文件流
        Document document = new Document();
        FileOutputStream fos = new FileOutputStream(pdfFile);
        System.out.println(pdfFile);
        InputStream is = new ByteArrayInputStream(htmlContent.getBytes(StandardCharsets.UTF_8));
        //InputStream cssIs = new ByteArrayInputStream(getCssFile());
        PdfWriter writer = null;
        try {
            writer = PdfWriter.getInstance(document, fos);
            //3. 设置字体
            XMLWorkerFontProvider fontProvider1 = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
            //fontProvider1.register(path+"\\simsun.ttc");//本地
            fontProvider1.register(path + "/simsun.ttc");//部署服务器

            //3 打开文档
            document.open();
            // 段落
            Paragraph paragraph = new Paragraph(htmlArticleTitle, titlefont);
            paragraph.setAlignment(1); //设置文字居中 0靠左   1，居中     2，靠右
            paragraph.setIndentationLeft(12); //设置左缩进
            paragraph.setIndentationRight(12); //设置右缩进
            paragraph.setFirstLineIndent(24); //设置首行缩进
            paragraph.setLeading(20f); //行间距
            paragraph.setSpacingBefore(5f); //设置段落上空白
            paragraph.setSpacingAfter(10f); //设置段落下空白
            document.add(paragraph);
            //4 html转为pdf
            //XMLWorkerHelper.getInstance().parseXHtml(writer, document, is, cssIs, Charset.forName("UTF-8"), fontProvider1);
            XMLWorkerHelper.getInstance().parseXHtml(writer, document, is, StandardCharsets.UTF_8, fontProvider1);

        } catch (DocumentException | IOException e) {
            throw new RuntimeException("转pdf失败罗~");
        } finally {
            if (null != writer) {
                writer.flush();
            }
            //5 关闭文档
            document.close();
            fos.close();
            //cssIs.close();
            is.close();
            writer.close();
            MultipartFile multipartFile = getMulipartFiles2(pdfFile + "");
            System.out.println("pdfFile = " + pdfFile);
            return multipartFile;
        }
    }

    public MultipartFile getMulipartFiles2(String filePath) throws IOException {
        File file = new File(filePath);
        FileInputStream fileInputStream = new FileInputStream(file);
        MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                "application/sql", fileInputStream);
        long size = multipartFile.getSize();
        return multipartFile;
    }


    /**
     * 获取html
     *
     * @return
     */
    public String content2Html(String htmlContent) {
        String COMPLETE_CONTENT = "<html><head></head><body style=\"font-family: SimSun;\">" + htmlContent + "</body></html>";
        String content = COMPLETE_CONTENT;
        content = content.replace("<br>", "<br/>");
        return content;
    }

    /**
     * 获取样式文件
     *
     * @return
     * @throws Exception
     */
    protected byte[] getCssFile() throws Exception {
        FileInputStream fileInputStream = new FileInputStream("D:\\editor.css");
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1204];
        int len = 0;
        while ((len = fileInputStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        fileInputStream.close();
        return outStream.toByteArray();
    }
}