Browse Source

feature 代码提交

xiahan 1 year ago
parent
commit
c4a7fb5e13

+ 45 - 3
bs-common/pom.xml

@@ -33,12 +33,54 @@
             <groupId>com.rongwei</groupId>
             <artifactId>rw-admin-common</artifactId>
             <version>1.1-SNAPSHOT</version>
+            <exclusions>
+                <exclusion>
+                    <groupId>commons-io</groupId>
+                    <artifactId>commons-io</artifactId>
+                </exclusion>
+            </exclusions>
         </dependency>
         <dependency>
-            <groupId>org.apache.poi</groupId>
-            <artifactId>poi-ooxml</artifactId>
-            <version>5.2.0</version>
+            <groupId>com.alibaba</groupId>
+            <artifactId>easyexcel</artifactId>
+            <version>3.3.2</version>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>easyexcel-core</artifactId>
+            <version>3.3.2</version>
             <scope>compile</scope>
         </dependency>
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>easyexcel-core</artifactId>
+            <version>3.3.2</version>
+            <scope>compile</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-test</artifactId>
+        </dependency>
+<!--        <dependency>-->
+<!--            <groupId>commons-io</groupId>-->
+<!--            <artifactId>commons-io</artifactId>-->
+<!--            <version>2.11.0</version>-->
+<!--        </dependency>-->
+<!--        <dependency>-->
+<!--            <groupId>org.apache.xmlbeans</groupId>-->
+<!--            <artifactId>xmlbeans</artifactId>-->
+<!--            <version>5.1.0</version>-->
+<!--        </dependency>-->
+<!--        <dependency>-->
+<!--            <groupId>org.apache.poi</groupId>-->
+<!--            <artifactId>poi-ooxml</artifactId>-->
+<!--            <version>5.2.0</version>-->
+<!--            <scope>compile</scope>-->
+<!--        </dependency>-->
+<!--        <dependency>-->
+<!--            <groupId>org.apache.poi</groupId>-->
+<!--            <artifactId>poi-ooxml-schemas</artifactId>-->
+<!--            <version>3.17</version>-->
+<!--        </dependency>-->
     </dependencies>
 </project>

+ 78 - 0
bs-common/src/main/java/com/rongwei/safecommon/config/CustomCellWriteWidthConfig.java

@@ -0,0 +1,78 @@
+package com.rongwei.safecommon.config;
+
+import com.alibaba.excel.enums.CellDataTypeEnum;
+import com.alibaba.excel.metadata.Head;
+import com.alibaba.excel.metadata.data.CellData;
+import com.alibaba.excel.metadata.data.WriteCellData;
+import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
+import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
+import org.apache.commons.collections4.CollectionUtils;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.Sheet;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * CustomCellWriteWidthConfig class
+ *
+ * @author XH
+ * @date 2024/02/02
+ */
+public class CustomCellWriteWidthConfig extends AbstractColumnWidthStyleStrategy {
+    private final Map<Integer, Map<Integer, Integer>> CACHE = new HashMap<>();
+    @Override
+    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer integer, Boolean isHead) {
+        boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
+        if (needSetWidth) {
+            Map<Integer, Integer> maxColumnWidthMap = CACHE.computeIfAbsent(writeSheetHolder.getSheetNo(), k -> new HashMap<>());
+
+            Integer columnWidth = this.dataLength(cellDataList, cell, isHead);
+            // 单元格文本长度大于60换行
+            if (columnWidth >= 0) {
+                if (columnWidth > 60) {
+                    columnWidth = 60;
+                }
+                Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
+                if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
+                    maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
+                    Sheet sheet = writeSheetHolder.getSheet();
+                    sheet.setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
+                }
+            }
+        }
+    }
+    /**
+     * 计算长度
+     * @param cellDataList
+     * @param cell
+     * @param isHead
+     * @return
+     */
+    private Integer dataLength(List<WriteCellData<?>> cellDataList, Cell cell, Boolean isHead) {
+        if (isHead) {
+            return cell.getStringCellValue().getBytes().length;
+        } else {
+            CellData<?> cellData = cellDataList.get(0);
+            CellDataTypeEnum type = cellData.getType();
+            if (type == null) {
+                return -1;
+            } else {
+                switch (type) {
+                    case STRING:
+                        // 换行符(数据需要提前解析好)
+                        int index = cellData.getStringValue().indexOf("\n");
+                        return index != -1 ?
+                                cellData.getStringValue().substring(0, index).getBytes().length + 1 : cellData.getStringValue().getBytes().length + 1;
+                    case BOOLEAN:
+                        return cellData.getBooleanValue().toString().getBytes().length;
+                    case NUMBER:
+                        return cellData.getNumberValue().toString().getBytes().length;
+                    default:
+                        return -1;
+                }
+            }
+        }
+    }
+}

+ 168 - 168
bs-common/src/main/java/com/rongwei/safecommon/utils/CommonEasyExcelUtils.java

