CustomTemplateServiceImpl.java 18 KB
package com.lhcredit.project.business.customTemplate.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.data.DocxRenderData;
import com.deepoove.poi.data.Includes;
import com.lhcredit.common.utils.*;
import com.lhcredit.framework.web.domain.AjaxResult;
import com.lhcredit.project.business.reportMake.ReportMakeService;
import com.lhcredit.project.business.reportMake.reportTemp.ReportTemplateService;
import com.lhcredit.project.business.reportMake.reportTemp.WebTempConfig;
import com.lhcredit.project.business.templateDataSource.domain.TemplateDataSource;
import com.lhcredit.project.business.templateDataSource.service.ITemplateDataSourceService;
import com.lhcredit.project.business.templateDataSource.service.TemplateDataSourceServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lhcredit.project.business.customTemplate.mapper.CustomTemplateMapper;
import com.lhcredit.project.business.customTemplate.domain.CustomTemplate;
import com.lhcredit.project.business.customTemplate.service.ICustomTemplateService;
import com.lhcredit.common.utils.text.Convert;

/**
 * 定制模版 服务层实现
 *
 * @author lhcredit
 * @date 2025-04-08
 */
@Service
public class CustomTemplateServiceImpl implements ICustomTemplateService {
    @Autowired
    private CustomTemplateMapper customTemplateMapper;
    @Autowired
    private ITemplateDataSourceService templateDataSourceService;


    @Override
    public AjaxResult addTempLate(List<WebTempConfig.TemplateConfig> list, Integer id) {
        //存储到模版数据中
        CustomTemplate customTemplate = customTemplateMapper.selectCustomTemplateById(id);
        //更新目录
        customTemplate.setSourceJson(JSONArray.toJSONString(list));
        String dirName="template"+System.currentTimeMillis();
        String localpath=WordToPdfUtil.fileDirectory+dirName;
        // 根据编号进行排序  规则是  大模块排序不动  1,2级模块根据所填写的编号 进行排序
        customTemplateMapper.updateCustomTemplate(customTemplate);
        try{
            list = WebTempConfig.filterChecked(list);
            list = WebTempConfig.sortTemplateItem(list);
        }catch (Exception e){
            e.printStackTrace();
            customTemplateMapper.deleteCustomTemplateById(customTemplate.getId());
            return AjaxResult.error(e.getMessage());//数据编号验证存在异常返回
        }
        //处理授信标题
        if (!StreamUtils.of(list).filter(f->f.getKey().equals("model8")).isEmpty()){
            for (WebTempConfig.TemplateConfig templateConfig : list) {
                if (!templateConfig.getKey().equals("model8"))continue;
                templateConfig.setName(templateConfig.getOptions());
            }
        }
        //创建1P级模版
        list= createPLvDocx(list,localpath);
        //原生poi创建生成模版
        String lastTemplate= createPoiTemplate(list,localpath);
        //生成demo数据
        String demoPath=createDemoDocx(lastTemplate,list,localpath);
        String demoUrl =FileSysUtils.getFullPath(FileSysUtils.upLoadFile(new File(WordToPdfUtil.filePathChangeOs(demoPath))));
        String lastTempUrl =FileSysUtils.getFullPath(FileSysUtils.upLoadFile(new File(WordToPdfUtil.filePathChangeOs(lastTemplate))));
        customTemplate.setDemoUrl(demoUrl);
        customTemplate.setTemplateModel(lastTempUrl);
        customTemplateMapper.updateCustomTemplate(customTemplate);
        ReportTemplateService.FileUtils.removeDir(localpath);
        return AjaxResult.success(demoUrl);
    }


