许鹏程
2023-05-26 340049ec6c2c1d830f5331e2cbb02204ee1572b1
src/main/java/com/product/server/report/service/DataListReportService.java
@@ -1,5 +1,8 @@
package com.product.server.report.service;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
@@ -18,13 +21,19 @@
import com.product.core.service.support.AbstractBaseService;
import com.product.core.service.support.QueryFilterService;
import com.product.core.spring.context.SpringMVCContextHolder;
import com.product.module.data.service.SystemDataExportService;
import com.product.server.report.config.CmnConst;
import com.product.server.report.config.ReportCode;
import com.product.server.report.entity.ReportColumn;
import com.product.server.report.entity.ReportEntity;
import com.product.util.BaseUtil;
import com.product.util.SystemParamReplace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
@@ -32,6 +41,7 @@
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
 * Copyright © 6c
@@ -52,6 +62,107 @@
   private QueryFilterService queryFilterService;
   @Autowired
   private RouterService routerService;
   @Resource
   private SystemDataExportService exportService;
   public void outReportExcel(HttpServletResponse response, FieldSetEntity fse) throws BaseException, IOException {
      ReportEntity reportEntity = getReportEntity(fse);
      List<List<ReportColumn>> reportHeader = reportEntity.getReportHeader();
      List<List<String>> headerTemp = processingMergeData(reportHeader);
      List<List<String>> header = headerTemp.get(0).stream().map(item -> new ArrayList<String>()).collect(Collectors.toList());
      int size = headerTemp.get(0).size();
      for (int i = 0; i < size; i++) {
         for (int k = 0; k < headerTemp.size(); k++) {
            header.get(i).add(headerTemp.get(k).get(i));
         }
      }
      List<List<ReportColumn>> reportData = reportEntity.getReportData();
      if (!CollectionUtil.isEmpty(reportEntity.getReportTail())) {
         reportData.addAll(reportEntity.getReportTail());
      }
      List<List<String>> data = processingMergeData(reportData);
      exportService.writeExcel(header, data, "测试", response);
   }
   private static List<List<String>> processingMergeData(List<List<ReportColumn>> data) {
      if (CollectionUtil.isEmpty(data)) {
         return null;
      }
      List<List<String>> resultData = data.stream().map(item -> new ArrayList<String>()).collect(Collectors.toList());
      for (int i = 0; i < data.size(); i++) {
         List<ReportColumn> columns = data.get(i);
         for (ReportColumn column : columns) {
            //跨行
            int rowspan = column.getRowspan() < 1 ? 1 : column.getRowspan();
            //跨列
            int colspan = column.getColspan() < 1 ? 1 : column.getColspan();
            List<String> currentCell = new ArrayList<>();
            for (int k = 0; k < colspan; k++) {
               currentCell.add(column.getContent(true));
            }
            for (int j = 0; j < rowspan; j++) {
               resultData.get(j + i).addAll(currentCell);
            }
            System.out.println(resultData);
         }
      }
      return resultData;
   }
   public static void main(String[] args) {
      List<List<ReportColumn>> data = new ArrayList<>();
      List<ReportColumn> columns = new ArrayList<>();
      ReportColumn column = new ReportColumn();
      column.setRowspan(2);
      column.setColspan(4);
      column.setContent("跨行数:2,跨列数:4");
      columns.add(column);
      data.add(columns);
      columns = new ArrayList<>();
      data.add(columns);
      for (int i = 0; i < 3; i++) {
         column = new ReportColumn();
         column.setContent("跨行数:1,跨列数:1,下标:" + i);
         columns.add(column);
      }
      processingMergeData(data);
   }
   /**
    * @param target
    * @param content
    * @param colspan
    * @param rowspan
    * @param currentColspan
    * @param currentRowsSpan
    */
   private void rowspanAndColspan(String[][] target, String content, int colspan, int rowspan, int currentColspan, int currentRowsSpan) {
      int k = currentColspan;
      int i = currentRowsSpan;
      if (colspan > 1) {
         for (int j = 1; j < colspan; j++) {
            int index = j + k;
            while (target[i][index] != null) {
               index++;
            }
            target[i][index] = content;
         }
      }
      if (rowspan > 1) {
         for (int j = 1; j < rowspan; j++) {
            int index = i + k;
            while (target[index][k] != null) {
               index++;
            }
            target[index][k] = content;
         }
      }
   }
   /**
    * 加载所有缓存
@@ -132,11 +243,9 @@
         if (preX != x || preY != y) {
            fieldConfigObj = new JSONObject();
            areaList.add(fieldConfigObj);
         } else if (areaList.size() > 0) {
            fieldConfigObj = areaList.get(areaList.size() - 1);
         } else {
            continue;
         }
                fieldConfigObj = areaList.get(areaList.size() - 1);
            }
         fieldConfigObj.put(attrFse.getString(CmnConst.ATTR_NAME), attrFse.getString(CmnConst.ATTR_VALUE));
         fieldConfigObj.put(CmnConst.ATTR_X, x);
         fieldConfigObj.put(CmnConst.ATTR_Y, y);
@@ -251,13 +360,19 @@
      }
   }
   /**
    * 获取报表
    *
    * @return
    */
   public JSONObject getReport(FieldSetEntity fse) {
   public ReportEntity getReportEntity(FieldSetEntity fse) {
      ReportEntity report = null;
      String reportConfigUUID = fse.getUUID();
      if (!StringUtils.isEmpty(fse.getString("~report_config_uuid~"))) {
         //子报表会传入此key作为报表的uuid 规避参数中有uuid的key
         reportConfigUUID = fse.getString("~report_config_uuid~");
      }
      DataTableEntity reportConfigDte = DataPoolCacheImpl.getInstance().getCacheData(CmnConst.CACHE_REPORT_CONFIG, new String[]{reportConfigUUID});
      if (BaseUtil.dataTableIsEmpty(reportConfigDte)) {
         throw new BaseException(ReportCode.GET_CACHE_FIAL.getValue(), ReportCode.GET_CACHE_FIAL.getText() + ":" + CmnConst.CACHE_REPORT_CONFIG);
@@ -326,6 +441,7 @@
      JSONObject resultObj = new JSONObject();
      // 首次加载,默认添加条件
      Map<String, Map<String, String>> outerMap = Maps.newHashMap();
      if (fse.getBoolean(CmnConst.FIRST_LOAD)) {
         DataTableEntity allFilterDte = getDefaultSearchFilter(reportSourceFse.getUUID());
         Map<String, DataTableEntity> subMap = Maps.newHashMap();
@@ -335,7 +451,7 @@
         DataTableEntity defaultFilterDte = new DataTableEntity();
         FieldSetEntity tempFse;
         Map<String, Map<String, String>> outerMap = Maps.newHashMap();
         Map<String, String> innerMap;
         for (int i = 0; i < allFilterDte.getRows(); i++) {
            tempFse = allFilterDte.getFieldSetEntity(i);
@@ -349,7 +465,7 @@
            innerMap.put(CmnConst.FIELD_TYPE, tempFse.getString(CmnConst.FIELD_TYPE));
            outerMap.put(tempFse.getString(CmnConst.FIELD_NAME), innerMap);
         }
         resultObj.put("filterInfo", outerMap);
//         resultObj.put("filterInfo", outerMap);
         if (!DataTableEntity.isEmpty(defaultFilterDte)) {
            subMap.put("systemSeniorQueryString", defaultFilterDte);
@@ -367,25 +483,29 @@
//            return checkObj;
//        }
      StringBuilder tableStyle = new StringBuilder(32);
      String widthType = reportConfigFse.getString(CmnConst.REPORT_WIDTH_TYPE);
      String width = reportConfigFse.getString(CmnConst.REPORT_WIDTH_VALUE);
      if (!StringUtils.isEmpty(width)) {
         if ("1".equals(widthType)) {
            tableStyle.append(" style=\"width:").append(width).append("%\"");
         } else if ("0".equals(widthType)) {
            tableStyle.append(" style=\"width:").append(width).append("px\"");
         }
      }
//      StringBuilder tableStyle = new StringBuilder(32);
//      String widthType = reportConfigFse.getString(CmnConst.REPORT_WIDTH_TYPE);
//      String width = reportConfigFse.getString(CmnConst.REPORT_WIDTH_VALUE);
//      if (!StringUtils.isEmpty(width)) {
//         if ("1".equals(widthType)) {
//            tableStyle.append(" style=\"width:").append(width).append("%\"");
//         } else if ("0".equals(widthType)) {
//            tableStyle.append(" style=\"width:").append(width).append("px\"");
//         }
//      }
      if (CmnConst.REPORT_TYPE_COMMON.equals(reportType)) {
         resultObj.putAll(commonReportService.getReport(recordDte, totalName, reportConfigMap, tableStyle));
         report = commonReportService.getReportEntity(recordDte, totalName, reportConfigMap);
         report.setFilterInfo(outerMap);
      } else if (CmnConst.REPORT_TYPE_GROUP.equals(reportType)) {
         // 特殊处理额外查询内容
         recordDte.addFieldSetEntity(getRecordDte(sort, curPage, reportSourceFse, fse, reportConfigFse, reportConfigMap));
         resultObj.putAll(groupReportService.getReport(recordDte, totalName, reportConfigMap, tableStyle));
         report = groupReportService.getReportEntity(recordDte, totalName, reportConfigMap);
//         resultObj.putAll(groupReportService.getReport(recordDte, totalName, reportConfigMap, tableStyle));
      }
      report.setReportConfigUid(reportConfigFse.getUUID());
      report.setReportName(reportConfigFse.getString(CmnConst.REPORT_NAME));
//      report.setFilterInfo(outerMap);
      if (CmnConst.FALSE.equals(resultObj.getString(CmnConst.RETURN_ATTR_RESULT))) {
         resultObj.put(CmnConst.RETURN_ATTR_RESULT, true);
         resultObj.put(CmnConst.RETURN_ATTR_MESSAGE, "获取报表失败!");
@@ -393,24 +513,30 @@
         // 分页参数
         SQLEntity sqlEntity = recordDte.getSqle();
         if ("1".equals(reportConfigFse.getString(CmnConst.IS_PAGE)) && sqlEntity != null) {
            resultObj.put(CmnConst.IS_PAGE, 1);
            resultObj.put(CmnConst.CPAGE, curPage);
            resultObj.put("totalCount", sqlEntity.getTotalCount());
            resultObj.put("totalpage", sqlEntity.getTotalpage());
            resultObj.put("pagesize", StringUtils.isEmpty(reportConfigFse.getString(CmnConst.PAGE_SIZE)) ? 0 : reportConfigFse.getInteger(CmnConst.PAGE_SIZE));
         } else {
            resultObj.put(CmnConst.IS_PAGE, 0);
            report.setPage(true);
            report.setTotalCount(sqlEntity.getTotalCount());
            report.setPageSize(StringUtils.isEmpty(reportConfigFse.getString(CmnConst.PAGE_SIZE)) ? 0 : reportConfigFse.getInteger(CmnConst.PAGE_SIZE));
            report.setPageIndex(curPage);
//            resultObj.put(CmnConst.IS_PAGE, 1);
//            resultObj.put(CmnConst.CPAGE, curPage);
//            resultObj.put("totalCount", sqlEntity.getTotalCount());
//            resultObj.put("totalpage", sqlEntity.getTotalpage());
//            resultObj.put("pagesize", StringUtils.isEmpty(reportConfigFse.getString(CmnConst.PAGE_SIZE)) ? 0 : reportConfigFse.getInteger(CmnConst.PAGE_SIZE));
         }
      }
      if (!DataTableEntity.isEmpty(recordDte)) {
         resultObj.put("current_page_count", recordDte.getRows());
      }
      resultObj.put("systemFieldMeta", getSearchInfo(reportSourceFse.getUUID()));
      resultObj.put("report_type", reportConfigFse.getString("type_uuid"));
//      if (!DataTableEntity.isEmpty(recordDte)) {
//         resultObj.put("current_page_count", recordDte.getRows());
//      }
      report.setSystemFieldMeta(getSearchInfo(reportSourceFse.getUUID()));
      report.setReportType(reportConfigFse.getString("type_uuid"));
//      resultObj.put("systemFieldMeta", );
//      resultObj.put("report_type", reportConfigFse.getString("type_uuid"));
//        System.out.println(resultObj.getString("html"));
      return resultObj;
      return report;
   }
   /**
    * 获取报表缓存信息
@@ -452,7 +578,9 @@
    * @param reportConfigFse
    * @return
    */
   private DataTableEntity getRecordDte(StringBuilder sort, int curPage, FieldSetEntity reportSourceFse, FieldSetEntity fse, FieldSetEntity reportConfigFse, Map<Integer, List<JSONObject>> reportConfigMap) {
   private DataTableEntity getRecordDte(StringBuilder sort, int curPage, FieldSetEntity
         reportSourceFse, FieldSetEntity fse, FieldSetEntity
                                     reportConfigFse, Map<Integer, List<JSONObject>> reportConfigMap) {
      boolean spTimeFlag = reportConfigMap != null;
      String sql;
      String sqlText = reportSourceFse.getString(CmnConst.SQL_TEXT);
@@ -590,7 +718,8 @@
    * @param sort
    * @return
    */
   private String replaceSqlContent(String sqlText, FieldSetEntity fse, StringBuilder sort, FieldSetEntity reportConfigFse, int curPage, String selectedFields, Map<String, List<String>> queryFilterMap) {
   private String replaceSqlContent(String sqlText, FieldSetEntity fse, StringBuilder sort, FieldSetEntity
         reportConfigFse, int curPage, String selectedFields, Map<String, List<String>> queryFilterMap) {
      queryFilterMap = queryFilterMap == null ? queryFilterService.getQueryFilterMore(fse) : queryFilterMap;
      selectedFields = StringUtils.isEmpty(selectedFields) ? "*" : selectedFields;
      // 替换sql中的系统参数
@@ -665,7 +794,8 @@
      return sql.toString();
   }
   private String replaceSqlContent(String sqlText, FieldSetEntity fse, StringBuilder sort, FieldSetEntity reportConfigFse, int curPage) {
   private String replaceSqlContent(String sqlText, FieldSetEntity fse, StringBuilder sort, FieldSetEntity
         reportConfigFse, int curPage) {
      return replaceSqlContent(sqlText, fse, sort, reportConfigFse, curPage, null, null);
   }
@@ -678,7 +808,8 @@
    * @param queryFilterMap
    * @return
    */
   private String spReplaceSqlContent(String suitContent, String regexp, int num, Map<String, List<String>> queryFilterMap, Map<String, List<String>> residueQueryFilterMap) {
   private String spReplaceSqlContent(String suitContent, String regexp, int num, Map<
         String, List<String>> queryFilterMap, Map<String, List<String>> residueQueryFilterMap) {
      List<String> innerSuitList = getSuitContent(suitContent, regexp);
      String curField;
      String filter;
@@ -757,7 +888,9 @@
    * @param queryFilterMap
    * @param curFieldName
    */
   private void spDealFilterForLastYear(Map<String, List<String>> tempQueryFilterMap, Map<String, List<String>> queryFilterMap, String curFieldName) {
   private void spDealFilterForLastYear
   (Map<String, List<String>> tempQueryFilterMap, Map<String, List<String>> queryFilterMap, String
         curFieldName) {
      List<String> paramList = tempQueryFilterMap.get(curFieldName);
      for (int i = 0; i < paramList.size(); i++) {
         paramList.set(i, paramList.get(i).replace("str_to_date(", "date_add(str_to_date(")
@@ -778,7 +911,9 @@
    * @param queryFilterMap
    * @param curFieldName
    */
   private void spDealFilterForPrePeriod(Map<String, List<String>> tempQueryFilterMap, Map<String, List<String>> queryFilterMap, String curFieldName) {
   private void spDealFilterForPrePeriod
   (Map<String, List<String>> tempQueryFilterMap, Map<String, List<String>> queryFilterMap, String
         curFieldName) {
      List<String> paramList = tempQueryFilterMap.get(curFieldName);
      String[] timeArr = paramList.get(0).split("~");
      try {
@@ -811,7 +946,8 @@
    * @param dataList
    * @return
    */
   private Set<String> getFieldAndSpTimeStatisticsTypeSet(Set<String> baseFieldSet, Map<String, Map<String, JSONObject>> spTimeStatisticsFieldMap, List<JSONObject> dataList) {
   private Set<String> getFieldAndSpTimeStatisticsTypeSet
   (Set<String> baseFieldSet, Map<String, Map<String, JSONObject>> spTimeStatisticsFieldMap, List<JSONObject> dataList) {
      Set<String> spTimeStatisticsTypeSet = Sets.newHashSet();
      JSONObject curFieldObj;
      String fieldName;
@@ -957,7 +1093,8 @@
    * @param locationType            位置类型,head-头部,tail-尾部
    * @return
    */
   public StringBuilder getTitleHtml(List<JSONObject> list, int totalColCount, Map<String, Set<String>> headAndTailTitleDataMap, String locationType) {
   public StringBuilder getTitleHtml(List<JSONObject> list, int totalColCount, Map<
         String, Set<String>> headAndTailTitleDataMap, String locationType) {
      StringBuilder html = new StringBuilder(1024);
      int colspan;
      int preRow = 0;
@@ -1017,6 +1154,79 @@
   }
   /**
    * 报表-解析-获取头部或者尾部标题Html
    *
    * @param list                    报表配置信息,缓存list
    * @param totalColCount           总列数
    * @param headAndTailTitleDataMap 头部、尾部标题区数据字段map
    * @param locationType            位置类型,head-头部,tail-尾部
    * @return
    */
   public List<List<ReportColumn>> getTitle(List<JSONObject> list, int totalColCount, Map<
         String, Set<String>> headAndTailTitleDataMap, String locationType) {
      List<List<ReportColumn>> row = new ArrayList<>();
//      StringBuilder html = new StringBuilder(1024);
      int colspan;
      int preRow = 0;
      int preCol = 0;
      int curRow;
      int curCol;
      String value;
//      String style;
      List<ReportColumn> reportColumns = new ArrayList<>();
      for (JSONObject singleObj : list) {
         curRow = singleObj.getIntValue(CmnConst.ATTR_Y);
         curCol = singleObj.getIntValue(CmnConst.ATTR_X);
         colspan = singleObj.getIntValue(CmnConst.ATTR_COLSPAN);
         colspan = colspan < 0 ? totalColCount : Math.max(1, colspan);
         value = replaceFormDataAndSysData(singleObj.getString(CmnConst.ATTR_SHOW_NAME), headAndTailTitleDataMap, singleObj);
         value = value == null ? "" : value;
//         if ("1".equals(singleObj.getString(CmnConst.ATTR_IS_TITLE))) {
//            style = " class=\"" + CmnConst.CLASS_TR_REPORT_TITLE + "\"";
//         } else {
//            if ("head".equals(locationType)) {
//               style = " class=\"" + CmnConst.CLASS_TR_HEAD + "\"";
//            } else {
//               style = " class=\"" + CmnConst.CLASS_TR_TAIL + "\"";
//            }
//         }
         if (preRow < curRow) {
            if(!reportColumns.isEmpty()){
               row.add(reportColumns);
               reportColumns=new ArrayList<>();
            }
//            if (preRow != 0) {
//               row.add(getAimNumTdPlaceholderColumn(totalColCount - preCol, 1));
//            }
//            if (preRow == 0 && preCol == 0 && preCol < curCol - 1) {
//               row.add(getAimNumTdPlaceholderColumn(curCol - preCol - 1, 1));
//            }
            preCol = curCol;
         }
         if (preCol < curCol - 1) {
            row.add(getAimNumTdPlaceholderColumn(curCol - preCol - 1, 1));
         }
         if ("1".equals(singleObj.getString(CmnConst.ATTR_IS_TITLE))) {
            colspan = totalColCount;
         }
         ReportColumn column = new ReportColumn();
         column.setColspan(colspan);
         column.setContent(value);
         reportColumns.add(column);
         preRow = curRow;
         preCol = curCol + singleObj.getIntValue(CmnConst.ATTR_COLSPAN) - 1;
         if ("1".equals(singleObj.getString(CmnConst.ATTR_IS_TITLE))) {
            preCol = totalColCount;
         }
      }
      row.add(reportColumns);
//      reportColumns.addAll(getAimNumTdPlaceholderColumn(totalColCount - preCol, 1));
//      row.add();
      return row;
   }
   /**
    * 获取指定数据集中包含的数据区字段集合
    *
    * @param list 指定数据集合
@@ -1051,7 +1261,8 @@
    * @param lastStageFlag          是否末级(数据区分组字段末级和分组表头区字段都是末级才为末级)
    * @return
    */
   public JSONObject getStatisticsValueObj(JSONObject valueJsonObject, JSONObject dataAreaFieldConfigObj, String actualValue, String type, boolean lastStageFlag) {
   public JSONObject getStatisticsValueObj(JSONObject valueJsonObject, JSONObject dataAreaFieldConfigObj, String
         actualValue, String type, boolean lastStageFlag) {
      if (valueJsonObject == null) {
         valueJsonObject = new JSONObject();
      }
@@ -1112,7 +1323,8 @@
    * @param set
    * @param recordFse
    */
   public void getHeadAndTailTitleDataMap(Map<String, Set<String>> headAndTailTitleDataMap, Set<String> set, FieldSetEntity recordFse) {
   public void getHeadAndTailTitleDataMap
   (Map<String, Set<String>> headAndTailTitleDataMap, Set<String> set, FieldSetEntity recordFse) {
      for (String fieldName : set) {
         headAndTailTitleDataMap.computeIfAbsent(fieldName, k -> Sets.newLinkedHashSet()).add(recordFse.getString(fieldName));
      }
@@ -1254,6 +1466,10 @@
      return dealedValueSb.toString();
   }
   public int dealColumnWidth(JSONObject dataAreaFieldConfigObj) {
      return NumberUtil.isNumber(dataAreaFieldConfigObj.getString(CmnConst.ATTR_WIDTH)) ? NumberUtil.parseInt(dataAreaFieldConfigObj.getString(CmnConst.ATTR_WIDTH)) : 0;
   }
   /**
    * 获取td的属性
    *
@@ -1333,7 +1549,8 @@
    * @param singleObj
    * @return
    */
   public String replaceFormDataAndSysData(String str, Map<String, Set<String>> headAndTailTitleDataMap, JSONObject singleObj) {
   public String replaceFormDataAndSysData(String
                                       str, Map<String, Set<String>> headAndTailTitleDataMap, JSONObject singleObj) {
      if (StringUtils.isEmpty(str)) {
         return "";
      }
@@ -1500,6 +1717,30 @@
    * @param num
    * @return
    */
   public List<ReportColumn> getAimNumTdPlaceholderColumn(int num, int type) {
      List<ReportColumn> columns = new ArrayList<>();
      if (num <= 0) {
         return columns;
      }
      if (type == 0) {
         for (int i = 0; i < num; i++) {
            columns.add(new ReportColumn());
         }
      } else {
         ReportColumn column = new ReportColumn();
         column.setColspan(num);
         columns.add(column);
      }
      return columns;
   }
   /**
    * 获取指定个数的td占位
    *
    * @param num
    * @return
    */
   public String getAimNumTdPlaceholder(int num, int type) {
      StringBuilder result = new StringBuilder(64);
      if (num <= 0) {
@@ -1557,7 +1798,8 @@
    * @param type      类型:1-获取目标属性,其他-排除目标属性
    * @return
    */
   public JSONObject extendJSONObject(JSONObject aimObj, JSONObject sourceObj, Collection<String> aimAttr, int type) {
   public JSONObject extendJSONObject(JSONObject aimObj, JSONObject sourceObj, Collection<String> aimAttr,
                              int type) {
      if (aimObj == null) {
         aimObj = new JSONObject();
      }