@@ -40,173 +40,173 @@ import static com.rongwei.safecommon.utils.SaveConstans.DatePattern.DATE_PATTERN
  */
 @Component
 public class CommonEasyExcelUtils {
-    private static final Logger log = LoggerFactory.getLogger(CommonEasyExcelUtils.class.getClass().getName());
-    private static final int MAX_COLUMN_WIDTH = 255 * 256;
-    @Autowired
-    private SysDictDao autoSysDictDao;
-
-    private static SysDictDao sysDictDao;
-    private static SysFileFolderDo sysFileFolderDo;
-
-
-    @PostConstruct
-    public void init() {
-        sysDictDao = autoSysDictDao;
-    }
-
-    private static final Map<String, String> CONTENT_TYPE_MAP = new HashMap<String, String>(4) {{
-        put(SaveConstans.FileSuffix.XLS, SaveConstans.ContentType.XLS);
-        put(SaveConstans.FileSuffix.XLSX, SaveConstans.ContentType.XLSX);
-
-    }};
-
-    /**
-     * 生成excel文件
-     *
-     * @param exportExcelCommonDTO
-     * @param dataList
-     * @param <T>
-     */
-    public static <T> void exportExcelUtil(ExportExcelCommonVo exportExcelCommonDTO, List<T> dataList) {
-        log.info("开始导出excel");
-        // excel文件名称
-        String excelFileName = exportExcelCommonDTO.getExcelFileName();
-        // excel 文件后缀
-        String excelFileSuffix = exportExcelCommonDTO.getExcelFileSuffix();
-        // 数据字典处理
-        List<CommonGenerateExcelVo> excelFieldDescDTOList = getDictData(exportExcelCommonDTO.getExcelFieldDescDTOList());
-
-        String dateStr = new SimpleDateFormat(DATE_PATTERN_YMD).format(new Date());
-
-        String fileName = StringUtils.isBlank(excelFileName) ? dateStr : excelFileName + dateStr;
-        try (FileOutputStream outputStream = new FileOutputStream(new File("指定目录/文件名"))) {
-//            OutputStream outputStream = response.getOutputStream();
-//            response.setHeader("Content-disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
-//            response.setContentType(String.format("%s;%s", CONTENT_TYPE_MAP.get(excelFileSuffix), "charset=UTF-8"));
-            XSSFWorkbook excelWorkBook = new XSSFWorkbook();
-            /****************************设置单元格居中样式*********************************/
-            XSSFCellStyle centerStyle = excelWorkBook.createCellStyle();
-            // 水平居中
-            centerStyle.setAlignment(HorizontalAlignment.CENTER);
-            // 垂直居中
-            centerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
-
-            // 创建sheet
-            XSSFSheet sheet = excelWorkBook.createSheet(StringUtils.isBlank(excelFileName) ? "sheet1" : excelFileName);
-            /********************************创建标题行***********************************/
-//            if(StringUtils.isNotBlank(excelFileName)){
-//                XSSFRow firstRow = sheet.createRow(0);
-//                XSSFCell firstRowCell = firstRow.createCell(0);
-//                firstRowCell.setCellValue(excelFileName);
-//                firstRowCell.setCellStyle(centerStyle);
+//    private static final Logger log = LoggerFactory.getLogger(CommonEasyExcelUtils.class.getClass().getName());
+//    private static final int MAX_COLUMN_WIDTH = 255 * 256;
+//    @Autowired
+//    private SysDictDao autoSysDictDao;
+//
+//    private static SysDictDao sysDictDao;
+//    private static SysFileFolderDo sysFileFolderDo;
+//
+//
+//    @PostConstruct
+//    public void init() {
+//        sysDictDao = autoSysDictDao;
+//    }
+//
+//    private static final Map<String, String> CONTENT_TYPE_MAP = new HashMap<String, String>(4) {{
+//        put(SaveConstans.FileSuffix.XLS, SaveConstans.ContentType.XLS);
+//        put(SaveConstans.FileSuffix.XLSX, SaveConstans.ContentType.XLSX);
+//
+//    }};
+//
+//    /**
+//     * 生成excel文件
+//     *
+//     * @param exportExcelCommonDTO
+//     * @param dataList
+//     * @param <T>
+//     */
+//    public static <T> void exportExcelUtil(ExportExcelCommonVo exportExcelCommonDTO, List<T> dataList) {
+//        log.info("开始导出excel");
+//        // excel文件名称
+//        String excelFileName = exportExcelCommonDTO.getExcelFileName();
+//        // excel 文件后缀
+//        String excelFileSuffix = exportExcelCommonDTO.getExcelFileSuffix();
+//        // 数据字典处理
+//        List<CommonGenerateExcelVo> excelFieldDescDTOList = getDictData(exportExcelCommonDTO.getExcelFieldDescDTOList());
+//
+//        String dateStr = new SimpleDateFormat(DATE_PATTERN_YMD).format(new Date());
+//
+//        String fileName = StringUtils.isBlank(excelFileName) ? dateStr : excelFileName + dateStr;
+//        try (FileOutputStream outputStream = new FileOutputStream(new File("指定目录/文件名"))) {
+////            OutputStream outputStream = response.getOutputStream();
+////            response.setHeader("Content-disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
+////            response.setContentType(String.format("%s;%s", CONTENT_TYPE_MAP.get(excelFileSuffix), "charset=UTF-8"));
+//            XSSFWorkbook excelWorkBook = new XSSFWorkbook();
+//            /****************************设置单元格居中样式*********************************/
+//            XSSFCellStyle centerStyle = excelWorkBook.createCellStyle();
+//            // 水平居中
+//            centerStyle.setAlignment(HorizontalAlignment.CENTER);
+//            // 垂直居中
+//            centerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
+//
+//            // 创建sheet
+//            XSSFSheet sheet = excelWorkBook.createSheet(StringUtils.isBlank(excelFileName) ? "sheet1" : excelFileName);
+//            /********************************创建标题行***********************************/
+////            if(StringUtils.isNotBlank(excelFileName)){
+////                XSSFRow firstRow = sheet.createRow(0);
+////                XSSFCell firstRowCell = firstRow.createCell(0);
+////                firstRowCell.setCellValue(excelFileName);
+////                firstRowCell.setCellStyle(centerStyle);
+////            }
+//
+//            /********************************创建描述行***********************************/
+//            List<String> fieldDescList = excelFieldDescDTOList.stream().map(CommonGenerateExcelVo::getFiledDesc).collect(Collectors.toList());
+//            XSSFCell cell;
+//            XSSFRow descRow = sheet.createRow(0);
+//            for (int i = 0; i < fieldDescList.size(); i++) {
+//                cell = descRow.createCell(i);
+//                cell.setCellValue(fieldDescList.get(i));
+//                cell.setCellType(CellType.STRING);
+//                cell.setCellStyle(centerStyle);
 //            }
-
-            /********************************创建描述行***********************************/
-            List<String> fieldDescList = excelFieldDescDTOList.stream().map(CommonGenerateExcelVo::getFiledDesc).collect(Collectors.toList());
-            XSSFCell cell;
-            XSSFRow descRow = sheet.createRow(0);
-            for (int i = 0; i < fieldDescList.size(); i++) {
-                cell = descRow.createCell(i);
-                cell.setCellValue(fieldDescList.get(i));
-                cell.setCellType(CellType.STRING);
-                cell.setCellStyle(centerStyle);
-            }
-            /********************************创建内容行***********************************/
-            CommonGenerateExcelVo excelFieldDescDTO;
-            String valueStr = null;
-            Object fileValue;
-            Function getFunction;
-            DataFormat format = excelWorkBook.createDataFormat();
-            // 样式
-            XSSFCellStyle commonStyle = centerStyle;
-            commonStyle.setDataFormat(format.getFormat("@"));
-            XSSFRow valueRow;
-            SimpleDateFormat simpleDateFormat;
-            Map<String, Object> enumMap;
-            for (int j = 0; j < dataList.size(); j++) {
-                valueRow = sheet.createRow(j + 1);
-                Object data = dataList.get(j);
-                boolean isNumber;
-                for (int i = 0; i < excelFieldDescDTOList.size(); i++) {
-                    cell = valueRow.createCell(i);
-                    isNumber = false;
-                    excelFieldDescDTO = excelFieldDescDTOList.get(i);
-                    getFunction = excelFieldDescDTO.getGetOrgNameFunction();
-                    if (getFunction != null) {
-                        fileValue = getFunction.apply(data);
-                    } else {
-                        fileValue = excelFieldDescDTO.getFileValue();
-                    }
-                    String datePattern = excelFieldDescDTO.getDatePattern();
-                    if (fileValue == null) {
-                        valueStr = "";
-                    } else if (fileValue instanceof java.util.Date) {
-                        simpleDateFormat = new SimpleDateFormat(StringUtils.isBlank(datePattern) ? DATE_PATTERN_YMD : datePattern);
-                        // 日期格式处理
-                        valueStr = simpleDateFormat.format(fileValue);
-                    } else if (excelFieldDescDTO.getCustomDictMap() != null && !excelFieldDescDTO.getCustomDictMap().isEmpty()) {
-                        // 数据字典处理
-                        enumMap = excelFieldDescDTO.getCustomDictMap();
-                        valueStr = enumMap == null ? "" : enumMap.getOrDefault(fileValue.toString(), "").toString();
-                    } else if (fileValue instanceof java.math.BigDecimal) {
-                        // 特殊处理 小数位数都是0的情况下 只显示整数部分
-                        valueStr = ((BigDecimal) fileValue).stripTrailingZeros().toPlainString();
-                        isNumber = true;
-                    } else if (fileValue instanceof java.lang.Integer || fileValue instanceof java.lang.Long) {
-                        valueStr = fileValue.toString();
-                        isNumber = true;
-                    } else {
-                        isNumber = false;
-                        valueStr = fileValue.toString();
-                    }
-                    if (isNumber) {
-                        cell.setCellValue(Double.parseDouble(valueStr));
-                        cell.setCellStyle(centerStyle);
-                    } else {
-                        cell.setCellStyle(commonStyle);
-                        cell.setCellValue(valueStr);
-                    }
-                    cell.setCellType(isNumber ? CellType.NUMERIC : CellType.STRING);
-
-                }
-            }
-            for (int i = 0; i < fieldDescList.size(); i++) {
-                sheet.autoSizeColumn(i, true);
-                if (sheet.getColumnWidth(i) * 17 / 10 < MAX_COLUMN_WIDTH) {
-                    sheet.setColumnWidth(i, Math.max(sheet.getColumnWidth(i) * 17 / 10, 3000));
-                } else {
-                    sheet.setColumnWidth(i, 6000);
-                }
-                sheet.setDefaultColumnStyle(i, centerStyle);
-            }
-
-            excelWorkBook.write(outputStream);
-        } catch (Exception e) {
-            log.error("excel导出异常");
-            e.printStackTrace();
-            throw new RuntimeException("excel导出失败!请联系系统管理员");
-        }
-    }
-
-    public static List<CommonGenerateExcelVo> getDictData(List<CommonGenerateExcelVo> excelFieldDescDTOList) {
-        if (excelFieldDescDTOList.isEmpty()) {
-            return excelFieldDescDTOList;
-        }
-        List<String> dictTypeList = excelFieldDescDTOList.stream()
-                .map(info -> info.getDictType())
-                .filter(StringUtils::isNotBlank)
-                .distinct()
-                .collect(Collectors.toList());
-        if (dictTypeList.isEmpty()) {
-            return excelFieldDescDTOList;
-        }
-        List<SysDictDo> sysDictDos = sysDictDao.selectList(new LambdaQueryWrapper<SysDictDo>().eq(BaseDo::getDeleted, "0").in(SysDictDo::getDicttype, dictTypeList));
-        excelFieldDescDTOList.forEach(data -> {
-            if (StringUtils.isNotBlank(data.getDictType())) {
-                data.setCustomDictMap(sysDictDos.stream().filter(dict -> dict.getDicttype().equals(data.getDictType()))
-                        .collect(Collectors.toMap(SysDictDo::getValue, SysDictDo::getName)));
-            }
-        });
-        return excelFieldDescDTOList;
-    }
+//            /********************************创建内容行***********************************/
+//            CommonGenerateExcelVo excelFieldDescDTO;
+//            String valueStr = null;
+//            Object fileValue;
+//            Function getFunction;
+//            DataFormat format = excelWorkBook.createDataFormat();
+//            // 样式
+//            XSSFCellStyle commonStyle = centerStyle;
+//            commonStyle.setDataFormat(format.getFormat("@"));
+//            XSSFRow valueRow;
+//            SimpleDateFormat simpleDateFormat;
+//            Map<String, Object> enumMap;
+//            for (int j = 0; j < dataList.size(); j++) {
+//                valueRow = sheet.createRow(j + 1);
+//                Object data = dataList.get(j);
+//                boolean isNumber;
+//                for (int i = 0; i < excelFieldDescDTOList.size(); i++) {
+//                    cell = valueRow.createCell(i);
+//                    isNumber = false;
+//                    excelFieldDescDTO = excelFieldDescDTOList.get(i);
+//                    getFunction = excelFieldDescDTO.getGetOrgNameFunction();
+//                    if (getFunction != null) {
+//                        fileValue = getFunction.apply(data);
+//                    } else {
+//                        fileValue = excelFieldDescDTO.getFileValue();
+//                    }
+//                    String datePattern = excelFieldDescDTO.getDatePattern();
+//                    if (fileValue == null) {
+//                        valueStr = "";
+//                    } else if (fileValue instanceof java.util.Date) {
+//                        simpleDateFormat = new SimpleDateFormat(StringUtils.isBlank(datePattern) ? DATE_PATTERN_YMD : datePattern);
+//                        // 日期格式处理
+//                        valueStr = simpleDateFormat.format(fileValue);
+//                    } else if (excelFieldDescDTO.getCustomDictMap() != null && !excelFieldDescDTO.getCustomDictMap().isEmpty()) {
+//                        // 数据字典处理
+//                        enumMap = excelFieldDescDTO.getCustomDictMap();
+//                        valueStr = enumMap == null ? "" : enumMap.getOrDefault(fileValue.toString(), "").toString();
+//                    } else if (fileValue instanceof java.math.BigDecimal) {
+//                        // 特殊处理 小数位数都是0的情况下 只显示整数部分
+//                        valueStr = ((BigDecimal) fileValue).stripTrailingZeros().toPlainString();
+//                        isNumber = true;
+//                    } else if (fileValue instanceof java.lang.Integer || fileValue instanceof java.lang.Long) {
+//                        valueStr = fileValue.toString();
+//                        isNumber = true;
+//                    } else {
+//                        isNumber = false;
+//                        valueStr = fileValue.toString();
+//                    }
+//                    if (isNumber) {
+//                        cell.setCellValue(Double.parseDouble(valueStr));
+//                        cell.setCellStyle(centerStyle);
+//                    } else {
+//                        cell.setCellStyle(commonStyle);
+//                        cell.setCellValue(valueStr);
+//                    }
+//                    cell.setCellType(isNumber ? CellType.NUMERIC : CellType.STRING);
+//
+//                }
+//            }
+//            for (int i = 0; i < fieldDescList.size(); i++) {
+//                sheet.autoSizeColumn(i, true);
+//                if (sheet.getColumnWidth(i) * 17 / 10 < MAX_COLUMN_WIDTH) {
+//                    sheet.setColumnWidth(i, Math.max(sheet.getColumnWidth(i) * 17 / 10, 3000));
+//                } else {
+//                    sheet.setColumnWidth(i, 6000);
+//                }
+//                sheet.setDefaultColumnStyle(i, centerStyle);
+//            }
+//
+//            excelWorkBook.write(outputStream);
+//        } catch (Exception e) {
+//            log.error("excel导出异常");
+//            e.printStackTrace();
+//            throw new RuntimeException("excel导出失败!请联系系统管理员");
+//        }
+//    }
+//
+//    public static List<CommonGenerateExcelVo> getDictData(List<CommonGenerateExcelVo> excelFieldDescDTOList) {
+//        if (excelFieldDescDTOList.isEmpty()) {
+//            return excelFieldDescDTOList;
+//        }
+//        List<String> dictTypeList = excelFieldDescDTOList.stream()
+//                .map(info -> info.getDictType())
+//                .filter(StringUtils::isNotBlank)
+//                .distinct()
+//                .collect(Collectors.toList());
+//        if (dictTypeList.isEmpty()) {
+//            return excelFieldDescDTOList;
+//        }
+//        List<SysDictDo> sysDictDos = sysDictDao.selectList(new LambdaQueryWrapper<SysDictDo>().eq(BaseDo::getDeleted, "0").in(SysDictDo::getDicttype, dictTypeList));
+//        excelFieldDescDTOList.forEach(data -> {
+//            if (StringUtils.isNotBlank(data.getDictType())) {
+//                data.setCustomDictMap(sysDictDos.stream().filter(dict -> dict.getDicttype().equals(data.getDictType()))
+//                        .collect(Collectors.toMap(SysDictDo::getValue, SysDictDo::getName)));
+//            }
+//        });
+//        return excelFieldDescDTOList;
+//    }
 }

