package cn.reghao.tnb.file.app.service;

import cn.reghao.tnb.file.app.util.pdf.ContentStyle;
import cn.reghao.tnb.file.app.util.pdf.DateTimeUtil;
import cn.reghao.tnb.file.app.util.pdf.PDFUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * @author reghao
 * @date 2024-12-01 11:59:49
 */
@Slf4j
@Service
public class ReportService {
    private final String baseDir;
    private final PDFUtil pdfUtil;

    public ReportService() {
        this.baseDir = System.getProperty("java.io.tmpdir");
        this.pdfUtil = new PDFUtil();
    }

    public void createCertificate() {
        //  获取证书背景图片路径
        String backgroundImage = Objects.requireNonNull(PDFUtil.class.getClassLoader().getResource("static/bg.png")).getPath();
        //  获取发放证书的项目Logo
        String logo = Objects.requireNonNull(PDFUtil.class.getClassLoader().getResource("static/logo.png")).getPath();
        //  生成的pdf的文件位置
        String reportPath = String.format("%s/%s.pdf", baseDir, System.currentTimeMillis());

        //  准备证书所需要的数据
        String trueName = "周子轩";
        Date examTime = new Date();
        String userInfo = trueName + "同学：";
        String examName = "2024期末考试";

        //  证书字体样式
        ContentStyle style1 = new ContentStyle();
        style1.setFontSize(15);
        ContentStyle style2 = new ContentStyle();
        style2.setFontSize(10);
        //  生成证书内容
        String content = "您于" + DateTimeUtil.DateToString(examTime) + "在" + examName + "测评中取得优异成绩!";
        //  创建证书
        try {
            String content1 = "特发此证,以资鼓励!";
            pdfUtil.openDocument(reportPath)
                    .addImage(backgroundImage, 0, 400)
                    //.addLogo(logo, 270, 480)
                    .addContent(userInfo, 85, 630, style1)
                    .addContent(content1, 125, 495, style2)
                    .addLogo(logo, 360, 495);

            //  结束截取字符串的索引
            int end;
            //  证书内容分行,防止超出证书边缘
            for (int i = 0, y = 590; i < content.length(); y -= 30) {
                end = Math.min(i + 30, content.length());
                pdfUtil.addContent(content.substring(i, end), 125, y, style1);
                i = end;
            }
        } catch (Exception e) {
            log.error("生成证书错误: " + e);
        }
        //  关闭创建pdf的工具
        pdfUtil.close();
        log.info("pdf file path -> {}", reportPath);
    }
}
