Browse Source

计量报表写入

yangyj 1 year ago
parent
commit
0cc740d9ac

+ 22 - 0
blade-service-api/blade-manager-api/src/main/java/org/springblade/manager/vo/ReportResult.java

@@ -14,12 +14,34 @@ import java.util.Map;
 public class ReportResult {
     /**html地址*/
     private String url;
+    /**excel清表模版地址*/
+    private String excelUrl;
     /**表编号*/
     private String initTableName;
     /**清表模版*/
     private Long excelId;
     /**表名*/
     private String name;
+    /**pdf路基*/
+    private String pdfPath;
+    /**Excel路基*/
+    private String excelPath;
     /**每一页的数据,格式{y_x:val,y1_x1:val1...}{...}...*/
     private List<Map<String,Object>> data;
+
+    public String getPdfPath(){
+        return this.pdfPath;
+    }
+    public String getExcelPath(){
+       return this.excelPath;
+    }
+
+    public String getId(){
+        return  0L+""+excelId;
+    }
+    public void pathInit(String sysLocalFileUrl){
+        this.pdfPath=sysLocalFileUrl + "/pdf//" +getId() + ".pdf";
+        this.excelPath=sysLocalFileUrl + "/pdf//" + getId() + ".xlsx";
+    }
+
 }

+ 137 - 91
blade-service/blade-meter/src/main/java/org/springblade/meter/controller/TaskController.java

@@ -1,6 +1,7 @@
 package org.springblade.meter.controller;
 
 
+import com.aspose.cells.SaveFormat;
 import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
 import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
@@ -9,22 +10,23 @@ import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.core.type.TypeReference;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
+import com.itextpdf.text.Document;
+import com.itextpdf.text.pdf.PdfCopy;
+import com.itextpdf.text.pdf.PdfReader;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import lombok.AllArgsConstructor;
 import lombok.Data;
 import org.apache.commons.lang.StringUtils;
 import org.apache.commons.lang.time.DateUtils;
-import org.apache.poi.ss.usermodel.Cell;
-import org.apache.poi.ss.usermodel.Row;
-import org.apache.poi.ss.usermodel.Sheet;
-import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.ss.usermodel.*;
 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 import org.springblade.business.entity.FixedFlowLink;
 import org.springblade.business.entity.Task;
 import org.springblade.business.entity.TaskParallel;
 import org.springblade.business.feign.TaskClient;
 import org.springblade.common.constant.ClientIdConstant;
+import org.springblade.common.utils.BaseUtils;
 import org.springblade.common.utils.CommonUtil;
 import org.springblade.common.utils.SnowFlakeUtil;
 import org.springblade.core.boot.ctrl.BladeController;
@@ -36,16 +38,15 @@ import org.springblade.core.secure.utils.AuthUtil;
 import org.springblade.core.secure.utils.SecureUtil;
 import org.springblade.core.tool.api.R;
 import org.springblade.core.tool.utils.*;
+import org.springblade.core.tool.utils.DateUtil;
 import org.springblade.feign.ArchiveFileTaskClient;
 import org.springblade.manager.entity.ContractInfo;
 import org.springblade.manager.entity.ContractRelationJlyz;
-import org.springblade.manager.entity.ExcelTab;
 import org.springblade.manager.entity.WbsTreePrivate;
 import org.springblade.manager.feign.FormulaClient;
 import org.springblade.manager.vo.ReportResult;
 import org.springblade.meter.dto.*;
 import org.springblade.meter.entity.*;
-import org.springblade.meter.mapper.MaterialStartStatementMapper;
 import org.springblade.meter.mapper.MiddleMeterApplyMapper;
 import org.springblade.meter.service.IMaterialStartStatementService;
 import org.springblade.meter.service.impl.*;
@@ -2451,10 +2452,10 @@ public class TaskController extends BladeController {
     }
 
 
-    @GetMapping("/meterPdfInfo")
+    @GetMapping("/meterPdfInfoOld")
     @ApiOperationSupport(order = 20)
     @ApiOperation(value = "计量生成Pdf", notes = "计量生成Pdf")