+ 60 - 0
bs-common/src/main/java/com/rongwei/safecommon/utils/ExportExceByEasyExcel.java

@@ -0,0 +1,60 @@
+package com.rongwei.safecommon.utils;
+
+import cn.hutool.json.JSONObject;
+import cn.hutool.json.JSONUtil;
+import com.alibaba.excel.EasyExcel;
+import com.alibaba.excel.ExcelWriter;
+import com.alibaba.excel.write.metadata.WriteSheet;
+import com.rongwei.rwcommon.base.R;
+import com.rongwei.safecommon.config.CustomCellWriteWidthConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.mock.web.MockMultipartFile;
+import org.springframework.stereotype.Component;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.util.List;
+
+import static com.rongwei.safecommon.utils.SaveConstans.NotifyTitle.WEEK_HIDDEN_DANGER_TASK;
+
+/**
+ * ExportExceByEasyExcel class
+ *
+ * @author XH
+ * @date 2024/02/02
+ */
+@Component
+public class ExportExceByEasyExcel {
+
+    private static final Logger log = LoggerFactory.getLogger(ExportExceByEasyExcel.class.getName());
+
+    public static <T> String genarteExcel(String file, String originalFilename, String notifyId, List<T> data, Class<T> className) {
+        String returnStr = "";
+        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();) {
+            ExcelWriter excelWriter = EasyExcel.write(byteArrayOutputStream).build();
+            WriteSheet maintainSheet = EasyExcel.writerSheet(0, WEEK_HIDDEN_DANGER_TASK)
+                    .head(className)
+                    .registerWriteHandler(new CustomCellWriteWidthConfig())
+                    .build();
+            excelWriter.write(data, maintainSheet);
+            excelWriter.finish();
+
+            byte[] byteArray = byteArrayOutputStream.toByteArray();
+            MultipartFile multipartFile = new MockMultipartFile(file,
+                    originalFilename,
+                    SaveConstans.ContentType.XLSX, byteArray);
+            R upload = CXCommonUtils.upload(multipartFile, notifyId);
+
+            if ("200".equals(upload.getCode())) {
+                JSONObject jsonObject = JSONUtil.parseObj(upload.getData());
+                returnStr = jsonObject.get("filename").toString() + "-;-" + jsonObject.get("id").toString();
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+            log.error("文件生成异常");
+        }
+        return returnStr;
+    }
+}