    private String createDemoDocx(String lastTemplate, List<WebTempConfig.TemplateConfig> list, String localpath) {
        System.out.println("lastTemplate"+lastTemplate);
        System.out.println("localpath"+localpath);
        List<TemplateDataSource> templateDataSources = templateDataSourceService.selectTemplateDataSourceList(null);
        ConfigureBuilder configureBuilder = new PoitlUtils().getConfigureBuilder().useSpringEL(true);
        JSONObject allPamras = new JSONObject();
        allPamras.put("ename", "demoXXXX企业");
        allPamras.put("showFinanceType", "XXXX类型");
        allPamras.put("genTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, new Date()));
        allPamras.put("showDemo", true);
        allPamras.put("financeUnit", "万元");
        JSONObject param = new JSONObject();
        List<WebTempConfig.TemplateConfig> allTemplate = WebTempConfig.getAllTemplate(list);
        JSONObject idxItem = changeDocIdx(allTemplate);
        allPamras.put("idx", idxItem);
        allPamras.put("isShs", false);
        allPamras.put("financeTypeXc", false);
        allPamras.put("reportFinanceType", "ds");
        //todo 定制版本的excel模型

        allPamras.put("model8_name","建议授信额度");
        allPamras.put("basisCreditLimit",ReportMakeService.no_data);
        //根据前台选择展示的数据
        WebTempConfig.TemplateConfig model8 = StreamUtils.of(list).filter(f -> f.getKey().equals("model8")).getFirst();
        if (null==model8)allPamras.put("xyed_del",true);
        WebTempConfig.TemplateConfig first = StreamUtils.of(list).filter(f -> "model7".contains(f.getKey())).getFirst();
        if (null!=first&&first.isChecked()&&null!=first.getOptionsArr()){
            List<String> collect = Arrays.stream(first.getOptionsArr()).collect(Collectors.toList());
            if (collect.contains("违约率"))allPamras.put("wyl_del",true);
            if (collect.contains("信用评分"))allPamras.put("xypf_del",true);
            if (collect.contains("信用级别"))allPamras.put("xyjb_del",true);
        }
        //根据选择进行复制
        if (!allPamras.containsKey("wyl_del")){
            allPamras.put("default_rate",ReportMakeService.no_data);
//            allPamras.put("appendix4",true);
        }else{
            allPamras.put("default_rate","10%");
        }
        if (!allPamras.containsKey("xypf_del")){
            allPamras.put("creditScore",ReportMakeService.no_data);
        }else{
            allPamras.put("creditScore","50");
        }
        if (!allPamras.containsKey("xyjb_del")){
            allPamras.put("creditLv",ReportMakeService.no_data);
        }else{
            allPamras.put("creditLv","A");
        }
        if (allPamras.containsKey("xyed_del")){
            allPamras.put("creditLimitStr",ReportMakeService.no_data);
            allPamras.put("creditLimit",ReportMakeService.no_data);
        }else{
            allPamras.put("creditLimitStr","10万元");
            allPamras.put("creditLimit","10");
        }
        allPamras.put("creditScoreImTag",false);
        if(allPamras.containsKey("xypf_del")){
            allPamras.put("creditScoreImTag",true);
        }
        allPamras.put("creditLvImgTag",false);
        if(allPamras.containsKey("xyjb_del")){
            allPamras.put("creditLvImgTag",true);
        }
        allPamras.put("model8jy_tag",false);
        allPamras.put("model8jc_tag",false);
        if (null!=model8&&model8.isChecked()){
            if (model8.getOptions().equals("基础授信额度")){
                allPamras.put("model8jc_tag",true);
                allPamras.put("model8_name","基础授信额度");
                allPamras.put("basisCreditLimitTag",true);//基础授信展示标签  =false时模版特殊展示
                allPamras.put("basisCreditLimit",ReportMakeService.no_data);
                allPamras.put("basisCreditLimitShowStr",ReportMakeService.no_data);
                if (allPamras.containsKey("xyed_del")){
                    allPamras.put("basisCreditLimit",ReportMakeService.no_data);
                }
            }else if (model8.getOptions().equals("建议授信额度")){
                allPamras.put("model8jy_tag",true);
                allPamras.put("model8_name","建议授信额度");
            }
        }

        WebTempConfig.TemplateConfig templateConfig = StreamUtils.of(list).filter(f -> f.isChecked() && "model7".contains(f.getKey())).getFirst();
        if (null!=templateConfig){
            String options = templateConfig.getOptions();
            List<String> type =new ArrayList<String>(){{add("违约率");}{add("信用评分");}{add("信用级别");}};
            if (StringUtils.isNotEmpty(options)){
                for (String s2 : options.split(",")) {
                    type.remove(s2);
                }
            }
            if (type.contains("违约率"))allPamras.put("default_rate",ReportMakeService.no_data);
            if (type.contains("信用评分"))allPamras.put("creditScore",ReportMakeService.no_data);
            if (type.contains("信用级别"))allPamras.put("creditLv",ReportMakeService.no_data);
        }

        for (WebTempConfig.TemplateConfig i : allTemplate) {
            TemplateDataSource first2 = StreamUtils.of(templateDataSources).filter(f -> StringUtils.isNotEmpty(f.getModelKey())).filter(f -> f.getModelKey().equals(i.getKey())).getFirst();
            try {
                if ("zy.model7,model8".contains(i.getKey())) {
                    i.setType(WebTempConfig.Type.H1.type);
                }
                DocxRenderData docxRenderData = null;
                try {
                    if (i.getType().equals(WebTempConfig.Type.P.type) || i.getType().equals(WebTempConfig.Type.PModel.type) || i.getType().equals(WebTempConfig.Type.H1Tit.type)) {
                        docxRenderData = Includes.ofStream(new FileInputStream(new File(WordToPdfUtil.filePathChangeOs(i.getLocalPath())))).setRenderModel(allPamras).create();
                    } else {
                        String val254 = WordToPdfUtil.resourcePath  + first2.getDocPath().replace("/", "\\");
                        docxRenderData = Includes.ofStream(new FileInputStream(new File(WordToPdfUtil.filePathChangeOs(val254)))).setRenderModel(allPamras).create();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                param.put(i.getKey(), docxRenderData);
                //首页添加  轮询就这样吧
                param.put("home", Includes.ofStream(new FileInputStream(new File(WordToPdfUtil.filePathChangeOs(WordToPdfUtil.resourcePath+ "reportTemplate\\首页.docx")))).setRenderModel(allPamras).create());

            } catch (FileNotFoundException e) {
                System.out.println(i.getName());
                throw new RuntimeException(e);
            }
        }
        param.putAll(allPamras);
        String s = PoitlUtils.outPutDocx2(lastTemplate, localpath, "demo", param, configureBuilder.build());
        PoitlUtils.updateCatalogue(s);
        PoitlUtils.updateCatalogue(s);
        return s;
    }

    private JSONObject changeDocIdx(List<WebTempConfig.TemplateConfig> allTemplate) {
        JSONObject idxItem=new JSONObject();
        for (WebTempConfig.TemplateConfig templateConfig : allTemplate) {
            if (StringUtils.isEmpty(templateConfig.getIdx()))templateConfig.setIdx("-");
            idxItem.put(templateConfig.getKey(),templateConfig.getIdx());
        }
        return idxItem;
    }

    private String createPoiTemplate(List<WebTempConfig.TemplateConfig> list, String localpath) {
        String sy=WordToPdfUtil.resourcePath+"reportTemplate"+File.separator+"首页.docx";
        try{
            XWPFDocument document = new XWPFDocument(new FileInputStream(new File(WordToPdfUtil.filePathChangeOs(sy))));
            for (WebTempConfig.TemplateConfig templateConfig : list) {
                if (!templateConfig.isChecked())continue;
                if (!templateConfig.getKey().equals("model9")){//9附录不生成
                    addText(document,"{{+"+templateConfig.getKey()+"}}");
                }
                List<WebTempConfig.TemplateConfig> h1List = templateConfig.getList();
                if (CollectionUtils.isEmpty(h1List))continue;
                //处理h1
                for (WebTempConfig.TemplateConfig h1Item : h1List) {
                    if (!h1Item.isChecked())continue;
                    addText(document,"{{+"+h1Item.getKey()+"}}");
                    List<WebTempConfig.TemplateConfig> h2List = h1Item.getList();
                    if (CollectionUtils.isEmpty(h2List))continue;
                    for (WebTempConfig.TemplateConfig i : h2List) {
                        if (i.isChecked()){
                            addText(document,"{{+"+i.getKey()+"}}");
                        }
                    }
                }
            }
            String lastPath=localpath + "\\lastTemplate.docx";
            try (FileOutputStream out = new FileOutputStream(WordToPdfUtil.filePathChangeOs(lastPath))) {
                document.write(out);
            }
            document.close();
            return lastPath;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    public void addText( XWPFDocument document,String text){
        document.createParagraph().createRun().setText(text);
    }



    private List<WebTempConfig.TemplateConfig>  createPLvDocx(List<WebTempConfig.TemplateConfig> list, String localpath) {
        String pTemplate=WordToPdfUtil.resourcePath+"reportTemplate\\p1Idx.docx";
        String h1Template=WordToPdfUtil.resourcePath+"reportTemplate\\h1Tltle.docx";
        ReportTemplateService.FileUtils.creditDir(localpath);
        for (WebTempConfig.TemplateConfig templateConfig : list) {
            if (!templateConfig.isChecked()) continue;//未选择跳过
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("p1idx",templateConfig.getIdx());
            jsonObject.put("p1Name",templateConfig.getName());
            jsonObject.put("top",templateConfig.getIdx().equals("1"));//给标题进行段前分页
            String s = PoitlUtils.outPutDocx2(pTemplate, localpath, templateConfig.getKey(), jsonObject, new PoitlUtils().getConfigureBuilder().useSpringEL(true).build());
            templateConfig.setLocalPath(s);
            List<WebTempConfig.TemplateConfig> h1 = templateConfig.getList();
            if (CollectionUtils.isEmpty(h1))continue;
            for (WebTempConfig.TemplateConfig hiItem : h1) {
                if (!hiItem.isChecked()) continue;//未选择跳过
                if (hiItem.getType().equals(WebTempConfig.Type.H1Tit.type)){
                    JSONObject h1Json=new JSONObject();
                    h1Json.put("h1Tit",hiItem.getIdx());
                    h1Json.put("h1Name",hiItem.getName());
                    h1Json.put("top",hiItem.getIdx().equals("1"));//给标题进行段前分页
                    String path = PoitlUtils.outPutDocx2(h1Template, localpath, hiItem.getKey(), h1Json, new PoitlUtils().getConfigureBuilder().useSpringEL(true).build());
                    hiItem.setLocalPath(path);
                }
            }
        }
        return list;
    }


    /**
     * 查询定制模版信息
     *
     * @param id 定制模版ID
     * @return 定制模版信息
     */
    @Override
    public CustomTemplate selectCustomTemplateById(Integer id) {
        return customTemplateMapper.selectCustomTemplateById(id);
    }

    /**
     * 查询定制模版列表
     *
     * @param customTemplate 定制模版信息
     * @return 定制模版集合
     */
    @Override
    public List<CustomTemplate> selectCustomTemplateList(CustomTemplate customTemplate) {
        List<CustomTemplate> customTemplates = customTemplateMapper.selectCustomTemplateList(customTemplate);
        if (CollectionUtils.isEmpty(customTemplates))return customTemplates;
        for (CustomTemplate template : customTemplates) {
            template.setSourceJson(null);
        }
        return customTemplates;
    }

    /**
     * 字段转换
     * @param customTemplate 定制模版信息
     * @return 定制模版信息
     */
    @Override
    public CustomTemplate changeModel(CustomTemplate customTemplate) {
//        //这里写各字段转换逻辑
//        if(customTemplate!=null){
//            if(StringUtils.isNotEmpty(customTemplate.getXXX())){
//               customTemplate.setXXX(customTemplate.getXXX());
//            }
//        }
        return customTemplate;
    }

    /**
     * 列表转换
     *
     * @param customTemplateList 定制模版集合
     * @return 定制模版集合
     */
    @Override
    public List<CustomTemplate> changeModel(List<CustomTemplate> customTemplateList) {
        List<CustomTemplate> result = new ArrayList<CustomTemplate>();
        if (customTemplateList.size() > 0) {
            for (CustomTemplate customTemplate:customTemplateList){
                result.add(changeModel(customTemplate));
            }
        }
        return result;
    }

    /**
     * 新增定制模版
     *
     * @param customTemplate 定制模版信息
     * @return 结果
     */
    @Override
    public int insertCustomTemplate(CustomTemplate customTemplate) {
        return customTemplateMapper.insertCustomTemplate(customTemplate);
    }

    /**
     * 修改定制模版
     *
     * @param customTemplate 定制模版信息
     * @return 结果
     */
    @Override
    public int updateCustomTemplate(CustomTemplate customTemplate) {
        return customTemplateMapper.updateCustomTemplate(customTemplate);
    }

    /**
     * 删除定制模版对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteCustomTemplateByIds(String ids) {
        return customTemplateMapper.deleteCustomTemplateByIds(Convert.toStrArray(ids));
    }

    @Override
    public  List<CustomTemplate> getByOrgId(Integer orgId) {
        return customTemplateMapper.getByOrgId(orgId);
    }

}