-    public R meterPdfInfo(@RequestParam String ContractId, @RequestParam String FormDataId, @RequestParam Integer type) {
+    public R meterPdfInfoOld(@RequestParam String ContractId, @RequestParam String FormDataId, @RequestParam Integer type) {
         String file_path = CollectionUtils.getSysLocalFileUrl();
         String fileUrl = "";
         Long sid = 0l;
@@ -2574,105 +2575,136 @@ public class TaskController extends BladeController {
         return R.success(fileUrl);
     }
 
+    @GetMapping("/meterPdfInfo")
+    @ApiOperationSupport(order = 20)
+    @ApiOperation(value = "计量生成Pdf", notes = "计量生成Pdf")
+    public R meterPdfInfo( @RequestParam String reportId, @RequestParam Integer type){
+          return R.data(calculate(reportId,type));
+    }
+
+    public R<String> calculate(String reportId, Integer type){
+        if(BaseUtils.isNumber(reportId)&&BaseUtils.isNumber(type)) {
+            Report report = generateReport(Long.parseLong(reportId), type);
+            return R.data(generateReportsPdf(report));
+        }
+        return R.fail("计算失败");
+    }
 
     /*中期支付证书报表、开工、材料手册报表*/
-    public void generateReportsPdf(Report report){
+    public String generateReportsPdf(Report report){
         /*报表记录新增或者重算的时候会调用当前方法,生成PDF*/
-        /*保存两类PDF,一每种表独立一份放标浏览,二合成表用于电签*/
+        /*保存两类PDF,一每种表独立一份用于浏览,二合成表用于电签*/
         /*数据完全独立互不影响,可以并发生成,预估PDF的总大小来绝对是否全部在内存中生成PDF*/
+        /*分为新增和更新*/
         List<ReportResult> reportResults = formulaClient.formulaExecute3(report.getContractId(), report.getId(), report.getType());
+        String fileUrl = null;
         if(Func.isNotEmpty(reportResults)){
-            List<String> dataListPdf = new ArrayList<>();
+            /*List<String> dataListPdf = new ArrayList<>();*/
             String file_path = CollectionUtils.getSysLocalFileUrl();
-            String fileUrl = "";
-            Long sid = 0L;
-            for (ReportResult data : reportResults) {
-                Long excelId = data.getExcelId();
-                String exSql = "SELECT * from m_excel_tab where id=" + excelId + "";
-               // ExcelTab
-                Map<String, Object> exMap = jdbcTemplate.queryForMap(exSql);
-                if (exMap == null) {
-                    //return R.fail("未获取到该表单的信息");
-                }
-                if (exMap.get("file_url") == null) {
-                  //  return R.fail("htmlUrl is null");
-                }
-                String pkeyId = sid + "" + excelId;
-                String pdfPath = file_path + "/pdf//" + pkeyId + ".pdf";
-                String excelPath = file_path + "/pdf//" + pkeyId + ".xlsx";
-
-                String excelUrl = exMap.get("file_url") + "";
-
-                File tabPdf = null;
-                try {
-                    tabPdf = ResourceUtil.getFile(pdfPath);
-                } catch (FileNotFoundException e) {
-                    throw new RuntimeException(e);
-                }
-                if (tabPdf.exists()) {
-                    tabPdf.delete();
-                }
-
-
-                //获取excel流 和 html流
-                try {
-                    InputStream exceInp = CommonUtil.getOSSInputStream(excelUrl);
-                    Workbook workbook = null;
-                    int index = excelUrl.lastIndexOf(".");
-                    String suffix = excelUrl.substring(index).toLowerCase();
-
-                    if (".xls".equals(suffix)) {
-                        workbook = new XSSFWorkbook(exceInp);
-                    } else if (".xlsx".equals(suffix)) {
-                        workbook = new XSSFWorkbook(exceInp);
+          /*  String fileUrl = "";*/
+            List<Map<String,Object>> excelInfo=jdbcTemplate.queryForList("SELECT id,file_url from m_excel_tab where id in(?)",reportResults.stream().map(ReportResult::getExcelId).distinct().collect(Collectors.toList()));
+            if(Func.isNotEmpty(excelInfo)){
+                /*所有的Excel地址映射*/
+                Map<String,String> fileUrlMapping = excelInfo.stream().collect(Collectors.toMap(m->m.get("id").toString(),m->m.get("file_url").toString(),(v1,v2)->v1));
+                /*把Excel缺失的移除*/
+                reportResults.removeIf(rs->!fileUrlMapping.containsKey(rs.getExcelId().toString()));
+                /*准备*/
+                reportResults.forEach(rs->{
+                    /*初始化路径*/
+                     rs.pathInit(file_path);
+                     rs.setExcelUrl(fileUrlMapping.get(rs.getExcelId().toString()));
+                    /*删除已经存在的PDF*/
+                    File tabPdf;
+                    try {
+                        tabPdf = ResourceUtil.getFile(rs.getPdfPath());
+                        if (tabPdf.exists()) {
+                            if(tabPdf.delete()){
+                                System.out.println(rs.getPdfPath()+"删除成功");
+                            }
+                        }
+                    } catch (FileNotFoundException e) {
+                        throw new RuntimeException(e);
                     }
-                    //获取工作表
-                    Sheet sheet = workbook.getSheetAt(0);
-                    sheet.setForceFormulaRecalculation(true);
-
-                    // 写入数据
-                    List<Map<String, Object>> dataData = data.getData();
-                    if (dataData != null && dataData.size() >= 1) {
-                        for (Map<String, Object> dama : dataData) {
-
-                            // 循环Key
-                            for (String keys : dama.keySet()) {
-                                int y1 = Func.toInt(keys.split("_")[0]);
-                                int x1 = Func.toInt(keys.split("_")[1]);
-                                Row row = sheet.getRow(y1 - 1);
-                                if (row != null) {
-                                    Cell cell = row.getCell(x1 - 1);
-                                    String dataval = dama.get(keys) + "";
-                                    if (dataval.indexOf("第") >= 0 && dataval.indexOf("次支付") >= 0) {
-                                        String datare = dataval.replace("第", "").replace("次交付", "");
-                                        dataval = datare.replace("次支付", "");
+                });
+                /*每种表生成一份pdf*/
+                reportResults.parallelStream().forEach(rs->{
+                    try {
+                        byte[] excelByte = CommonUtil.InputStreamToBytes(CommonUtil.getOSSInputStream(rs.getExcelUrl()));
+                        if(Func.isNotEmpty(rs.getData())){
+                            PdfReader reader;
+                            Document doc = new Document();
+                            PdfCopy pdfCopy;
+                            pdfCopy = new PdfCopy(doc, new FileOutputStream(rs.getPdfPath()));
+                            int pageCount;
+                            doc.open();
+                            for(Map<String,Object> dataMap:rs.getData()){
+                                if (Func.isNotEmpty(dataMap)) {
+                                    try {
+                                        Workbook workbook  = WorkbookFactory.create(new ByteArrayInputStream(excelByte));
+                                        //获取工作表
+                                        Sheet sheet = workbook.getSheetAt(0);
+                                        sheet.setForceFormulaRecalculation(true);
+                                        // 循环Key
+                                        for (String keys : dataMap.keySet()) {
+                                            int y1 = Func.toInt(keys.split("_")[0]);
+                                            int x1 = Func.toInt(keys.split("_")[1]);
+                                            Row row = sheet.getRow(y1);
+                                            if (row != null) {
+                                                Cell cell = row.getCell(x1);
+                                                cell.setCellValue(dataMap.getOrDefault(keys,StringPool.EMPTY).toString());
+                                            }
+                                        }
+                                        /*输出到内存*/
+                                        //去掉表格虚线
+                                        sheet.setPrintGridlines(false);
+                                        //设置 整个工作表为一页
+                                        sheet.setFitToPage(true);
+                                        sheet.getPrintSetup().setPaperSize(PrintSetup.A4_PAPERSIZE);
+                                        ByteArrayOutputStream out = new ByteArrayOutputStream();
+                                        workbook.write(out);
+                                       // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(out.toByteArray());
+                                        com.aspose.cells.Workbook wb = new com.aspose.cells.Workbook( new ByteArrayInputStream(out.toByteArray()));
+                                        out.reset();
+                                        wb.save(out, SaveFormat.PDF);
+                                        //reader = new PdfReader(new ByteArrayInputStream(out.toByteArray()));
+                                        reader = new PdfReader(new ByteArrayInputStream(out.toByteArray()));
+                                        pageCount = reader.getNumberOfPages();
+                                        for (int i = 0; i < pageCount; ++i) {
+                                            int is = i + 1;
+                                            pdfCopy.addPage(pdfCopy.getImportedPage(reader, is));
+                                        }
+                                        workbook.close();
+                                    }catch (Exception e){
+                                        e.printStackTrace();
+                                    }finally {
+                                        pdfCopy.flush();
+                                        pdfCopy.close();
+                                        doc.close();
                                     }
-                                    cell.setCellValue(dataval);
                                 }
                             }
                         }
+                    }catch (Exception e){
+                        e.printStackTrace();
                     }
-
-                    //输出流
-                    FileOutputStream outputStream = new FileOutputStream(excelPath);
-                    workbook.write(outputStream);
-                    CollectionUtils.excelToPdf(excelPath, pdfPath);
-                    dataListPdf.add(pdfPath);
-                    //关闭流
-                    IoUtil.closeQuietly(outputStream);
-                    IoUtil.closeQuietly(exceInp);
-                } catch (Exception e) {
-                    throw new RuntimeException(e);
-                }
+                });
+                /*合并所有表*/
+                Long dataId = SnowFlakeUtil.getId();
+                String lasPdf = file_path + "/pdf//" + dataId + "_last.pdf";
+                CollectionUtils.mergePdfPublicMethods(reportResults.stream().map(ReportResult::getPdfPath).collect(Collectors.toList()), lasPdf);
+                BladeFile bladeFile = newIOSSClient.uploadFile(dataId + "_last.pdf", lasPdf);
+                fileUrl=bladeFile.getLink();
+                String upSql = "update "+Report.REPORT_TYPE[report.getType()]+" set raw_url='" + fileUrl + "' where contract_id=" + report.getContractId() + " and type=1 and meter_period_id=" + report.getPeriodId() + "";
+                jdbcTemplate.execute(upSql);
             }
         }
-
+       return fileUrl;
     }
 
     @Data
    static class Report{
-        public static final String[] REPORT_TYPE=new String[]{"s_material_start_statement","s_interim_pay_certificate"};
-        public static final String[] PERIOD_TYPE=new String[]{"s_contract_meter_period","s_meter_period"};
+        public static final String[] REPORT_TYPE=new String[]{"s_interim_pay_certificate","s_material_start_statement","s_material_start_statement"};
+        public static final String[] PERIOD_TYPE=new String[]{"s_contract_meter_period","s_meter_period","s_meter_period"};
         /**报表记录id*/
         private Long id;
         /**报表PDF地址*/
@@ -2683,10 +2715,24 @@ public class TaskController extends BladeController {
         private Long contractId;
         /**计量类型,0中间计量 1材料,2开工动员*/
         private Integer type;
-   }
 
-   public Report generateReport(String reportId,Integer type){
-        return new Report();
+        public Report(Long id, Integer type) {
+            this.id = id;
+            this.type = type;
+        }
+    }
+
+   public Report generateReport(Long reportId,Integer type){
+        Report report =new Report(reportId,type);
+        Map<String,Object> map;
+        if(type==0){
+            map = this.jdbcTemplate.queryForMap("select id,contract_id ,contract_period_id period_id from s_interim_pay_certificate where id = "+reportId);
+        }else{
+            map = this.jdbcTemplate.queryForMap("select id,contract_id,meter_period_id period_id  from s_material_start_statement where id = "+reportId);
+        }
+        report.setContractId(Long.parseLong(map.get("contract_id").toString()));
+        report.setPeriodId(Long.parseLong(map.get("period_id").toString()));
+        return report;
    }