+ 7 - 0
cx-safe-check/cx-save-check-common/src/main/java/com/rongwei/sfcommon/sys/dao/SaveCheckCommonDao.java

@@ -20,5 +20,12 @@ public interface SaveCheckCommonDao {
     SysUserDo getSafetyManager();
 
     List<UserMailOrgVo> getUserInfoByDeptCode(@Param("roleCode") String roleCode);
+
     List<UserMailOrgVo> getSafetyPromoter(@Param("deptIds") List<String> deptIds);
+
+    void updateNotifyState(@Param("notifyType") String notifyType,@Param("tenantId") String tenantId);
+
+    List<String> getUserIdByRoleCodeAndOrgIdAndTenantId(@Param("roleCodes") List<String> roleCode,
+                                                        @Param("orgIds") List<String> orgIds,
+                                                        @Param("tenantId") String tenantId);
 }

+ 3 - 0
cx-safe-check/cx-save-check-common/src/main/java/com/rongwei/sfcommon/sys/service/SafeCheckSendNotifyService.java

@@ -30,4 +30,7 @@ public interface SafeCheckSendNotifyService {
     R sendBackSystem(Map<String, String> map);
 
     R submitSystem(Map<String, String> map);
+
+
+    R hiddenDangerTask(Map<String, String> map);
 }

