package com.jwipc.finance.logic.impl;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.jwipc.api.dto.ESignFileResposeDTO;
import com.jwipc.api.esign.SignFileCreateCallBackLogic;
import com.jwipc.constant.SignProcessType;
import com.jwipc.finance.logic.CompanyAccountStatementLogic;
import com.jwipc.finance.service.IAccountStatementService;
import com.jwipc.prop.SysProp;
import com.jwipc.sys.client.ESignClient;
import com.jwipc.sys.client.FileClient;
import com.jwipc.sys.logic.FileLogic;
import com.jwipc.util.PDFUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author shenyang.ou
 * @date 2024/5/10 10:00
 * @desc
 */
@Service("CompanyAccountStatementSignFileCreateCallBack")
@RequiredArgsConstructor
public class CompanyAccountStatementSignFileCreateCallBack implements SignFileCreateCallBackLogic {

    private final IAccountStatementService accountStatementService;
    private final CompanyAccountStatementLogic companyAccountStatementLogic;
    private final Configuration freemarkerConfig;
    private final FileClient fileClient;
    private final FileLogic fileLogic;
    private final ESignClient eSignClient;
    private final SysProp sysProp;

    /**
     * sign 回调接口
     *
     * @param businessId
     * @return
     */
    @Override
    public List<ESignFileResposeDTO> processor(Long businessId,Integer templateType) {
        Map<String,Object> map = companyAccountStatementLogic.printStatement(businessId);
        map.put("ctx",sysProp.getHostUrl());
        String configValue = ResourceUtil.readUtf8Str("view/pc/finance/companyAccountStatement/statement_print_pdf.ftl");
        Template template = null;
        try {
            //生成html字符串
            template = new Template("emailTemplate", configValue, freemarkerConfig);
            String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            //创建pdf空文件
            File file = fileClient.createFile("生成跨公司销售对账单-"+ IdWorker.getId() +".pdf");
            //生成pdf
//            HtmlToPdf.create().object(HtmlToPdfObject.forHtml(html).defaultEncoding("utf8")).convert(file.getPath());
            PDFUtil.generatePdfFromHtml(html, file.getPath(), true,true);

            File file1 = new File(StrUtil.concat(false, fileLogic.genDatePath().getKey(), File.separator, file.getName()));
            InputStream inputStream = new FileInputStream(file1);
            PdfReader reader = new PdfReader(inputStream);
            PdfWriter writer = new PdfWriter(file1);
            int numberOfPages = 0;
            try (PdfDocument pdfDoc = new PdfDocument(reader, writer)) {
                numberOfPages = pdfDoc.getNumberOfPages();
                inputStream.close();
            }

            //上传到e签宝
            ESignFileResposeDTO eSignFileResposeDTO = fileClient.uploadESignFile(file);
            String fileKey = eSignClient.sendFileClient(eSignFileResposeDTO,fileClient.file2MultipartFile(file));
            //插入fileKey
            eSignFileResposeDTO.setFileKey(fileKey);
            //返回文件总页数到前端，校验骑缝章的问题。 邓京术 2025-07-09
            eSignFileResposeDTO.setNumberOfPages(numberOfPages);
            List<ESignFileResposeDTO> eSignFileResposeDTOS = new ArrayList<>();
            eSignFileResposeDTOS.add(eSignFileResposeDTO);
            //返回list
            return eSignFileResposeDTOS;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 当前服务是属于哪个流程
     *
     * @return
     */
    @Override
    public SignProcessType getProcessType() {
        return SignProcessType.COMPANY_ACCOUNT_STATEMENT;
    }
}