+ 167 - 7
cx-safe-check/cx-save-check-common/src/main/java/com/rongwei/sfcommon/sys/service/impl/SafeCheckSendNotifyServiceImpl.java

@@ -1,30 +1,54 @@
 package com.rongwei.sfcommon.sys.service.impl;
 
+import cn.hutool.json.JSONObject;
+import cn.hutool.json.JSONUtil;
+import com.alibaba.excel.EasyExcel;
+import com.alibaba.excel.ExcelWriter;
+import com.alibaba.excel.write.metadata.WriteSheet;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.rongwe.scentity.domian.HiddenDangerTrackDo;
 import com.rongwe.scentity.domian.ThemeCheckDo;
 import com.rongwe.scentity.domian.ThemeCheckItemDo;
-import com.rongwe.scentity.domian.ThemeCheckWorkparkDo;
+import com.rongwe.scentity.vo.ExportHiddenDangerVo;
+import com.rongwei.rwadmincommon.system.domain.SysDictDo;
+import com.rongwei.rwadmincommon.system.service.SysDictService;
 import com.rongwei.rwcommon.base.BaseDo;
 import com.rongwei.rwcommon.base.R;
+import com.rongwei.rwcommon.utils.SecurityUtil;
 import com.rongwei.rwcommon.utils.StringUtils;
 import com.rongwei.safecommon.utils.CXCommonUtils;
+import com.rongwei.safecommon.utils.ExportExceByEasyExcel;
+import com.rongwei.safecommon.utils.SaveConstans;
 import com.rongwei.sfcommon.sys.dao.DangerousDao;
+import com.rongwei.sfcommon.sys.dao.SaveCheckCommonDao;
 import com.rongwei.sfcommon.sys.service.SafeCheckSendNotifyService;
 import com.rongwei.sfcommon.sys.service.ThemeCheckItemService;
 import com.rongwei.sfcommon.sys.service.ThemeCheckService;
 import com.rongwei.sfcommon.sys.service.ThemeCheckWorkparkService;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.mock.web.MockMultipartFile;
 import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
 
+import java.io.ByteArrayOutputStream;
+import java.text.SimpleDateFormat;
+import java.time.DayOfWeek;
+import java.time.LocalDate;
 import java.util.*;
 import java.util.stream.Collectors;
 
+import static com.rongwei.safecommon.utils.SaveConstans.COMPANY_MAP;
 import static com.rongwei.safecommon.utils.SaveConstans.DEFAULT_SEPARATOR;
+import static com.rongwei.safecommon.utils.SaveConstans.DatePattern.DATE_PATTERN_YMD;
+import static com.rongwei.safecommon.utils.SaveConstans.DictType.*;
+import static com.rongwei.safecommon.utils.SaveConstans.FileSuffix.XLSX;
 import static com.rongwei.safecommon.utils.SaveConstans.NotifyContent.*;
 import static com.rongwei.safecommon.utils.SaveConstans.NotifyTitle.*;
 import static com.rongwei.safecommon.utils.SaveConstans.NotifyType.*;
+import static com.rongwei.safecommon.utils.SaveConstans.RoleCode.EDMS;
+import static com.rongwei.safecommon.utils.SaveConstans.RoleCode.HOED;
+import static com.rongwei.sfcommon.utils.MlConstants.DANGER_SOURCE_POINTCHECK;
 
 /**
  * SafeCheckSendNotifyServiceImpl class
@@ -76,12 +100,30 @@ public class SafeCheckSendNotifyServiceImpl implements SafeCheckSendNotifyServic
     @Autowired
     private ThemeCheckItemService themeCheckItemService;
 
+    @Autowired
+    private SaveCheckCommonDao saveCheckCommonDao;
+
+    @Autowired
+    private SysDictService sysDictService;
+
+
+    /**
+     * 生产
+     * 日常点巡检异常问题提醒 用来区分 消息提醒的角色
+     */
+    public static final String PRODUCTION = "production";
+    /**
+     * 维修
+     * 日常点巡检异常问题提醒 用来区分 消息提醒的角色
+     */
+    public static final String MAINTAIN = "maintain";
+
     @Override
     public void inspectionTasks() {
         // 获取所有待检查的检查任务
         List<ThemeCheckItemDo> prepare = themeCheckItemService.list(new LambdaQueryWrapper<ThemeCheckItemDo>()
                 .eq(BaseDo::getDeleted, "0").eq(ThemeCheckItemDo::getCheckstatus, "prepare"));
-        if(prepare.isEmpty()){
+        if (prepare.isEmpty()) {
             log.debug("暂无待检测的任务");
             return;
         }
@@ -271,22 +313,141 @@ public class SafeCheckSendNotifyServiceImpl implements SafeCheckSendNotifyServic
             title = VERIFICATION_MAIL_TITLE;
             String format = String.format(VERIFICATION_REMIND_TEMP, hiddenDangerTrackDo.getCode(),
                     hiddenDangerTrackDo.getHiddendangercontent());
-            context = String.format(VERIFICATION_REMIND_MAIL_CONTENT,format);
+            context = String.format(VERIFICATION_REMIND_MAIL_CONTENT, format);
         } else if ("40".equals(state)) {
             userId = Arrays.asList(hiddenDangerTrackDo.getSafetypromoterid().split(","));
             title = AFFIRM_MAIL_TITLE;
             String format = String.format(VERIFICATION_REMIND_TEMP, hiddenDangerTrackDo.getCode(),
                     hiddenDangerTrackDo.getHiddendangercontent());
-            context = String.format(AFFIRM_REMIND_MAIL_CONTENT,format);
+            context = String.format(AFFIRM_REMIND_MAIL_CONTENT, format);
         }
-        if (userId.size()==0){
+        if (userId.size() == 0) {
             log.error("无法找到接收人!");
         }
         CXCommonUtils.sendNotify(title,
-                context,null,userId,hiddenDangerTrackDo.getId(),DANGERTASKS);
+                context, null, userId, hiddenDangerTrackDo.getId(), DANGERTASKS);
         return R.ok();
     }
 
+    /**
+     * 点巡检隐患任务提醒
+     *
+     * @param map
+     * @return
+     */
+    @Override
+    public R hiddenDangerTask(Map<String, String> map) {
+        List<HiddenDangerTrackDo> hiddenDangerTrackDos = hiddenDangerTrackService.list(new LambdaQueryWrapper<HiddenDangerTrackDo>()
+                .eq(BaseDo::getDeleted, "0")
+                .eq(HiddenDangerTrackDo::getSource, "1")
+                .eq(HiddenDangerTrackDo::getDangersource, DANGER_SOURCE_POINTCHECK)
+                .last(" AND  DATEDIFF(NOW(),FINDTIME) BETWEEN 0 AND 7  "));
+        if (hiddenDangerTrackDos.isEmpty()) {
+            return R.ok();
+        }
+        LocalDate date = LocalDate.now(); // 获取当前日期
+        DayOfWeek dayOfWeek = date.getDayOfWeek(); // 获取日期对应的星期几
+        // 周五发送维修和生产提醒 周三发送生产提醒
+        if (dayOfWeek != DayOfWeek.WEDNESDAY && dayOfWeek != DayOfWeek.FRIDAY) {
+            return R.ok();
+        }
+        // 获取数据字典
+        List<SysDictDo> dicts = sysDictService.list(new LambdaQueryWrapper<SysDictDo>().eq(BaseDo::getDeleted, "0").in(SysDictDo::getDicttype,
+                TASK_SOURCE_TYPE, HIDDEN_DANGER_TYPE, TRACK_STATUS));
+        hiddenDangerTrackDos.forEach(info -> {
+            if (StringUtils.isNotBlank(info.getDangersource())) {
+                info.setDangersource(dicts.stream().filter(dict -> TASK_SOURCE_TYPE.equals(dict.getDicttype()) &&
+                                info.getDangersource().equals(dict.getValue())).map(SysDictDo::getName)
+                        .collect(Collectors.joining(",")));
+            }
+
+            if (StringUtils.isNotBlank(info.getHiddendangertype())) {
+                info.setHiddendangertype(dicts.stream().filter(dict -> HIDDEN_DANGER_TYPE.equals(dict.getDicttype()) &&
+                                info.getHiddendangertype().equals(dict.getValue())).map(SysDictDo::getName)
+                        .collect(Collectors.joining(",")));
+            }
+
+            if (StringUtils.isNotBlank(info.getStatus())) {
+                info.setStatus(dicts.stream().filter(dict -> TRACK_STATUS.equals(dict.getDicttype()) &&
+                                info.getStatus().equals(dict.getValue())).map(SysDictDo::getName)
+                        .collect(Collectors.joining(",")));
+            }
+        });
+
+        // 对业务数据按照厂区进行分组
+        Map<String, List<HiddenDangerTrackDo>> collect = hiddenDangerTrackDos.stream().collect(Collectors.groupingBy(HiddenDangerTrackDo::getTenantid));
+        collect.forEach((k, v) -> {
+            // 周五需要生成 维修提醒
+            if (DayOfWeek.WEDNESDAY == dayOfWeek) {
+                // 维修
+                sendNotify(HIDDEN_DANGER_TASK_MAINTAIN, k, v);
+
+            }
+            //周三和周五生成 生产提醒
+            sendNotify(HIDDEN_DANGER_TASK_PRODUCTION, k, v);
+        });
+        return R.ok();
+    }
+
+    /**
+     * 发送消息提醒
+     */
+    public void sendNotify(String notifyType, String tenantId, List<HiddenDangerTrackDo> dangerTrackDos) {
+        // 已读以往提醒信息
+        saveCheckCommonDao.updateNotifyState(notifyType, tenantId);
+
+        /****************************获取提醒人信息*******************************/
+        List<String> recipientIds = new ArrayList<>();
+        if (HIDDEN_DANGER_TASK_MAINTAIN.equals(notifyType)) {
+            // 维修 对应工厂的设备部部长 + 设备部维修主管
+            recipientIds = saveCheckCommonDao.getUserIdByRoleCodeAndOrgIdAndTenantId(Arrays.asList(HOED, EDMS), null, tenantId);
+        } else {
+            // 生产 根据 隐患地点 取对应部门车间的 车间主任、车间维修主管 角色中人员
+            List<String> orgId = dangerTrackDos.stream().map(HiddenDangerTrackDo::getDangerworkpark).distinct().collect(Collectors.toList());
+            if(!orgId.isEmpty()){
+                recipientIds.addAll(saveCheckCommonDao.getUserIdByRoleCodeAndOrgIdAndTenantId(Arrays.asList(HOED, EDMS), orgId, tenantId));
+            }
+            // 整改状态为“待整改”记录中的 指派跟踪人
+            recipientIds.addAll(dangerTrackDos.stream().filter(info -> "20".equals(info.getStatus()))
+                    .map(HiddenDangerTrackDo::getTrackuserid)
+                    .filter(StringUtils::isNotBlank)
+                    .distinct()
+                    .collect(Collectors.toList()));
+        }
+        if (recipientIds.isEmpty()) {
+            return;
+        }
+        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_PATTERN_YMD);
+        // 附件生成
+        List<ExportHiddenDangerVo> exportData = dangerTrackDos.stream().map((data) -> {
+            ExportHiddenDangerVo exportHiddenDangerVo = new ExportHiddenDangerVo();
+            exportHiddenDangerVo.setTenantId(COMPANY_MAP.get( data.getTenantid()));
+            exportHiddenDangerVo.setStatus(data.getStatus());
+            exportHiddenDangerVo.setCode(data.getCode());
+            exportHiddenDangerVo.setHiddendangertype(data.getHiddendangertype());
+            exportHiddenDangerVo.setHiddendangercontent(data.getHiddendangercontent());
+            exportHiddenDangerVo.setTrackusername(data.getTrackusername());
+            exportHiddenDangerVo.setRectificationdate(data.getRectificationdate() == null ? "" : simpleDateFormat.format(data.getRectificationdate()));
+            exportHiddenDangerVo.setCompletionschedule(data.getCompletionschedule());
+            exportHiddenDangerVo.setFinishdate(data.getFinishdate() == null ? "" : simpleDateFormat.format(data.getFinishdate()));
+            exportHiddenDangerVo.setDangersource(data.getDangersource());
+            return exportHiddenDangerVo;
+        }).collect(Collectors.toList());
+
+        // 消息提醒ID
+        String notifyId = SecurityUtil.getUUID();
+
+        String fileNameAndId = ExportExceByEasyExcel.genarteExcel("file",WEEK_HIDDEN_DANGER_TASK + simpleDateFormat.format(new Date()) + XLSX ,
+                notifyId, exportData, ExportHiddenDangerVo.class);
+        if(StringUtils.isBlank(fileNameAndId)){
+            return;
+        }
+        CXCommonUtils.sendNotify(notifyId, tenantId, WEEK_HIDDEN_DANGER_TASK,
+                String.format(HIDDEN_DANGER_TASK_CONTENT, dangerTrackDos.size()), fileNameAndId, recipientIds, null,
+                notifyType, false);
+    }
+
+
     /**
      * 隐患任务整改提醒
      *
@@ -294,7 +455,6 @@ public class SafeCheckSendNotifyServiceImpl implements SafeCheckSendNotifyServic
      * @return
      * @date 2023/12/20 9:54
      * @author shangmi
-     *
      */
 
     public void rectificationNotify(List<HiddenDangerTrackDo> hiddenDangerTrackList){

+ 34 - 0
cx-safe-check/cx-save-check-common/src/main/resources/mybatis/SaveCheckCommonDao.xml

@@ -64,4 +64,38 @@
             </foreach>
         </if>
     </select>
+    <update id="updateNotifyState">
+        update sys_notify_announce_user set READSTATE =1
+        <where>
+            ANNOUNCEID = (select ID from sys_notify_announce where NOTIFYTYPE =#{notifyType} and DELETED='0'
+            <if test="tenantId != null and tenantId != ''">
+                    and TENANTID =#{tenantId}
+            </if>
+            );
+        UPDATE sys_notify_announce SET DELETED='1' WHERE NOTIFYTYPE =#{notifyType}
+        </where>
+    </update>
+    <select id="getUserIdByRoleCodeAndOrgIdAndTenantId" resultType="java.lang.String">
+        select DISTINCT su.ID from sys_user su
+        left join sys_user_role sur on sur.USERID = su.ID and sur.DELETED='0'
+        left join sys_role sr on sr.ID = sur.ROLEID and sr.DELETED='0'
+        left join sys_user_org suo on sur.USERID = suo.USERID and suo.DELETED='0'
+        left join sys_organization so on suo.ORGID =so.ID and so.DELETED='0'
+        <where>
+            su.DELETED ='0'
+            AND FIND_IN_SET(#{tenantId},so.FULLPID)
+            <if test="roleCodes != null and roleCodes.size()>0">
+            AND sr.code in
+                <foreach collection="roleCodes" item="roleCode" open="(" close=")" separator=",">
+                    #{roleCode}
+                </foreach>
+            </if>
+            <if test="orgIds != null and orgIds.size()>0">
+                AND so.ID in
+                <foreach collection="orgIds" item="orgId" open="(" close=")" separator=",">
+                    #{orgId}
+                </foreach>
+            </if>
+        </where>
+    </select>
 </mapper>

+ 47 - 0
cx-safe-check/cx-save-check-entity/src/main/java/com/rongwe/scentity/vo/ExportHiddenDangerVo.java

@@ -0,0 +1,47 @@
+package com.rongwe.scentity.vo;
+
+import com.alibaba.excel.annotation.ExcelProperty;
+import com.alibaba.excel.annotation.write.style.ColumnWidth;
+import lombok.Data;
+
+/**
+ * ExportHiddenDangerVo class
+ *
+ * @author XH
+ * @date 2024/02/02
+ */
+@Data
+public class ExportHiddenDangerVo {
+    @ColumnWidth(20)
+    @ExcelProperty(value = "所属工厂", index = 0)
+    private String tenantId;
+    @ColumnWidth(10)
+    @ExcelProperty(value = "跟踪状态", index = 1)
+    private String status;
+
+    @ColumnWidth(14)
+    @ExcelProperty(value = "隐患任务编号", index = 2)
+    private String code;
+
+    @ExcelProperty(value = "隐患类型", index = 3)
+    private String hiddendangertype;
+    @ColumnWidth(40)
+    @ExcelProperty(value = "隐患内容", index = 4)
+    private String hiddendangercontent;
+
+    @ExcelProperty(value = "指派跟踪人", index = 5)
+    private String trackusername;
+
+    @ExcelProperty(value = "限整改日期", index = 6)
+    private String rectificationdate;
+
+    @ExcelProperty(value = "措施完成进度", index = 7)
+    private String completionschedule;
+
+    @ExcelProperty(value = "完成日期", index = 8)
+    private String finishdate;
+
+    @ExcelProperty(value = "隐患来源", index = 9)
+    private String dangersource;
+
+}

+ 8 - 0
cx-safe-check/cx-save-check-server/src/main/java/com/rongwei/savecheck/controller/SafeSendNotifyController.java

@@ -142,4 +142,12 @@ public class SafeSendNotifyController {
         return R.ok();
     }
 
+    @Scheduled(cron = "0 0 7 ? * WED,FRI")
+    @PostMapping("/hidden/danger")
+    public R hiddenDangerTak(@RequestBody Map<String, String> map){
+        log.info("点巡检隐患任务提醒",map);
+        sendNotifyService.hiddenDangerTask(map);
+        return R.ok();
+    }
+
 }