diff --git a/inspect-base/inspect-base-core/src/main/java/com/inspect/base/core/constant/RedisConst.java b/inspect-base/inspect-base-core/src/main/java/com/inspect/base/core/constant/RedisConst.java index 9561e4e..cd82dd3 100644 --- a/inspect-base/inspect-base-core/src/main/java/com/inspect/base/core/constant/RedisConst.java +++ b/inspect-base/inspect-base-core/src/main/java/com/inspect/base/core/constant/RedisConst.java @@ -13,4 +13,5 @@ public class RedisConst { public static final String TASK_RECORD_CNT = "TASK_RECORD_CNT"; public static final String TASK_CURRENT_CODE = "TASK_CURRENT_CODE@"; public static final String IMMEDIATELY_EXEC_TASK_TIME = "IMMEDIATELY_EXEC_TASK_TIME"; + public static final String REPORT_PUSH_LOCK = "REPORT_PUSH_LOCK@";//任务完成自动归档+报告推送 防重锁 } diff --git a/inspect-main/inspect-main-api/src/main/java/com/inspect/api/config/RabbitMQConfig.java b/inspect-main/inspect-main-api/src/main/java/com/inspect/api/config/RabbitMQConfig.java index 4c11d4a..f100c04 100644 --- a/inspect-main/inspect-main-api/src/main/java/com/inspect/api/config/RabbitMQConfig.java +++ b/inspect-main/inspect-main-api/src/main/java/com/inspect/api/config/RabbitMQConfig.java @@ -25,7 +25,7 @@ public class RabbitMQConfig { @Bean public Binding alarmBinding() { - return BindingBuilder.bind(alarmQueue()).to(alarmExchange()).with(YanyuanConstants.EXCHANGE); + return BindingBuilder.bind(alarmQueue()).to(alarmExchange()).with(YanyuanConstants.ROUTING_KEY); } @Bean diff --git a/inspect-main/inspect-main-api/src/main/java/com/inspect/api/domain/AlarmMessage.java b/inspect-main/inspect-main-api/src/main/java/com/inspect/api/domain/AlarmMessage.java index 5c0fd73..d3e6425 100644 --- a/inspect-main/inspect-main-api/src/main/java/com/inspect/api/domain/AlarmMessage.java +++ b/inspect-main/inspect-main-api/src/main/java/com/inspect/api/domain/AlarmMessage.java @@ -6,6 +6,8 @@ import lombok.*; @ToString @Data @Builder +@NoArgsConstructor +@AllArgsConstructor public class AlarmMessage extends BaseEntity { private String messageId; private String messageType; diff --git a/inspect-main/inspect-main-start/src/main/java/com/inspect/InspectStartApplication.java b/inspect-main/inspect-main-start/src/main/java/com/inspect/InspectStartApplication.java index eb0c44d..4a1927d 100644 --- a/inspect-main/inspect-main-start/src/main/java/com/inspect/InspectStartApplication.java +++ b/inspect-main/inspect-main-start/src/main/java/com/inspect/InspectStartApplication.java @@ -18,7 +18,7 @@ import org.springframework.scheduling.annotation.EnableAsync; @EnableRyFeignClients @EnableDiscoveryClient @SpringBootApplication -@EnableAspectJAutoProxy +@EnableAspectJAutoProxy(exposeProxy = true) @EnableAsync public class InspectStartApplication { private final static Logger log = LoggerFactory.getLogger(InspectStartApplication.class); diff --git a/inspect-main/inspect-main-task/src/main/java/com/inspect/analysis/utils/ResultAnalysisUtils.java b/inspect-main/inspect-main-task/src/main/java/com/inspect/analysis/utils/ResultAnalysisUtils.java index ff74319..3ad7b0c 100644 --- a/inspect-main/inspect-main-task/src/main/java/com/inspect/analysis/utils/ResultAnalysisUtils.java +++ b/inspect-main/inspect-main-task/src/main/java/com/inspect/analysis/utils/ResultAnalysisUtils.java @@ -508,7 +508,7 @@ public class ResultAnalysisUtils { if (!NumberUtils.isCreatable(val)) { return val; } - + // 红外算法,保留1位小数(四舍五入) if (AlgConstants.ALG_INFRARED_LIST.contains(algType)) { String formatted = BigDecimalUtil.toOneDecimal(val, 1); return shouldAddUnit ? formatted + unit : formatted; @@ -521,7 +521,7 @@ public class ResultAnalysisUtils { } return val; } - + // 所有值都加单位(如果有单位的话) return shouldAddUnit ? val + unit : val; }) .collect(Collectors.joining(",")); diff --git a/inspect-main/inspect-main-task/src/main/java/com/inspect/aspect/TaskStatusChangeAspect.java b/inspect-main/inspect-main-task/src/main/java/com/inspect/aspect/TaskStatusChangeAspect.java index 34cf3ba..7128c37 100644 --- a/inspect-main/inspect-main-task/src/main/java/com/inspect/aspect/TaskStatusChangeAspect.java +++ b/inspect-main/inspect-main-task/src/main/java/com/inspect/aspect/TaskStatusChangeAspect.java @@ -1,6 +1,7 @@ package com.inspect.aspect; import com.inspect.annotation.TaskStatusChange; +import com.inspect.reportpush.service.ReportAutoArchiveService; import com.inspect.task.service.IPatrolTaskService; import com.inspect.taskstatus.domain.PatrolTaskStatus; import lombok.extern.slf4j.Slf4j; @@ -18,6 +19,9 @@ public class TaskStatusChangeAspect { @Autowired private IPatrolTaskService patrolTaskService; + @Autowired + private ReportAutoArchiveService reportAutoArchiveService; + /** * 拦截带有 @TaskStatusChange 注解的方法 @@ -46,8 +50,9 @@ public class TaskStatusChangeAspect { // 执行切面逻辑 if (taskStatusChange.async()) { - log.info("异步执行区域任务合并报告,任务执行id: {}", taskStatus.getTaskPatrolledId()); - patrolTaskService.executeAsync(taskStatus); + log.info("异步执行自动归档,任务执行id: {}", taskStatus.getTaskPatrolledId()); + // 任务巡检完成自动归档 + 生成报告 + websocket 推送(盐源外部平台) + reportAutoArchiveService.onTaskCompleted(taskStatus); } else { executeSync(taskStatus); } diff --git a/inspect-main/inspect-main-task/src/main/java/com/inspect/img/domain/InspectionReportImg.java b/inspect-main/inspect-main-task/src/main/java/com/inspect/img/domain/InspectionReportImg.java index 46208aa..d73f148 100644 --- a/inspect-main/inspect-main-task/src/main/java/com/inspect/img/domain/InspectionReportImg.java +++ b/inspect-main/inspect-main-task/src/main/java/com/inspect/img/domain/InspectionReportImg.java @@ -28,6 +28,9 @@ public class InspectionReportImg extends BaseEntity { name = "缩略图路径" ) private String imgSrc; + + private String imageNormalUrlPath; + @JsonFormat( pattern = "yyyy-MM-dd" ) diff --git a/inspect-main/inspect-main-task/src/main/java/com/inspect/insreportdata/domain/InspectionReportData.java b/inspect-main/inspect-main-task/src/main/java/com/inspect/insreportdata/domain/InspectionReportData.java index 3a40037..3597643 100644 --- a/inspect-main/inspect-main-task/src/main/java/com/inspect/insreportdata/domain/InspectionReportData.java +++ b/inspect-main/inspect-main-task/src/main/java/com/inspect/insreportdata/domain/InspectionReportData.java @@ -58,6 +58,11 @@ public class InspectionReportData extends BaseEntity { name = "巡视结果" ) private String inspectionResults; + + @Excel( + name = "巡视读数" + ) + private String inspectionValue; @Excel( name = "点位状态:正常、异常、待人工确 认三种状态" ) diff --git a/inspect-main/inspect-main-task/src/main/java/com/inspect/message/MessageUtils.java b/inspect-main/inspect-main-task/src/main/java/com/inspect/message/MessageUtils.java index 31339bc..7b89677 100644 --- a/inspect-main/inspect-main-task/src/main/java/com/inspect/message/MessageUtils.java +++ b/inspect-main/inspect-main-task/src/main/java/com/inspect/message/MessageUtils.java @@ -235,6 +235,8 @@ public class MessageUtils { return "summary"; case "缺陷": return "defect"; + case "本次巡检未发现缺陷项": + return "No defects were found during this inspection."; case"分析失败": return "analysis failed"; default: diff --git a/inspect-main/inspect-main-task/src/main/java/com/inspect/partrolresult/service/impl/PatrolResultServiceImpl.java b/inspect-main/inspect-main-task/src/main/java/com/inspect/partrolresult/service/impl/PatrolResultServiceImpl.java index e7de160..fa697b2 100644 --- a/inspect-main/inspect-main-task/src/main/java/com/inspect/partrolresult/service/impl/PatrolResultServiceImpl.java +++ b/inspect-main/inspect-main-task/src/main/java/com/inspect/partrolresult/service/impl/PatrolResultServiceImpl.java @@ -1321,31 +1321,33 @@ public class PatrolResultServiceImpl implements IPatrolResultService { reportData.setTaskName(resultTaskName); reportData.setTaskPatrolledId(taskPatrolledId); reportData.setTaskResultId(String.valueOf(mainId)); - if ("1".equals(patrolResultRef.getResultType()) && validAlgTypes.contains(patrolResultRef.getAlgType())) { - reportData.setInspectionResults(patrolResultRef.getValue()); - } else { - reportData.setInspectionResults(patrolResultRef.getDescription()); - } +// if ("1".equals(patrolResultRef.getResultType()) && validAlgTypes.contains(patrolResultRef.getAlgType())) { +// reportData.setInspectionResults(patrolResultRef.getValue()); +// } else { +// reportData.setInspectionResults(patrolResultRef.getDescription()); +// } + reportData.setInspectionResults(patrolResultRef.getDescription()); + reportData.setInspectionValue(patrolResultRef.getValue()); reportData.setAlgName(patrolResultRef.getAlgName()); - String threshold = patrolResultRef.getThreshold(); - if (StringUtils.isBlank(threshold)) { - threshold = ""; - } - if ("1".equals(patrolResultRef.getResultType()) && threshold.contains("sub_53")) { - reportData.setInspectionResults(patrolResultRef.getValue()); - } - - if ("1".equals(patrolResultRef.getResultType()) && (threshold.contains("sub_52") || threshold.contains("sub_53")) - && !"0".equals(patrolResultRef.getValue()) - && !"1".equals(patrolResultRef.getValue()) - && !"-1".equals(patrolResultRef.getValue()) - && !"check image".equals(patrolResultRef.getValue())) { - reportData.setInspectionResults(patrolResultRef.getValue()); - } +// String threshold = patrolResultRef.getThreshold(); +// if (StringUtils.isBlank(threshold)) { +// threshold = ""; +// } +// if ("1".equals(patrolResultRef.getResultType()) && threshold.contains("sub_53")) { +// reportData.setInspectionResults(patrolResultRef.getValue()); +// } +// +// if ("1".equals(patrolResultRef.getResultType()) && (threshold.contains("sub_52") || threshold.contains("sub_53")) +// && !"0".equals(patrolResultRef.getValue()) +// && !"1".equals(patrolResultRef.getValue()) +// && !"-1".equals(patrolResultRef.getValue()) +// && !"check image".equals(patrolResultRef.getValue())) { +// reportData.setInspectionResults(patrolResultRef.getValue()); +// } // 给读数增加单位 - String resValue = resultAnalysisUtils.addUnit2Value(reportData.getInspectionResults(), patrolResultRef.getAlgType(), patrolResultRef.getUnit()); - reportData.setInspectionResults(resValue); + String resValue = resultAnalysisUtils.addUnit2Value(reportData.getInspectionValue(), patrolResultRef.getAlgType(), patrolResultRef.getUnit()); + reportData.setInspectionValue(resValue); String pointStatus = patrolResultRef.getPointStatus(); String resultType = patrolResultRef.getResultType(); @@ -1395,16 +1397,20 @@ public class PatrolResultServiceImpl implements IPatrolResultService { //List results = JSONObject.parseObject(resultContent).getJSONArray("resultList").toJavaList(resultList.class); //String imgUrl = results.get(0).getResults().get(0).getResImageUrl(); AnalyseResPoint analyseResPoint = JSONObject.parseObject(resultContent, AnalyseResPoint.class); - String imgUrl = analyseResPoint.getResImageUrl(); + String resImageUrl = analyseResPoint.getResImageUrl(); + String imageNormalUrlPath = analyseResPoint.getImageNormalUrlPath(); - if (StringUtils.isEmpty(imgUrl)) { - imgUrl = patrolResultRef.getFilePath().split(StringUtils.COMMA)[0]; + if (StringUtils.isEmpty(resImageUrl)) { + resImageUrl = patrolResultRef.getFilePath().split(StringUtils.COMMA)[0]; + } + if (StringUtils.isEmpty(imageNormalUrlPath)) { + imageNormalUrlPath = patrolResultRef.getFilePath().split(StringUtils.COMMA)[0]; } - InspectionReportImg reportImg = new InspectionReportImg(); reportImg.setReportInfoId(reportDataId); - reportImg.setImg(imgUrl); - reportImg.setImgSrc(imgUrl); + reportImg.setImg(resImageUrl); + reportImg.setImgSrc(patrolResultRef.getFilePath().split(StringUtils.COMMA)[0]); + reportImg.setImageNormalUrlPath(imageNormalUrlPath); reportImg.setImgType("0"); reportImg.setCreatTime(new Date()); reportImages.add(reportImg); diff --git a/inspect-main/inspect-main-task/src/main/java/com/inspect/reportpush/config/ReportPushProperties.java b/inspect-main/inspect-main-task/src/main/java/com/inspect/reportpush/config/ReportPushProperties.java new file mode 100644 index 0000000..2198d18 --- /dev/null +++ b/inspect-main/inspect-main-task/src/main/java/com/inspect/reportpush/config/ReportPushProperties.java @@ -0,0 +1,57 @@ +package com.inspect.reportpush.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * 任务巡检完成自动归档 + 生成报告 + websocket 推送配置 + *

+ * 对应 application.yml 中 {@code inspect.report-push.*} 配置块 + * (可在 nacos 配置中心按现场覆盖)。 + * + * @author inspect + */ +@Data +@Component +@ConfigurationProperties(prefix = "inspect.report-push") +public class ReportPushProperties { + + /** 是否启用自动归档 + 推送 */ + private boolean enabled = true; + +// /** 外部平台网关基础路径(/ext_auth/getAuthToken 获取 Joinbright-Token) */ +// private String baseUrl; +// +// /** 外部平台 websocket 地址 */ +// private String wsUrl; +// +// /** 认证凭据(现场提供) */ +// private String clientId; +// +// private String clientSecret; +// +// /** token 缓存时长(秒) */ +// private long tokenCacheSeconds = 7200; +// +// /** websocket 连接超时(秒) */ +// private int connectTimeoutSeconds = 10; +// +// /** 发送后等待时间(毫秒) */ +// private long sendWaitMillis = 500; + + /** 自动归档审核人 */ + private String checkPerson = "admin"; + + /** 自动归档巡视结论 */ + private String taskResult = "巡检完成,自动归档"; + + /** 无缺陷数据时是否仍归档(false: 与手动归档一致,无缺陷不归档) */ + private boolean archiveWithoutDefect = false; + + /** 任务状态更新事务提交等待时间(毫秒) */ + private long afterCommitDelayMillis = 2000; + + /** 归档防重锁过期时间(秒) */ + private long lockExpireSeconds = 86400; +} diff --git a/inspect-main/inspect-main-task/src/main/java/com/inspect/reportpush/service/ReportAutoArchiveService.java b/inspect-main/inspect-main-task/src/main/java/com/inspect/reportpush/service/ReportAutoArchiveService.java new file mode 100644 index 0000000..ae48e7e --- /dev/null +++ b/inspect-main/inspect-main-task/src/main/java/com/inspect/reportpush/service/ReportAutoArchiveService.java @@ -0,0 +1,197 @@ +package com.inspect.reportpush.service; + +import com.inspect.base.core.constant.RedisConst; +import com.inspect.base.core.enums.TaskStatus; +import com.inspect.base.core.enums.TaskType; +import com.inspect.base.core.utils.StringUtils; +import com.inspect.base.redis.service.RedisService; +import com.inspect.analysis.domain.ResultAnalysis; +import com.inspect.analysis.service.IResultAnalysisService; +import com.inspect.reportpush.config.ReportPushProperties; +import com.inspect.resultmain.controller.DonghuanReportExportController; +import com.inspect.resultmain.domain.PatrolTaskResultMain; +import com.inspect.resultmain.service.IPatrolTaskResultMainService; +import com.inspect.taskstatus.domain.PatrolTaskStatus; +import com.inspect.taskstatus.service.IPatrolTaskStatusService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/** + * 任务巡检完成 → 自动归档 + 生成报告(动环 Word) → websocket 推送 + *

+ * 由 {@code TaskStatusChangeAspect} 在任务状态变更为「已完成(1)」时异步触发, + * 仅处理主任务/普通任务(子任务由主任务统一归档), + * 通过 Redis 防重锁避免重复归档。 + * + * @author inspect + */ +@Slf4j +@Service +public class ReportAutoArchiveService { + + private final ReportPushProperties properties; + private final RedisService redisService; + private final IPatrolTaskStatusService patrolTaskStatusService; + private final IPatrolTaskResultMainService patrolTaskResultMainService; + private final IResultAnalysisService resultAnalysisService; + private final DonghuanReportExportController donghuanReportExportController; + + public ReportAutoArchiveService(ReportPushProperties properties, + RedisService redisService, + IPatrolTaskStatusService patrolTaskStatusService, + IPatrolTaskResultMainService patrolTaskResultMainService, + IResultAnalysisService resultAnalysisService, + DonghuanReportExportController donghuanReportExportController) { + this.properties = properties; + this.redisService = redisService; + this.patrolTaskStatusService = patrolTaskStatusService; + this.patrolTaskResultMainService = patrolTaskResultMainService; + this.resultAnalysisService = resultAnalysisService; + this.donghuanReportExportController = donghuanReportExportController; + } + + /** + * 任务状态变更为已完成时触发(异步)。 + * + * @param taskStatus 变更后的任务状态(切面入参) + */ + @Async + public void onTaskCompleted(PatrolTaskStatus taskStatus) { + try { + if (!properties.isEnabled()) { + log.info("[AUTO_ARCHIVE] 未启用 inspect.report-push.enabled,跳过自动归档: taskPatrolledId={}", + taskStatus == null ? null : taskStatus.getTaskPatrolledId()); + return; + } + if (taskStatus == null || StringUtils.isEmpty(taskStatus.getTaskPatrolledId())) { + log.warn("[AUTO_ARCHIVE] 任务状态参数为空,跳过自动归档"); + return; + } + // 子任务不单独归档,由主任务统一归档 + if (TaskType.SUB.getCode().equals(taskStatus.getTaskType())) { + log.debug("[AUTO_ARCHIVE] 子任务不触发归档: {}", taskStatus.getTaskPatrolledId()); + return; + } + + // 归档单元:主任务(联合任务)或普通任务自身 + PatrolTaskStatus mainTask = patrolTaskStatusService.selectPatrolTaskStatusMain(taskStatus.getTaskPatrolledId()); + String archiveTaskPatrolledId = mainTask != null + ? mainTask.getTaskPatrolledId() : taskStatus.getTaskPatrolledId(); + if (StringUtils.isEmpty(archiveTaskPatrolledId)) { + log.warn("[AUTO_ARCHIVE] 无法确定归档任务ID,跳过: {}", taskStatus.getTaskPatrolledId()); + return; + } + + // 防重锁:同一归档单元只允许一次自动归档 + String lockKey = RedisConst.REPORT_PUSH_LOCK + archiveTaskPatrolledId; + Boolean locked = redisService.redisTemplate.opsForValue() + .setIfAbsent(lockKey, archiveTaskPatrolledId, + properties.getLockExpireSeconds(), TimeUnit.SECONDS); + if (!Boolean.TRUE.equals(locked)) { + log.info("[AUTO_ARCHIVE] 任务 {} 已在归档/推送中(防重锁),跳过", archiveTaskPatrolledId); + return; + } + log.info("[AUTO_ARCHIVE] 获取归档防重锁: {}", lockKey); + + // 等待任务状态事务提交、结果数据落库 + long waitMillis = properties.getAfterCommitDelayMillis(); + if (waitMillis > 0) { + try { + Thread.sleep(waitMillis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + releaseLock(lockKey); + return; + } + } + + // 二次校验:任务仍为已完成状态 + PatrolTaskStatus freshTask = patrolTaskStatusService.selectPatrolTaskStatusByTaskPatrolledId(archiveTaskPatrolledId); + if (freshTask == null || !TaskStatus.DONE.getCode().equals(freshTask.getTaskState())) { + log.info("[AUTO_ARCHIVE] 任务 {} 当前状态 {},非已完成,跳过自动归档", + archiveTaskPatrolledId, freshTask == null ? "null" : freshTask.getTaskState()); + releaseLock(lockKey); + return; + } + + // 二次校验:已归档(file_status=1)的任务不重复归档 + PatrolTaskResultMain existMain = patrolTaskResultMainService + .selectPatrolTaskResultMainByTaskPatrolledId(archiveTaskPatrolledId); + if (existMain != null && "1".equals(existMain.getFileStatus())) { + log.info("[AUTO_ARCHIVE] 任务 {} 已归档(fileStatus=1),跳过", archiveTaskPatrolledId); + releaseLock(lockKey); + return; + } + + // 归档范围:主任务 + 其下所有子任务(联合任务) + List taskPatrolledIds = new ArrayList<>(); + taskPatrolledIds.add(archiveTaskPatrolledId); + List subTasks = patrolTaskStatusService.selectPatrolTaskStatusListByMainId(archiveTaskPatrolledId); + if (subTasks != null) { + for (PatrolTaskStatus subTask : subTasks) { + if (StringUtils.isNotEmpty(subTask.getTaskPatrolledId())) { + taskPatrolledIds.add(subTask.getTaskPatrolledId()); + } + } + } + + // 无缺陷不归档(与手动归档一致) +// if (!properties.isArchiveWithoutDefect() && !hasDefect(taskPatrolledIds)) { +// log.info("[AUTO_ARCHIVE] 任务 {} 无缺陷数据,不归档(archive-without-defect=false)", archiveTaskPatrolledId); +// releaseLock(lockKey); +// return; +// } + + // 触发归档(动环 Word 报告),报告生成后由 exportDonghuanReport 回调推送 + PatrolTaskResultMain resultMain = new PatrolTaskResultMain(); + resultMain.setTaskPatrolledIds(taskPatrolledIds); + resultMain.setCheckPerson(properties.getCheckPerson()); + resultMain.setTaskResult(properties.getTaskResult()); + log.info("[AUTO_ARCHIVE] 触发自动归档: taskPatrolledIds={}, checkPerson={}, taskResult={}", + taskPatrolledIds, resultMain.getCheckPerson(), resultMain.getTaskResult()); + donghuanReportExportController.updateInfo_donghuan(resultMain); + } catch (Exception e) { + log.error("[AUTO_ARCHIVE] 自动归档异常: taskPatrolledId={}", + taskStatus == null ? null : taskStatus.getTaskPatrolledId(), e); + } + } + + /** + * 校验任务(含子任务)是否存在缺陷数据(初筛缺陷 + 大模型缺陷) + */ + private boolean hasDefect(List taskPatrolledIds) { + try { + Map abnormalMap = resultAnalysisService.selectTaskAbnormalDataBatch(taskPatrolledIds); + if (abnormalMap == null || abnormalMap.isEmpty()) { + return false; + } + int csQxNum = 0, aiQxNum = 0; + for (ResultAnalysis analysis : abnormalMap.values()) { + if (analysis == null) { + continue; + } + csQxNum += analysis.getCsQxNum(); + aiQxNum += analysis.getAiQxNum(); + } + return csQxNum + aiQxNum > 0; + } catch (Exception e) { + log.error("[AUTO_ARCHIVE] 查询缺陷数据异常,按存在缺陷处理: taskPatrolledIds={}", taskPatrolledIds, e); + return true; + } + } + + private void releaseLock(String lockKey) { + try { + redisService.deleteObject(lockKey); + } catch (Exception e) { + log.warn("[AUTO_ARCHIVE] 释放防重锁失败: {}", lockKey, e); + } + } + +} diff --git a/inspect-main/inspect-main-task/src/main/java/com/inspect/reportpush/service/ReportPushService.java b/inspect-main/inspect-main-task/src/main/java/com/inspect/reportpush/service/ReportPushService.java new file mode 100644 index 0000000..ce4ea65 --- /dev/null +++ b/inspect-main/inspect-main-task/src/main/java/com/inspect/reportpush/service/ReportPushService.java @@ -0,0 +1,130 @@ +package com.inspect.reportpush.service; + +import com.alibaba.fastjson.JSONObject; +import com.inspect.api.domain.AlarmMessage; +import com.inspect.api.enums.MessageType; +import com.inspect.api.enums.SystemCode; +import com.inspect.api.service.AlarmPublisher; +import com.inspect.insreport.domain.InspectionReport; +import com.inspect.insreportdata.domain.InspectionReportData; +import com.inspect.message.MessageUtils; +import com.inspect.reportpush.config.ReportPushProperties; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.UUID; + +/** + * 巡检报告 websocket 推送 + *

+ * 报告归档(Word)生成完毕后,组装 report_push 消息(沿用 AlarmMessage 结构), + * 通过 {@link AlarmPublisher} 发布到 alarm.exchange, + * 由 inspect-main-api 的 AlarmConsumer → {@code AlarmWsConnection} 推送到外部平台 + * (ws://…/jb-base-socket?Joinbright-Token=…)。 + * + * @author inspect + */ +@Slf4j +@Service +public class ReportPushService { + + private static final DateTimeFormatter TIME_FORMATTER = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + private final ReportPushProperties properties; + private final AlarmPublisher alarmPublisher; + private final MessageUtils messageUtils; + + @Autowired + public ReportPushService(ReportPushProperties properties, + AlarmPublisher alarmPublisher, + MessageUtils messageUtils) { + this.properties = properties; + this.alarmPublisher = alarmPublisher; + this.messageUtils = messageUtils; + } + + /** + * 报告生成并上传完成后推送。自动归档与手动归档均会触发。 + * + * @param report 已保存 filePath 的巡检报告 + */ + public void pushReport(InspectionReport report) { + if (report == null) { + return; + } + if (!properties.isEnabled()) { + log.info("[REPORT_PUSH] 未启用 report-push 配置,跳过报告推送: reportId={}", report.getLineId()); + return; + } + try { + AlarmMessage message = AlarmMessage.builder() + .messageId(UUID.randomUUID().toString().replace("-", "")) + .messageType(MessageType.REPORT.getCode()) + .timestamp(LocalDateTime.now().format(TIME_FORMATTER)) + .systemCode(SystemCode.PATROL.getCode()) + .data(buildReportData(report)) + .build(); + alarmPublisher.publish(message); + log.info("[REPORT_PUSH] 报告推送消息已发布: reportId={}, taskName={}, filePath={}", + report.getLineId(), report.getInspectionTaskName(), report.getFilePath()); + } catch (Exception e) { + log.error("[REPORT_PUSH] 报告推送失败: reportId={}", report.getLineId(), e); + } + } + + /** + * 组装推送 data 载荷:报告基本信息 + 状态统计 + */ + private JSONObject buildReportData(InspectionReport report) { + JSONObject data = new JSONObject(); + data.put("reportId", report.getLineId()); + data.put("reportName", report.getInspectionTaskName()); + data.put("filePath", report.getFilePath()); + data.put("taskId", report.getTaskId()); + data.put("taskPatrolledId", report.getTaskPatrolledId()); + data.put("stationName", report.getStationName()); + data.put("areaName", report.getAreaName()); + data.put("checkPerson", report.getCheckPerson()); + data.put("description", report.getDescription()); + if (report.getInspectionStartTime() != null) { + data.put("inspectionStartTime", TIME_FORMATTER.format( + LocalDateTime.ofInstant(report.getInspectionStartTime().toInstant(), + java.time.ZoneId.systemDefault()))); + } + if (report.getInspectionEndTime() != null) { + data.put("inspectionEndTime", TIME_FORMATTER.format( + LocalDateTime.ofInstant(report.getInspectionEndTime().toInstant(), + java.time.ZoneId.systemDefault()))); + } + // 状态统计 + String defect = messageUtils.get("缺陷"); + String abnormal = messageUtils.get("异常"); + String normal = messageUtils.get("正常"); + int defectCount = 0, abnormalCount = 0, normalCount = 0, total = 0; + List dataList = report.getReportDatalist(); + if (!CollectionUtils.isEmpty(dataList)) { + for (InspectionReportData item : dataList) { + total++; + String status = item.getPointStatus(); + if (defect.equals(status)) { + defectCount++; + } else if (abnormal.equals(status)) { + abnormalCount++; + } else if (normal.equals(status)) { + normalCount++; + } + } + } + data.put("totalCount", total); + data.put("defectCount", defectCount); + data.put("abnormalCount", abnormalCount); + data.put("normalCount", normalCount); + return data; + } +} diff --git a/inspect-main/inspect-main-task/src/main/java/com/inspect/resultmain/controller/DonghuanReportExportController.java b/inspect-main/inspect-main-task/src/main/java/com/inspect/resultmain/controller/DonghuanReportExportController.java new file mode 100644 index 0000000..c7ac2c5 --- /dev/null +++ b/inspect-main/inspect-main-task/src/main/java/com/inspect/resultmain/controller/DonghuanReportExportController.java @@ -0,0 +1,1189 @@ +package com.inspect.resultmain.controller; + +import com.inspect.base.core.sftp.SftpClient; +import com.inspect.base.core.sftp.SftpUploadEntity; +import com.inspect.base.core.utils.DateUtils; +import com.inspect.base.core.utils.StringUtils; +import com.inspect.base.core.web.controller.BaseController; +import com.inspect.base.core.web.domain.AjaxResult; +import com.inspect.img.domain.InspectionReportImg; +import com.inspect.img.service.IInspectionReportImgService; +import com.inspect.insreport.domain.InspectionReport; +import com.inspect.insreport.service.IInspectionReportService; +import com.inspect.insreportdata.domain.InspectionReportData; +import com.inspect.insreportdata.service.IInspectionReportDataService; +import com.inspect.message.MessageUtils; +import com.inspect.partrolresult.domain.PatrolResult; +import com.inspect.partrolresult.service.IPatrolResultService; +import com.inspect.partrolresult.util.PrintUtil; +import com.inspect.reportpush.service.ReportPushService; +import com.inspect.resultmain.domain.PatrolTaskResultMain; +import com.inspect.resultmain.service.IPatrolTaskResultMainService; +import org.apache.commons.io.function.IOConsumer; +import org.apache.poi.xwpf.usermodel.*; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.web.bind.annotation.*; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.math.BigInteger; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.stream.Collectors; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +/** + * 动环智能巡检报告 —— 归档导出(Word 版) + *

+ * 逻辑流程对标 {@link PatrolTaskResultMainController#updateInfo_shaoxing} / + * {@code exportExcelWordAndZipShaoxing}(数据准备、保存、异步导出完全一致), + * 仅 Word 生成改为动环模板样式(模板:动环智能巡检报告_20260817.docx)。 + *

+ * 样式要点(与模板逐项对齐): + *

+ *

+ * 已知不确定点(待归档时调整,均以 TODO 标注): + * 位置字段来源、巡检点位/设备数量口径、审核意见来源、巡检读数、封面 logo 路径、 + * 基准图/缺陷图选择规则、详情表范围(全部点位 or 仅缺陷)、Excel 导出。 + * + * @author inspect + */ +@RestController +@RefreshScope +@RequestMapping({"/resultmain"}) +public class DonghuanReportExportController extends BaseController { + + // ============================ 样式常量(与模板一致) ============================ + /** 正文 */ + private static final String FONT_BODY = "仿宋"; + /** 一级小标题 */ + private static final String FONT_HEAD = "黑体"; + /** 报告标题 */ + private static final String FONT_TITLE = "方正小标宋简体"; + /** 深蓝:标题 / 表头底色 */ + private static final String COLOR_DARK = "1F4E79"; + /** 浅蓝:封面副标题 */ + private static final String COLOR_LIGHT = "2E75B6"; + /** 表格边框浅蓝 */ + private static final String COLOR_BORDER = "B4C6E7"; + /** 封面占位值灰色 */ + private static final String COLOR_GRAY = "999999"; + /** 表头白字 */ + private static final String COLOR_WHITE = "FFFFFF"; + + /** 正文 12pt(半磅 24) */ + private static final int SZ_BODY = 24; + /** 小标题 16pt(半磅 32) */ + private static final int SZ_HEAD = 32; + /** 行高 atLeast(twips) */ + private static final int ROW_H = 454; + /** 单元格左右边距(twips) */ + private static final int CELL_MAR = 108; + + /** 巡检详情图片尺寸(EMU,与模板一致) */ + private static final long IMG_PATROL_W = 1711325L, IMG_PATROL_H = 960755L; + private static final long IMG_DEFECT_W = 1629410L, IMG_DEFECT_H = 916940L; + + @Value("${sftp.basePath}") + private String basePath; + + @Value("${sftp.stationCode}") + private String stationCode; + + /** + * 封面 logo 图片:默认从 classpath 加载(图片位于 + * inspect-main-task/src/main/resources/report/logo.png) + */ + @Value("${report.donghuan.logo:report/logo.png}") + private String logoPath; + + private final IPatrolTaskResultMainService patrolTaskResultMainService; + private final IPatrolResultService patrolResultService; + private final IInspectionReportDataService inspectionReportDataService; + private final IInspectionReportImgService inspectionReportImgService; + private final IInspectionReportService inspectionReportService; + private final SftpClient sftpClient; + private final ReportPushService reportPushService; + + private static final ExecutorService executor = Executors.newFixedThreadPool(10); + + @Autowired + private MessageUtils messageUtils; + + public DonghuanReportExportController(IPatrolTaskResultMainService patrolTaskResultMainService, + IPatrolResultService patrolResultService, + IInspectionReportDataService inspectionReportDataService, + IInspectionReportImgService inspectionReportImgService, + IInspectionReportService inspectionReportService, + SftpClient sftpClient, + ReportPushService reportPushService) { + this.patrolTaskResultMainService = patrolTaskResultMainService; + this.patrolResultService = patrolResultService; + this.inspectionReportDataService = inspectionReportDataService; + this.inspectionReportImgService = inspectionReportImgService; + this.inspectionReportService = inspectionReportService; + this.sftpClient = sftpClient; + this.reportPushService = reportPushService; + } + + // ============================================================================ + // 一、入口:动环归档 + // ============================================================================ + @PostMapping({"/updateInfo_shaoxing"}) + public AjaxResult updateInfo_donghuan(@RequestBody PatrolTaskResultMain resultMain) { + long startTime = System.currentTimeMillis(); + CompletableFuture> saveReportFuture = CompletableFuture.>supplyAsync(() -> { + List taskPatrolledIds = resultMain.getTaskPatrolledIds(); + logger.info("-----------patrolTaskResultMains taskPatrolledIds: {}", taskPatrolledIds); + List patrolTaskResultMains = + patrolTaskResultMainService.selectPatrolTaskResultMainByTaskPatrolledIds(taskPatrolledIds); + if (patrolTaskResultMains == null || patrolTaskResultMains.isEmpty()) { + logger.error("[归档]失败, 数据采集中..."); + return Collections.emptyList(); + } + List lineIds = patrolTaskResultMains.stream() + .map(PatrolTaskResultMain::getLineId).collect(Collectors.toList()); + List longs = patrolTaskResultMainService.selectLineIdsByList(lineIds); + if (longs != null && !longs.isEmpty()) { + lineIds.addAll(longs); + } + lineIds = lineIds.stream().distinct().collect(Collectors.toList()); + List resultList = patrolResultService.selectPatrolResultListByMainIds(lineIds); + if (resultList == null || resultList.isEmpty()) { + logger.error("[归档]失败, 数据采集中..."); + return Collections.emptyList(); + } + PrintUtil.useTime("查询统计数据", startTime); + logger.info("[ARCHIVE] Start saving reports (donghuan)"); + return patrolResultService.saveReportShaoxing(resultMain, lineIds, resultList); + }, executor).exceptionally(ex -> { + logger.error("Report saving failed", ex); + return Collections.emptyList(); + }); + PrintUtil.useTime("保存报告数据", startTime); + + // 保存完成后异步导出(动环 Word 版) + saveReportFuture.thenAcceptAsync(reportIds -> { + logger.info("-----------[ARCHIVE] Saved export reportIds: {}", reportIds); + if (reportIds.isEmpty()) { + logger.warn("No reports to export"); + return; + } + CompletableFuture.runAsync(() -> exportDonghuanReport(reportIds), executor) + .whenComplete((v, ex) -> { + if (ex != null) { + logger.error("Async export failed for reportIds: {}", reportIds, ex); + } + }); + }, executor).exceptionally(ex -> { + logger.error("Error occurred during saveReport: ", ex); + return null; + }); + return toAjax(1); + } + + // ============================================================================ + // 二、导出:动环 Word + 图片 ZIP + // ============================================================================ + public void exportDonghuanReport(List reportIds) { + // 合并报告,所有报告内容一致,取第一个导出即可 + Long lineId = reportIds.get(0); + List tempFiles = new ArrayList<>(); + Map tempFileMap = new LinkedHashMap<>(); + XWPFDocument wordDocument = null; + try { + InspectionReport inspectionReport = + inspectionReportService.selectInspectionReportByLineId(lineId); + if (inspectionReport == null) { + logger.warn("--exportDonghuanReport----report lineId:{} not exist!", lineId); + return; + } + InspectionReportData query = new InspectionReportData(); + query.setReportId(String.valueOf(inspectionReport.getLineId())); + List dataList = + inspectionReportDataService.selectInspectionReportDataList(query); + if (dataList == null || dataList.isEmpty()) { + logger.info("--exportDonghuanReport------report lineId:{},filter:{} no report data!", + lineId, inspectionReport.getFilter()); + return; + } + inspectionReport.setReportDatalist(dataList); + + // 图片映射:imgSrc -> 唯一文件名 + Map imgSrcToFileNameMap = new HashMap<>(); + List images = new ArrayList<>(); + for (InspectionReportData reportData : dataList) { + if (!messageUtils.get("缺陷").equals(reportData.getPointStatus())) { + continue; + } + InspectionReportImg imgQuery = new InspectionReportImg(); + imgQuery.setReportInfoId(reportData.getLineId()); + List reportImgList = + inspectionReportImgService.selectInspectionReportImgList(imgQuery); + reportData.setReportImgList(reportImgList); + + int imgIndex = 1; + for (InspectionReportImg reportImg : reportImgList) { + // 原图 + String originalImgSrc = reportImg.getImgSrc(); + // 基准图 + String imageNormalUrlPath = reportImg.getImageNormalUrlPath(); + // 结果图 + String img = reportImg.getImg(); + images.add(originalImgSrc); + images.add(imageNormalUrlPath); + images.add(img); + String pointName = reportData.getPointName() != null + ? reportData.getPointName() : "unnamed"; + + // 原图 + if (originalImgSrc != null) { + String extension = ""; + int dotIndex = originalImgSrc.lastIndexOf('.'); + if (dotIndex > 0) { + extension = originalImgSrc.substring(dotIndex); + } + String uniqueFileName = String.format("%s_%s_%s_%d%s", + originalImgSrc.split("_")[2], + pointName.replaceAll("[\\\\/:*?\"<>|]", "") + .replaceAll("\\s+", ""), + reportData.getLineId(), imgIndex, extension); + imgSrcToFileNameMap.put(originalImgSrc, uniqueFileName); + imgIndex++; + } + // 结果图 + if (img != null) { + String extension = ""; + int dotIndex = img.lastIndexOf('.'); + if (dotIndex > 0) { + extension = img.substring(dotIndex); + } + String uniqueImgName = String.format("%s_%s_%s_%d%s", + img.split("_")[2], + pointName.replaceAll("[\\\\/:*?\"<>|]", "") + .replaceAll("\\s+", ""), + reportData.getLineId(), imgIndex, extension); + imgSrcToFileNameMap.put(img, uniqueImgName); + imgIndex++; + } + // 基准图 + if (imageNormalUrlPath != null) { + String extension = ""; + int dotIndex = imageNormalUrlPath.lastIndexOf('.'); + if (dotIndex > 0) { + extension = imageNormalUrlPath.substring(dotIndex); + } + String uniqueImgNormalPathName = String.format("%s_%s_%s_%d%s", + imageNormalUrlPath.split("_")[2], + pointName.replaceAll("[\\\\/:*?\"<>|]", "") + .replaceAll("\\s+", ""), + reportData.getLineId(), imgIndex, extension); + imgSrcToFileNameMap.put(imageNormalUrlPath, uniqueImgNormalPathName); + imgIndex++; + } + } + } + + // 图片下载到临时文件,避免内存驻留大量图片字节 + for (String imgSrc : images) { + try { + Path tempFile = downloadImageToTemp(imgSrc); + if (tempFile != null) { + tempFileMap.put(imgSrc, tempFile); + tempFiles.add(tempFile); + } + } catch (Exception e) { + logger.warn("报告归档下载图片失败: {}", imgSrc, e); + } + } + + // 生成动环样式 Word + wordDocument = getXWPFDocumentDonghuan(inspectionReport, tempFileMap); + + String basePath = this.basePath + stationCode + "/Model/"; + Date startTime = inspectionReport.getInspectionStartTime() != null + ? inspectionReport.getInspectionStartTime() : new Date(); + String timestamp = DateUtils.format(DateUtils.yyyyMMddHHmmss2, startTime) + + "_" + System.currentTimeMillis(); + String namePrefix = ""; +// if ("1".equals(inspectionReport.getFilter())) { +// namePrefix = messageUtils.get("初筛") + "_"; +// } else if ("0".equals(inspectionReport.getFilter())) { +// namePrefix = messageUtils.get("大模型") + "_"; +// } + String reportName = inspectionReport.getInspectionTaskName() + "_" + timestamp; + + // 上传图片 ZIP + CompletableFuture zipUploadFuture = CompletableFuture.runAsync(() -> { + uploadFile(basePath, reportName, ".zip", outputStream -> { + try (ZipOutputStream zipOut = new ZipOutputStream(outputStream)) { + for (Map.Entry entry : tempFileMap.entrySet()) { + String pointFileName = imgSrcToFileNameMap + .getOrDefault(entry.getKey(), "unnamed"); + ZipEntry zipEntry = new ZipEntry(pointFileName); + zipOut.putNextEntry(zipEntry); + Files.copy(entry.getValue(), zipOut); + zipOut.closeEntry(); + } + } catch (IOException e) { + throw new RuntimeException("生成ZIP文件失败", e); + } + }); + }, executor); + + // TODO 归档时调整:如需 Excel 导出,可复用 + // PatrolTaskResultMainController.getSXSSFWorkbookShaoxing(inspectionReport, tempFileMap) + // 并在此上传 .xls(本类暂只导出 Word + 图片 ZIP) + + // 上传 Word + XWPFDocument finalWordDocument = wordDocument; + CompletableFuture wordUploadFuture = CompletableFuture.runAsync(() -> { + uploadFile(basePath, reportName, ".docx", finalWordDocument::write); + }, executor); + + CompletableFuture.allOf(zipUploadFuture, wordUploadFuture) + .whenComplete((v, t) -> { + try { + inspectionReport.setFilePath(basePath + reportName + ".docx"); + inspectionReport.setLineIds(reportIds); + inspectionReportService.updateInspectionReportFilePath(inspectionReport); + // 报告生成并上传完成后,通过 websocket 推送到外部平台(自动归档与手动归档均推送) + reportPushService.pushReport(inspectionReport); + } finally { + closeResources(finalWordDocument, tempFiles); + } + }); + } catch (Throwable e) { + logger.error("生成动环巡视文件异常", e); + closeResources(wordDocument, tempFiles); + } + } + + // ============================================================================ + // 三、动环 Word 构建 + // ============================================================================ + private XWPFDocument getXWPFDocumentDonghuan(InspectionReport report, + Map tempFileMap) { + XWPFDocument doc = new XWPFDocument(); + setupPage(doc); + buildCoverPage1(doc); // 第1页:42pt 大标题 + 分页 + buildCoverPage2(doc, report); // 第2页:logo + 报告标题 + 副标题 + 签署表 + buildSectionBasic(doc, report); // 一、巡检基本情况 + buildSectionStatus(doc); // 二、巡检状态说明 + buildSectionOverview(doc, report); // 三、巡检结果概览 + buildSectionDetail(doc, report, tempFileMap); // 四、巡检详情 + return doc; + } + + /** 段落 keepNext:标题与后续表格/内容保持同页,避免标题孤行 */ + private void setKeepNext(XWPFParagraph p) { + CTPPr pPr = p.getCTP().isSetPPr() ? p.getCTP().getPPr() : p.getCTP().addNewPPr(); + if (!pPr.isSetKeepNext()) { + pPr.addNewKeepNext(); + } + } + + /** 页面设置:A4 + 模板版心 + 文档网格(与模板 sectPr 一致) */ + private void setupPage(XWPFDocument doc) { + CTBody body = doc.getDocument().getBody(); + CTSectPr sectPr = body.isSetSectPr() ? body.getSectPr() : body.addNewSectPr(); + CTPageSz pgSz = sectPr.isSetPgSz() ? sectPr.getPgSz() : sectPr.addNewPgSz(); + pgSz.setW(BigInteger.valueOf(11906)); + pgSz.setH(BigInteger.valueOf(16838)); + CTPageMar pgMar = sectPr.isSetPgMar() ? sectPr.getPgMar() : sectPr.addNewPgMar(); + pgMar.setTop(BigInteger.valueOf(2098)); + pgMar.setRight(BigInteger.valueOf(1474)); + pgMar.setBottom(BigInteger.valueOf(1984)); + pgMar.setLeft(BigInteger.valueOf(1587)); + pgMar.setHeader(BigInteger.valueOf(851)); + pgMar.setFooter(BigInteger.valueOf(992)); + pgMar.setGutter(BigInteger.ZERO); + CTColumns cols = sectPr.isSetCols() ? sectPr.getCols() : sectPr.addNewCols(); + cols.setNum(BigInteger.ONE); + cols.setSpace(BigInteger.valueOf(720)); + // 文档网格 linePitch=360(每行 18pt):模板封面第二页正是靠它撑满一页, + // 否则空行按 12pt 排版,内容变矮,「一、巡检基本情况」会被挤到封面页 + CTDocGrid grid = sectPr.isSetDocGrid() ? sectPr.getDocGrid() : sectPr.addNewDocGrid(); + grid.setLinePitch(BigInteger.valueOf(360)); + grid.setCharSpace(BigInteger.ZERO); + } + + /** 第1页封面:42pt 仿宋大标题 + 分页符 */ + private void buildCoverPage1(XWPFDocument doc) { + XWPFParagraph p = addPara(doc, "#动环智能巡检", FONT_BODY, 84, false, false, null, + ParagraphAlignment.CENTER, 120, 120); + p.createRun().addBreak(BreakType.PAGE); + } + + /** 第2页:logo + 报告标题 + 副标题 + 空行 + 封面签署表 */ + private void buildCoverPage2(XWPFDocument doc, InspectionReport report) { + // logo:优先 classpath 资源(src/main/resources/report/logo.png), + // 兼容本地绝对/相对路径 + if (StringUtils.isNotEmpty(logoPath)) { + try (InputStream is = openLogoStream(logoPath)) { + if (is != null) { + XWPFParagraph logoPara = doc.createParagraph(); + XWPFRun logoRun = logoPara.createRun(); + // 与模板一致:3203575 × 541020 EMU(POI 5.x 的 addPicture 仅 int 尺寸重载) + logoRun.addPicture(is, XWPFDocument.PICTURE_TYPE_PNG, "logo.png", + (int) 3203575L, (int) 541020L); + } + } catch (Exception e) { + logger.warn("插入封面 logo 失败: {}", logoPath, e); + } + } + addPara(doc, "", null, SZ_BODY, false, false, null, null, 600, null); + addPara(doc, "", null, SZ_BODY, false, false, null, null, 200, null); + + // 报告标题:站名 + 巡检报告(方正小标宋简体 22pt 加粗 深蓝) + // TODO 归档时调整:站名是否已含「场站/电站」后缀 + // 站名为空时标题不拼占位符(标题本身不会空白) + String station = report.getStationName(); + String reportTitle = (StringUtils.isEmpty(station) ? "" : station) + "巡检报告"; + addPara(doc, reportTitle, FONT_TITLE, 44, true, false, COLOR_DARK, + ParagraphAlignment.CENTER, 0, 100); + // 副标题 + addPara(doc, "【巡检类型:动环智能巡检】", FONT_BODY, SZ_HEAD, false, false, + COLOR_LIGHT, ParagraphAlignment.CENTER, 200, 100); + + // 空行(撑出版面,与模板一致) + for (int i = 0; i < 11; i++) { + addPara(doc, "", null, SZ_BODY, false, false, null, + ParagraphAlignment.CENTER, 200, 100); + } + addPara(doc, "", null, SZ_BODY, false, false, null, + ParagraphAlignment.CENTER, 400, null); + + // 封面签署表:初审/校对/审核/巡检日期(4行×2列,宽4686 twips) + XWPFTable table = addTable(doc, 4, 2, new int[]{1800, 2886}, 4686, true); + String[] labels = {"初审", "校对", "审核", "巡检日期"}; + // TODO 归档时调整:初审/校对/审核 人员数据来源暂用占位符;巡检日期取巡视开始日期 + String[] values = {"[填写]", "[填写]", "[填写]", + report.getInspectionStartTime() != null + ? DateUtils.format(DateUtils.yyyyMMdd2, report.getInspectionStartTime()) : "[填写]"}; + for (int i = 0; i < labels.length; i++) { + setRow(table.getRow(i), null, true); + setRowJcCenter(table.getRow(i)); + // 标签:仿宋 12pt 加粗 深蓝 居中 + styleCell(table.getRow(i).getCell(0), labels[i], FONT_BODY, SZ_BODY, true, false, + COLOR_DARK, false, ParagraphAlignment.CENTER, 0, 0, 1800, null, + 60, 150, 60, 120); + // 值:仿宋 12pt 灰色斜体 居中 + styleCell(table.getRow(i).getCell(1), values[i], FONT_BODY, SZ_BODY, false, true, + COLOR_GRAY, false, ParagraphAlignment.CENTER, 0, 0, 2886, null, + 60, 150, 60, 120); + } + } + + /** 一、巡检基本情况 */ + private void buildSectionBasic(XWPFDocument doc, InspectionReport report) { + XWPFParagraph h = addPara(doc, "一、巡检基本情况", FONT_HEAD, SZ_HEAD, true, false, + null, null, 160, 80); + setKeepNext(h); + + XWPFTable t = addTable(doc, 7, 4, new int[]{1827, 2655, 1920, 2659}, 9061, false); + List dataList = report.getReportDatalist(); + + // R0 表头(跨4列,深蓝底白字) + setRow(t.getRow(0), ROW_H, false); + mergeRowCells(t, 0, 0, 3); + styleCell(t.getRow(0).getCell(0), "场站基本信息", FONT_BODY, SZ_BODY, true, false, + COLOR_WHITE, true, ParagraphAlignment.CENTER, 0, 0, 9061, 4, + 0, CELL_MAR, 0, CELL_MAR); + + // R1 电站名称 | 白杨坪 | 位置 | 四川省/... + // TODO 归档时调整:位置字段来源(InspectionReport 无独立字段,暂用 areaName) + setRow(t.getRow(1), ROW_H, false); + bodyCell(t.getRow(1).getCell(0), "电站名称", 1827); + bodyCell(t.getRow(1).getCell(1), val(report.getStationName()), 2655); + bodyCell(t.getRow(1).getCell(2), "位置", 1920); + bodyCell(t.getRow(1).getCell(3), val(report.getAreaName()), 2659); + + // ==================== R2:巡视任务基本信息(新增表头) ==================== + setRow(t.getRow(2), ROW_H, false); + mergeRowCells(t, 2, 0, 3); + styleCell(t.getRow(2).getCell(0), "巡视任务基本信息", FONT_BODY, SZ_BODY, true, false, + COLOR_WHITE, true, ParagraphAlignment.CENTER, 0, 0, 9061, 4, + 0, CELL_MAR, 0, CELL_MAR); + + // R3 巡检任务 | xxx(跨3列) + setRow(t.getRow(3), ROW_H, false); + bodyCell(t.getRow(3).getCell(0), "巡检任务", 1827); + mergeRowCells(t, 3, 1, 3); + styleCell(t.getRow(3).getCell(1), val(report.getInspectionTaskName()), FONT_BODY, SZ_BODY, + false, false, null, false, ParagraphAlignment.LEFT, 0, 0, + 1827 + 2655 + 1920 + 2659 - 1827, 3, 0, CELL_MAR, 0, CELL_MAR); + + // R4 巡检开始时间 | xx | 巡检结束时间 | xx + setRow(t.getRow(4), ROW_H, false); + bodyCell(t.getRow(4).getCell(0), "巡检开始时间", 1827); + bodyCell(t.getRow(4).getCell(1), val(formatDateTime(report.getInspectionStartTime())), 2655); + bodyCell(t.getRow(4).getCell(2), "巡检结束时间", 1920); + bodyCell(t.getRow(4).getCell(3), val(formatDateTime(report.getInspectionEndTime())), 2659); + + // R5 巡检点位数量(个) | n | 巡检设备数量(个) | m + // TODO 归档时调整:数量口径(按点位名去重 / 按设备名去重) + setRow(t.getRow(5), ROW_H, false); + bodyCell(t.getRow(5).getCell(0), "巡检点位数量(个)", 1827); + bodyCell(t.getRow(5).getCell(1), String.valueOf(distinctCount(dataList, + InspectionReportData::getPointName)), 2655); + bodyCell(t.getRow(5).getCell(2), "巡检设备数量(个)", 1920); + bodyCell(t.getRow(5).getCell(3), String.valueOf(distinctCount(dataList, + InspectionReportData::getEqName)), 2659); + + // R6 审核意见 | (跨3列,可空) + // TODO 归档时调整:审核意见来源(暂用 report.description,可改为 checkPerson 或空) + setRow(t.getRow(6), ROW_H, false); + bodyCell(t.getRow(6).getCell(0), "审核意见", 1827); + mergeRowCells(t, 6, 1, 3); + styleCell(t.getRow(6).getCell(1), val(report.getDescription()), FONT_BODY, SZ_BODY, + false, false, null, false, ParagraphAlignment.LEFT, 0, 0, + 1827 + 2655 + 1920 + 2659 - 1827, 3, 0, CELL_MAR, 0, CELL_MAR); + } + + /** 二、巡检状态说明(静态文案,与模板一致) */ + private void buildSectionStatus(XWPFDocument doc) { + XWPFParagraph h = addPara(doc, "二、巡检状态说明", FONT_HEAD, SZ_HEAD, true, false, + null, null, 160, 80); + setKeepNext(h); + + XWPFTable t = addTable(doc, 4, 3, new int[]{1831, 4115, 3114}, 9060, false); + String[][] rows = { + {"状态", "说明", "典型场景"}, + {"缺陷", "巡检结果表明设备存在异常状态或潜在运行风险", + "表计超限、温度过高、表面油污、设备部件破损"}, + {"异常", "巡检数据未满足有效判定条件,无法准确判断设备当前状态", + "图像模糊、目标遮挡、通信异常、传感器数据异常"}, + {"正常", "巡检数据有效,检测结果符合设备正常运行要求,未发现异常状态或运行风险", + "表计读数正常、温度正常、设备外观正常"}, + }; + for (int i = 0; i < rows.length; i++) { + setRow(t.getRow(i), ROW_H, false); + if (i == 0) { + headerCell(t.getRow(i).getCell(0), rows[i][0], 1831); + headerCell(t.getRow(i).getCell(1), rows[i][1], 4115); + headerCell(t.getRow(i).getCell(2), rows[i][2], 3114); + } else { + bodyCell(t.getRow(i).getCell(0), rows[i][0], 1831, true); + bodyCell(t.getRow(i).getCell(1), rows[i][1], 4115, false); + bodyCell(t.getRow(i).getCell(2), rows[i][2], 3114, false); + } + } + } + + /** 三、巡检结果概览:(一)巡检统计 + (二)缺陷汇总表 */ + private void buildSectionOverview(XWPFDocument doc, InspectionReport report) { + XWPFParagraph h = addPara(doc, "三、巡检结果概览", FONT_HEAD, SZ_HEAD, true, false, + null, null, 160, 80); + setKeepNext(h); + + List dataList = report.getReportDatalist() != null + ? report.getReportDatalist() : Collections.emptyList(); + String statusDefect = messageUtils.get("缺陷"); + String statusAbnormal = messageUtils.get("异常"); + String statusNormal = messageUtils.get("正常"); + + // (一)巡检统计 + XWPFParagraph h1 = addPara(doc, "(一)巡检统计", FONT_BODY, SZ_HEAD, true, false, + null, null, 80, 40); + setKeepNext(h1); + XWPFTable statTable = addTable(doc, 5, 2, new int[]{4296, 4713}, 9008, true); + setRow(statTable.getRow(0), ROW_H, false); + headerCell(statTable.getRow(0).getCell(0), "巡检状态", 4296); + headerCell(statTable.getRow(0).getCell(1), "数量(个)", 4713); + String[][] statRows = { + {statusDefect, String.valueOf(countByStatus(dataList, statusDefect))}, + {statusAbnormal, String.valueOf(countByStatus(dataList, statusAbnormal))}, + {statusNormal, String.valueOf(countByStatus(dataList, statusNormal))}, + {"合计", String.valueOf(dataList.size())}, + }; + for (int i = 0; i < statRows.length; i++) { + setRow(statTable.getRow(i + 1), ROW_H, false); + bodyCell(statTable.getRow(i + 1).getCell(0), statRows[i][0], 4296, true); + bodyCell(statTable.getRow(i + 1).getCell(1), statRows[i][1], 4713, true); + } + + // (二)缺陷汇总表 + XWPFParagraph h2 = addPara(doc, "(二)缺陷汇总表", FONT_BODY, SZ_HEAD, true, false, + null, null, 80, 40); + setKeepNext(h2); + List defectList = dataList.stream() + .filter(d -> statusDefect.equals(d.getPointStatus())) + .collect(Collectors.toList()); + int[] summaryWidths = {717, 1200, 1230, 1245, 1215, 1710, 990, 727}; + int summaryTotalWidth = Arrays.stream(summaryWidths).sum(); + // 无缺陷数据时保留一行(合并整行输出文字说明),避免表格空白 + int summaryRows = 1 + Math.max(defectList.size(), 1); + XWPFTable summaryTable = addTable(doc, summaryRows, 8, summaryWidths, 9034, false); + String[] summaryHeaders = {"序号", "区域名称", "间隔名称", "设备名称", "部件名称", + "巡检点位名称", "巡检", "状态"}; + setRow(summaryTable.getRow(0), ROW_H, true); + for (int i = 0; i < summaryHeaders.length; i++) { + headerCell(summaryTable.getRow(0).getCell(i), summaryHeaders[i], summaryWidths[i]); + } + // 「巡检 / 结果」表头换行 + XWPFParagraph headP = summaryTable.getRow(0).getCell(6).getParagraphs().get(0); + setRunFont(headP.createRun(), "结果", FONT_BODY, SZ_BODY, true, false, COLOR_WHITE, true); + int num = 1; + for (int ri = 0; ri < defectList.size(); ri++) { + InspectionReportData d = defectList.get(ri); + setRow(summaryTable.getRow(ri + 1), ROW_H, true); + String[] vals = {String.valueOf(num++), val(d.getArea()), val(d.getTimeInterval()), + val(d.getEqName()), val(d.getParts()), val(d.getPointName()), + val(d.getInspectionResults()), val(d.getPointStatus())}; + for (int ci = 0; ci < vals.length; ci++) { + bodyCell(summaryTable.getRow(ri + 1).getCell(ci), vals[ci], + summaryWidths[ci], false, 120, 120); + } + } + if (defectList.isEmpty()) { + // 无缺陷数据时:整行合并输出文字说明(原占位横杠改为「本次巡检未发现缺陷项」) + setRow(summaryTable.getRow(1), ROW_H, true); + mergeRowCells(summaryTable, 1, 0, 7); + styleCell(summaryTable.getRow(1).getCell(0), + messageUtils.get("本次巡检未发现缺陷项"), FONT_BODY, SZ_BODY, + false, false, null, false, ParagraphAlignment.CENTER, 120, 120, + summaryTotalWidth, 8, 0, CELL_MAR, 0, CELL_MAR); + } + } + + /** 四、巡检详情:每个点位一张 8 行 × 4 列详情表 */ + private void buildSectionDetail(XWPFDocument doc, InspectionReport report, + Map tempFileMap) { + XWPFParagraph h = addPara(doc, "四、巡检详情", FONT_HEAD, SZ_HEAD, true, false, + null, null, 160, 80); + setKeepNext(h); + + List dataList = report.getReportDatalist() != null + ? report.getReportDatalist().stream().filter(item -> messageUtils.get("缺陷").equals(item.getPointStatus())).collect(Collectors.toList()) : Collections.emptyList(); + // TODO 归档时调整:详情表范围(全部点位 or 仅缺陷点位,如需仅缺陷请在此过滤) + if (dataList.isEmpty()) { + // 无缺陷数据时输出文字说明,避免「四、巡检详情」章节空白 + addPara(doc, messageUtils.get("本次巡检未发现缺陷项"), FONT_BODY, SZ_BODY, + false, false, null, ParagraphAlignment.LEFT, 160, 80); + return; + } + for (InspectionReportData d : dataList) { + XWPFTable t = addTable(doc, 8, 4, new int[]{1707, 2891, 1665, 2785}, 9048, false); + int[] grid = {1707, 2891, 1665, 2785}; + + String[][] pairs = { + {"巡检点位名称", val(d.getPointName()), "巡检时间", val(formatDateTime(d.getAcquisitionTime()))}, + {"区域名称", val(d.getArea()), "间隔名称", val(d.getTimeInterval())}, + {"设备名称", val(d.getEqName()), "部件名称", val(d.getParts())}, + {"数据来源", val(d.getDataSources()), "算法名称", val(d.getAlgName())}, + {"巡检读数", val(d.getInspectionValue()), "巡检结果", val(d.getInspectionResults())}, + }; + for (int ri = 0; ri < pairs.length; ri++) { + setRow(t.getRow(ri), ROW_H, false); + bodyCell(t.getRow(ri).getCell(0), pairs[ri][0], grid[0], false, 120, 120); + bodyCell(t.getRow(ri).getCell(1), pairs[ri][1], grid[1], false, 120, 120); + bodyCell(t.getRow(ri).getCell(2), pairs[ri][2], grid[2], false, 120, 120); + bodyCell(t.getRow(ri).getCell(3), pairs[ri][3], grid[3], false, 120, 120); + } + + // R5 巡检状态 | 状态(跨3列) + setRow(t.getRow(5), ROW_H, false); + bodyCell(t.getRow(5).getCell(0), "巡检状态", grid[0], false, 120, 120); + mergeRowCells(t, 5, 1, 3); + styleCell(t.getRow(5).getCell(1), val(d.getPointStatus()), FONT_BODY, SZ_BODY, + false, false, null, false, ParagraphAlignment.LEFT, 120, 120, + grid[1] + grid[2] + grid[3], 3, 0, CELL_MAR, 0, CELL_MAR); + + // R6 巡检原图 | 图片文件名(跨3列) + String imgName = firstImageName(d); + setRow(t.getRow(6), ROW_H, false); + bodyCell(t.getRow(6).getCell(0), "巡检原图", grid[0], false, 120, 120); + mergeRowCells(t, 6, 1, 3); + styleCell(t.getRow(6).getCell(1), val(imgName), FONT_BODY, SZ_BODY, + false, false, null, false, ParagraphAlignment.LEFT, 120, 120, + grid[1] + grid[2] + grid[3], 3, 0, CELL_MAR, 0, CELL_MAR); + + // R7 基准图 | 巡检原图照片 | 缺陷图 | 缺陷图照片 + // 图片列表为空或路径缺失时置 null,由 imageCell 输出横杠占位,避免空白/空指针 + setRow(t.getRow(7), ROW_H, false); + Path patrolPath = null; + Path defectPath = null; + if (d.getReportImgList() != null && !d.getReportImgList().isEmpty()) { + InspectionReportImg inspectionReportImg = d.getReportImgList().get(0); + patrolPath = tempFileMap.get(inspectionReportImg.getImageNormalUrlPath()); + defectPath = tempFileMap.get(inspectionReportImg.getImg()); + } + bodyCell(t.getRow(7).getCell(0), "基准图", grid[0], false, 120, 120); + imageCell(t.getRow(7).getCell(1), patrolPath, + IMG_PATROL_W, IMG_PATROL_H, grid[1]); + bodyCell(t.getRow(7).getCell(2), "缺陷图", grid[2], false, 120, 120); + imageCell(t.getRow(7).getCell(3), defectPath, + IMG_DEFECT_W, IMG_DEFECT_H, grid[3]); + + // 表间间距 + addPara(doc, "", null, SZ_BODY, false, false, null, null, 120, 120); + } + } + + // ============================================================================ + // 四、POI 样式工具方法 + // ============================================================================ + + /** 新建段落并写文字;halfPoints=字号半磅;before/after 单位 twips */ + private XWPFParagraph addPara(XWPFDocument doc, String text, String font, int halfPoints, + boolean bold, boolean italic, String color, + ParagraphAlignment align, Integer before, Integer after) { + XWPFParagraph p = doc.createParagraph(); + if (align != null) { + p.setAlignment(align); + } + if (before != null) { + p.setSpacingBefore(before); + } + if (after != null) { + p.setSpacingAfter(after); + } + // 正文段落行距 276 auto(1.15 倍),与模板 Normal 样式一致: + // 模板封面第二页正是靠它把空行撑满一页;若按默认单倍行距,封面页变矮, + // 「一、巡检基本情况」会被挤到封面页(表格内段落走 styleCell,显式 240) + CTPPr pPr = p.getCTP().isSetPPr() ? p.getCTP().getPPr() : p.getCTP().addNewPPr(); + CTSpacing spacing = pPr.isSetSpacing() ? pPr.getSpacing() : pPr.addNewSpacing(); + spacing.setLine(BigInteger.valueOf(276)); + spacing.setLineRule(STLineSpacingRule.AUTO); + if (text != null && !text.isEmpty()) { + XWPFRun run = p.createRun(); + setRunFont(run, text, font, halfPoints, bold, italic, color, false); + } + return p; + } + + /** 设置 run 字体(含中文 eastAsia)、字号、加粗、斜体、颜色 */ + private void setRunFont(XWPFRun run, String text, String font, int halfPoints, + boolean bold, boolean italic, String color, boolean lineBreak) { + if (lineBreak) { + run.addBreak(); // 换行符在前,实现「巡检⏎结果」这类两行表头 + } + if (text != null) { + run.setText(text); + } + // 字体/字号直接写 w:rPr XML: + // - setFontSize(double) 仅 POI 5.x 有,而运行环境是 poi-ooxml 4.1.2(target/lib), + // 调用会抛 NoSuchMethodError + // - w:sz 单位固定为半磅(24 = 12pt),所有 POI 版本一致 + CTRPr rPr = run.getCTR().isSetRPr() ? run.getCTR().getRPr() : run.getCTR().addNewRPr(); + if (font != null) { + run.setFontFamily(font); + CTFonts fonts = rPr.isSetRFonts() ? rPr.getRFonts() : rPr.addNewRFonts(); + fonts.setEastAsia(font); + fonts.setCs(font); + } + CTHpsMeasure sz = rPr.isSetSz() ? rPr.getSz() : rPr.addNewSz(); + sz.setVal(BigInteger.valueOf(halfPoints)); + CTHpsMeasure szCs = rPr.isSetSzCs() ? rPr.getSzCs() : rPr.addNewSzCs(); + szCs.setVal(BigInteger.valueOf(halfPoints)); + run.setBold(bold); + run.setItalic(italic); + if (color != null) { + run.setColor(color); + } + } + + /** 建表:设置 tblW / 边框 / autofit / 网格列宽 */ + private XWPFTable addTable(XWPFDocument doc, int rows, int cols, int[] gridWidths, + int tblWidth, boolean center) { + XWPFTable table = doc.createTable(rows, cols); + CTTbl tbl = table.getCTTbl(); + CTTblPr tblPr = tbl.getTblPr(); + if (tblPr == null) { + tblPr = tbl.addNewTblPr(); + } + CTTblWidth tblW = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr.addNewTblW(); + tblW.setW(BigInteger.valueOf(tblWidth)); + tblW.setType(STTblWidth.DXA); + + if (center) { + CTJc jc = tblPr.isSetJc() ? tblPr.getJc() : tblPr.addNewJc(); + jc.setVal(STJc.CENTER); + } + + CTTblBorders borders = tblPr.isSetTblBorders() ? tblPr.getTblBorders() : tblPr.addNewTblBorders(); + setBorders(borders); + + CTTblLayoutType layout = tblPr.isSetTblLayout() ? tblPr.getTblLayout() : tblPr.addNewTblLayout(); + layout.setType(STTblLayoutType.AUTOFIT); + + CTTblCellMar cellMar = tblPr.isSetTblCellMar() ? tblPr.getTblCellMar() : tblPr.addNewTblCellMar(); + setCellMar(cellMar, 0, CELL_MAR, 0, CELL_MAR); + + // 网格列宽 + CTTblGrid grid = tbl.getTblGrid(); + if (grid == null) { + grid = tbl.addNewTblGrid(); + } + for (int i = grid.sizeOfGridColArray() - 1; i >= 0; i--) { + grid.removeGridCol(i); + } + for (int w : gridWidths) { + grid.addNewGridCol().setW(BigInteger.valueOf(w)); + } + return table; + } + + private void setBorders(CTTblBorders borders) { + CTBorder top = borders.isSetTop() ? borders.getTop() : borders.addNewTop(); + CTBorder left = borders.isSetLeft() ? borders.getLeft() : borders.addNewLeft(); + CTBorder bottom = borders.isSetBottom() ? borders.getBottom() : borders.addNewBottom(); + CTBorder right = borders.isSetRight() ? borders.getRight() : borders.addNewRight(); + CTBorder insideH = borders.isSetInsideH() ? borders.getInsideH() : borders.addNewInsideH(); + CTBorder insideV = borders.isSetInsideV() ? borders.getInsideV() : borders.addNewInsideV(); + for (CTBorder b : new CTBorder[]{top, left, bottom, right, insideH, insideV}) { + b.setVal(STBorder.SINGLE); + b.setColor(COLOR_BORDER); + b.setSz(BigInteger.ZERO); + b.setSpace(BigInteger.ZERO); + } + } + + private void setBorders(CTTcBorders borders) { + CTBorder top = borders.isSetTop() ? borders.getTop() : borders.addNewTop(); + CTBorder left = borders.isSetLeft() ? borders.getLeft() : borders.addNewLeft(); + CTBorder bottom = borders.isSetBottom() ? borders.getBottom() : borders.addNewBottom(); + CTBorder right = borders.isSetRight() ? borders.getRight() : borders.addNewRight(); + for (CTBorder b : new CTBorder[]{top, left, bottom, right}) { + b.setVal(STBorder.SINGLE); + b.setColor(COLOR_BORDER); + b.setSz(BigInteger.ZERO); + b.setSpace(BigInteger.ZERO); + } + } + + private void setCellMar(CTTblCellMar mar, int top, int left, int bottom, int right) { + CTTblWidth t = mar.isSetTop() ? mar.getTop() : mar.addNewTop(); + t.setW(BigInteger.valueOf(top)); + t.setType(STTblWidth.DXA); + CTTblWidth l = mar.isSetLeft() ? mar.getLeft() : mar.addNewLeft(); + l.setW(BigInteger.valueOf(left)); + l.setType(STTblWidth.DXA); + CTTblWidth b = mar.isSetBottom() ? mar.getBottom() : mar.addNewBottom(); + b.setW(BigInteger.valueOf(bottom)); + b.setType(STTblWidth.DXA); + CTTblWidth r = mar.isSetRight() ? mar.getRight() : mar.addNewRight(); + r.setW(BigInteger.valueOf(right)); + r.setType(STTblWidth.DXA); + } + + private void setCellMar(CTTcMar mar, int top, int left, int bottom, int right) { + CTTblWidth t = mar.isSetTop() ? mar.getTop() : mar.addNewTop(); + t.setW(BigInteger.valueOf(top)); + t.setType(STTblWidth.DXA); + CTTblWidth l = mar.isSetLeft() ? mar.getLeft() : mar.addNewLeft(); + l.setW(BigInteger.valueOf(left)); + l.setType(STTblWidth.DXA); + CTTblWidth b = mar.isSetBottom() ? mar.getBottom() : mar.addNewBottom(); + b.setW(BigInteger.valueOf(bottom)); + b.setType(STTblWidth.DXA); + CTTblWidth r = mar.isSetRight() ? mar.getRight() : mar.addNewRight(); + r.setW(BigInteger.valueOf(right)); + r.setType(STTblWidth.DXA); + } + + /** 行高(atLeast)+ 可选 cantSplit */ + private void setRow(XWPFTableRow row, Integer height, boolean cantSplit) { + // 旧版 poi-ooxml-schemas 中 w:tr 的类型是 CTRow(非 CTr), + // 且 trPr 内元素为数组式访问器(sizeOfXxxArray/getXxxArray/addNewXxx) + CTRow ctRow = row.getCtRow(); + CTTrPr trPr = ctRow.isSetTrPr() ? ctRow.getTrPr() : ctRow.addNewTrPr(); + if (cantSplit && trPr.sizeOfCantSplitArray() == 0) { + trPr.addNewCantSplit(); + } + if (height != null) { + CTHeight h = trPr.sizeOfTrHeightArray() > 0 ? trPr.getTrHeightArray(0) : trPr.addNewTrHeight(); + h.setVal(BigInteger.valueOf(height)); + h.setHRule(STHeightRule.AT_LEAST); + } + } + + /** 行内水平居中(封面签署表用) */ + private void setRowJcCenter(XWPFTableRow row) { + CTRow ctRow = row.getCtRow(); + CTTrPr trPr = ctRow.isSetTrPr() ? ctRow.getTrPr() : ctRow.addNewTrPr(); + CTJc jc = trPr.sizeOfJcArray() > 0 ? trPr.getJcArray(0) : trPr.addNewJc(); + jc.setVal(STJc.CENTER); + } + + /** 水平合并 row 第 from..to 列(gridSpan + 移除多余单元格) */ + private void mergeRowCells(XWPFTable table, int rowIdx, int from, int to) { + XWPFTableRow row = table.getRow(rowIdx); + XWPFTableCell first = row.getCell(from); + CTTcPr tcPr = first.getCTTc().isSetTcPr() ? first.getCTTc().getTcPr() : first.getCTTc().addNewTcPr(); + CTDecimalNumber gs = tcPr.isSetGridSpan() ? tcPr.getGridSpan() : tcPr.addNewGridSpan(); + gs.setVal(BigInteger.valueOf(to - from + 1)); + List tcs = row.getCtRow().getTcList(); + for (int i = to; i > from; i--) { + tcs.remove(i); + } + } + + /** 表头单元格:深蓝底 + 白字 + 加粗 + 居中 */ + private void headerCell(XWPFTableCell cell, String text, int tcw) { + styleCell(cell, text, FONT_BODY, SZ_BODY, true, false, COLOR_WHITE, true, + ParagraphAlignment.CENTER, 0, 0, tcw, null, 0, CELL_MAR, 0, CELL_MAR); + } + + /** 正文单元格:仿宋 12pt,可选居中/行前段后间距 */ + private void bodyCell(XWPFTableCell cell, String text, int tcw, boolean center, + int before, int after) { + styleCell(cell, text, FONT_BODY, SZ_BODY, false, false, null, false, + center ? ParagraphAlignment.CENTER : ParagraphAlignment.LEFT, + before, after, tcw, null, 0, CELL_MAR, 0, CELL_MAR); + } + + private void bodyCell(XWPFTableCell cell, String text, int tcw, boolean center) { + bodyCell(cell, text, tcw, center, 0, 0); + } + + private void bodyCell(XWPFTableCell cell, String text, int tcw) { + bodyCell(cell, text, tcw, false, 0, 0); + } + + /** 图片单元格:细边框 + 垂直居中 + 图片(保持模板尺寸);无图时输出横杠占位 */ + private void imageCell(XWPFTableCell cell, Path imagePath, long w, long h, int tcw) { + styleCell(cell, "", FONT_BODY, SZ_BODY, false, false, null, false, + ParagraphAlignment.LEFT, 120, 120, tcw, null, 0, CELL_MAR, 0, CELL_MAR); + XWPFParagraph p = cell.getParagraphs().get(0); + if (imagePath == null) { + // 无图片时以横杠占位,避免空白单元格 + XWPFRun dashRun = p.createRun(); + setRunFont(dashRun, "--", FONT_BODY, SZ_BODY, false, false, null, false); + return; + } + XWPFRun run = p.createRun(); + try (InputStream is = Files.newInputStream(imagePath)) { + run.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, "img.jpg", (int) w, (int) h); + } catch (Exception e) { + logger.warn("插入巡检图片失败: {}", imagePath, e); + } + } + + /** + * 通用单元格样式:B4C6E7 细边框(sz=0)、垂直居中、可选深蓝底、 + * 列宽、gridSpan、单元格边距 + */ + private void styleCell(XWPFTableCell cell, String text, String font, int halfPoints, + boolean bold, boolean italic, String color, boolean shade, + ParagraphAlignment align, int before, int after, + Integer tcw, Integer gridSpan, + int marTop, int marLeft, int marBottom, int marRight) { + CTTcPr tcPr = cell.getCTTc().isSetTcPr() ? cell.getCTTc().getTcPr() : cell.getCTTc().addNewTcPr(); + + if (tcw != null) { + CTTblWidth w = tcPr.isSetTcW() ? tcPr.getTcW() : tcPr.addNewTcW(); + w.setW(BigInteger.valueOf(tcw)); + w.setType(STTblWidth.DXA); + } + if (gridSpan != null && gridSpan > 1) { + CTDecimalNumber gs = tcPr.isSetGridSpan() ? tcPr.getGridSpan() : tcPr.addNewGridSpan(); + gs.setVal(BigInteger.valueOf(gridSpan)); + } + CTTcBorders borders = tcPr.isSetTcBorders() ? tcPr.getTcBorders() : tcPr.addNewTcBorders(); + setBorders(borders); + if (shade) { + CTShd shd = tcPr.isSetShd() ? tcPr.getShd() : tcPr.addNewShd(); + shd.setVal(STShd.CLEAR); + shd.setColor("auto"); + shd.setFill(COLOR_DARK); + } + CTTcMar tcMar = tcPr.isSetTcMar() ? tcPr.getTcMar() : tcPr.addNewTcMar(); + setCellMar(tcMar, marTop, marLeft, marBottom, marRight); + CTVerticalJc vAlign = tcPr.isSetVAlign() ? tcPr.getVAlign() : tcPr.addNewVAlign(); + vAlign.setVal(STVerticalJc.CENTER); + + // 段落:清空默认段落,写入第一个段落 + List ctPList = cell.getCTTc().getPList(); + for (int i = ctPList.size() - 1; i > 0; i--) { + cell.getCTTc().removeP(i); + } + XWPFParagraph p = cell.getParagraphs().get(0); + for (int i = p.getRuns().size() - 1; i >= 0; i--) { + p.removeRun(i); + } + p.setAlignment(align); + p.setSpacingBefore(before); + p.setSpacingAfter(after); + // 表格内段落与模板一致:单倍行距(w:line=240 auto),不受 Normal 样式 1.15 倍影响 + CTPPr cellPPr = p.getCTP().isSetPPr() ? p.getCTP().getPPr() : p.getCTP().addNewPPr(); + CTSpacing cellSpacing = cellPPr.isSetSpacing() ? cellPPr.getSpacing() : cellPPr.addNewSpacing(); + cellSpacing.setLine(BigInteger.valueOf(240)); + cellSpacing.setLineRule(STLineSpacingRule.AUTO); + if (text != null && !text.isEmpty()) { + XWPFRun run = p.createRun(); + setRunFont(run, text, font, halfPoints, bold, italic, color, false); + } + } + + // ============================================================================ + // 五、数据小工具 + // ============================================================================ + + /** + * 空值/空白字符串转为占位横杠(--),避免报告中出现空白单元格; + * 非空则原样返回。 + */ + private String val(String s) { + return (s == null || s.trim().isEmpty()) ? "--" : s; + } + + private long countByStatus(List list, String status) { + if (list == null) { + return 0; + } + return list.stream().filter(d -> status.equals(d.getPointStatus())).count(); + } + + private long distinctCount(List list, + java.util.function.Function getter) { + if (list == null) { + return 0; + } + return list.stream().map(getter).filter(StringUtils::isNotEmpty).distinct().count(); + } + + /** 点位第一张图片的文件名(imgType=0),无则空串 */ + private String firstImageName(InspectionReportData d) { + if (d.getReportImgList() == null) { + return ""; + } + for (InspectionReportImg img : d.getReportImgList()) { + if ("0".equals(img.getImgType()) && StringUtils.isNotEmpty(img.getImgSrc())) { + String src = img.getImgSrc(); + int idx = src.lastIndexOf('/'); + return idx >= 0 ? src.substring(idx + 1) : src; + } + } + return ""; + } + + /** 点位第 idx 张图片(imgType=0)的临时文件,无则 null */ + private Path firstImagePath(InspectionReportData d, Map tempFileMap, int idx) { + if (d.getReportImgList() == null) { + return null; + } + int found = 0; + for (InspectionReportImg img : d.getReportImgList()) { + if ("0".equals(img.getImgType()) && StringUtils.isNotEmpty(img.getImgSrc())) { + if (found == idx) { + return tempFileMap.get(img.getImgSrc()); + } + found++; + } + } + return null; + } + + /** 点位第 idx 张图片(imgType=0)的临时文件,无则 null */ + private Path getImagePath(InspectionReportData d, Map tempFileMap, int idx) { + if (d.getReportImgList() == null) { + return null; + } + int found = 0; + for (InspectionReportImg img : d.getReportImgList()) { + if ("0".equals(img.getImgType()) && StringUtils.isNotEmpty(img.getImgSrc())) { + if (found == idx) { + return tempFileMap.get(img.getImgSrc()); + } + found++; + } + } + return null; + } + + + private String formatDateTime(Date date) { + return date != null ? DateUtils.format(DateUtils.yyyyMMddHHmmss2, date) : ""; + } + + // ============================================================================ + // 六、上传 / 资源工具(与 PatrolTaskResultMainController 保持一致) + // ============================================================================ + + private void uploadFile(String basePath, String fileName, String suffix, + IOConsumer writer) { + SftpUploadEntity sftpUploadEntity = new SftpUploadEntity(); + sftpUploadEntity.setFilePath(basePath); + sftpUploadEntity.setFileName(fileName); + sftpUploadEntity.setSuffix(suffix); + try { + String filePath = sftpClient.upload(sftpUploadEntity, outputStream -> { + writer.accept(outputStream); + outputStream.flush(); + }); + logger.info("文件上传成功: {}", filePath); + } catch (Exception e) { + logger.error("文件上传失败", e); + } + } + + private Path downloadImageToTemp(String imagePath) { + try { + if (imagePath == null) { + return null; + } + Path tempFile = Files.createTempFile("inspect_img_", ".jpg"); + sftpClient.downLoad(imagePath, inputStream -> + Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING)); + return tempFile; + } catch (Exception e) { + logger.warn("图片下载到临时文件失败: {}", imagePath, e); + return null; + } + } + + /** + * 打开 logo 图片流:优先按 classpath 资源加载(相对路径,图片随包发布), + * 找不到时兼容本地绝对/相对文件路径;两者都无则返回 null。 + */ + private InputStream openLogoStream(String logoPath) throws IOException { + InputStream is = getClass().getClassLoader().getResourceAsStream(logoPath); + if (is != null) { + return is; + } + Path p = Paths.get(logoPath); + if (Files.exists(p)) { + return Files.newInputStream(p); + } + logger.warn("logo 资源不存在: classpath={}, file={}", logoPath, p.toAbsolutePath()); + return null; + } + + private void closeResources(XWPFDocument wordDocument, List tempFiles) { + if (wordDocument != null) { + try { + wordDocument.close(); + logger.info("XWPFDocument 已关闭"); + } catch (IOException e) { + logger.error("关闭XWPFDocument失败", e); + } + } + for (Path tempFile : tempFiles) { + try { + Files.deleteIfExists(tempFile); + } catch (IOException e) { + logger.warn("删除临时文件失败: {}", tempFile, e); + } + } + } +} diff --git a/inspect-main/inspect-main-task/src/main/java/com/inspect/resultmain/controller/PatrolTaskResultMainController.java b/inspect-main/inspect-main-task/src/main/java/com/inspect/resultmain/controller/PatrolTaskResultMainController.java index a9ef223..a6cfa70 100644 --- a/inspect-main/inspect-main-task/src/main/java/com/inspect/resultmain/controller/PatrolTaskResultMainController.java +++ b/inspect-main/inspect-main-task/src/main/java/com/inspect/resultmain/controller/PatrolTaskResultMainController.java @@ -263,7 +263,7 @@ public class PatrolTaskResultMainController extends BaseController { } - @PostMapping({"/updateInfo_shaoxing"}) + @PostMapping({"/updateInfo_shaoxing1"}) public AjaxResult updateInfo_shaoxing( @RequestBody PatrolTaskResultMain resultMain) { long startTime = System.currentTimeMillis(); diff --git a/inspect-main/inspect-main-task/src/main/java/com/inspect/taskstatus/service/impl/PatrolTaskStatusServiceImpl.java b/inspect-main/inspect-main-task/src/main/java/com/inspect/taskstatus/service/impl/PatrolTaskStatusServiceImpl.java index 1652865..fa67491 100644 --- a/inspect-main/inspect-main-task/src/main/java/com/inspect/taskstatus/service/impl/PatrolTaskStatusServiceImpl.java +++ b/inspect-main/inspect-main-task/src/main/java/com/inspect/taskstatus/service/impl/PatrolTaskStatusServiceImpl.java @@ -22,6 +22,7 @@ import com.inspect.taskstatus.mapper.PatrolTaskStatusMapper; import com.inspect.taskstatus.service.IPatrolTaskStatusService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.aop.framework.AopContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -102,6 +103,7 @@ public class PatrolTaskStatusServiceImpl implements IPatrolTaskStatusService { return this.patrolTaskStatusMapper.updatePatrolTaskStatusOfTaskState(patrolTaskStatus); } + @TaskStatusChange(targetState = "1", async = true) // "1"表示已完成状态 public int updatePatrolTaskStatusOfTaskStateAndEndTime(PatrolTaskStatus patrolTaskStatus) { return this.patrolTaskStatusMapper.updatePatrolTaskStatusOfTaskStateAndEndTime(patrolTaskStatus); } @@ -119,6 +121,7 @@ public class PatrolTaskStatusServiceImpl implements IPatrolTaskStatusService { } @Override + @TaskStatusChange(targetState = "1", async = true) // "1"表示已完成状态 public int insertIgnorePatrolTaskStatus(PatrolTaskStatus patrolTaskStatusMain) { return this.patrolTaskStatusMapper.insertIgnorePatrolTaskStatus(patrolTaskStatusMain); } @@ -158,8 +161,8 @@ public class PatrolTaskStatusServiceImpl implements IPatrolTaskStatusService { patrolTaskStatus.setTaskState(state); setNormalTaskStatus(patrolTaskStatus); - // 更新子任务或普通任务 - updatePatrolTaskStatus(patrolTaskStatus); + // 更新子任务或普通任务(走代理调用,确保 @TaskStatusChange 切面在状态变为完成时触发) + ((IPatrolTaskStatusService) AopContext.currentProxy()).updatePatrolTaskStatus(patrolTaskStatus); log.info("updateTaskProgress: {}", patrolTaskStatus); // 如果是子任务,需要同步更新主任务 if (TaskType.SUB.getCode().equals(patrolTaskStatus.getTaskType()) && patrolTaskStatus.getMainId() != null) { @@ -239,8 +242,8 @@ public class PatrolTaskStatusServiceImpl implements IPatrolTaskStatusService { mainTask.setTaskEstimatedTime(mainAlgorithmProgress.toString()); setNormalTaskStatus(mainTask); - // 更新主任务 - patrolTaskStatusMapper.updatePatrolTaskStatus(mainTask); + // 更新主任务(走代理调用,确保 @TaskStatusChange 切面在联合任务完成时触发) + ((IPatrolTaskStatusService) AopContext.currentProxy()).updatePatrolTaskStatus(mainTask); } // 生成巡视归档记录 diff --git a/inspect-main/inspect-main-task/src/main/resources/mapper/task/InspectionReportDataMapper.xml b/inspect-main/inspect-main-task/src/main/resources/mapper/task/InspectionReportDataMapper.xml index 34cd8b7..ef3bbf0 100644 --- a/inspect-main/inspect-main-task/src/main/resources/mapper/task/InspectionReportDataMapper.xml +++ b/inspect-main/inspect-main-task/src/main/resources/mapper/task/InspectionReportDataMapper.xml @@ -15,6 +15,7 @@ + @@ -36,6 +37,7 @@ data_sources, acquisition_time, inspection_results, + inspection_value, point_status, inspection_img, alg_name, @@ -164,11 +166,11 @@ insert into inspection_report_data - (line_id,code,report_id,area,time_interval,eq_name,parts,point_name,data_sources,acquisition_time,inspection_results,point_status,inspection_img,alg_name,task_name,task_patrolled_id,task_result_id) + (line_id,code,report_id,area,time_interval,eq_name,parts,point_name,data_sources,acquisition_time,inspection_results,inspection_value,point_status,inspection_img,alg_name,task_name,task_patrolled_id,task_result_id) values (#{t.lineId}, #{t.code}, #{t.reportId}, #{t.area}, #{t.timeInterval}, #{t.eqName}, #{t.parts}, - #{t.pointName},#{t.dataSources},#{t.acquisitionTime},#{t.inspectionResults},#{t.pointStatus},#{t.inspectionImg},#{t.algName},#{t.taskName},#{t.taskPatrolledId},#{t.taskResultId}) + #{t.pointName},#{t.dataSources},#{t.acquisitionTime},#{t.inspectionResults},#{t.inspectionValue},#{t.pointStatus},#{t.inspectionImg},#{t.algName},#{t.taskName},#{t.taskPatrolledId},#{t.taskResultId}) diff --git a/inspect-main/inspect-main-task/src/main/resources/mapper/task/InspectionReportImgMapper.xml b/inspect-main/inspect-main-task/src/main/resources/mapper/task/InspectionReportImgMapper.xml index 9a0a4e5..360f1cc 100644 --- a/inspect-main/inspect-main-task/src/main/resources/mapper/task/InspectionReportImgMapper.xml +++ b/inspect-main/inspect-main-task/src/main/resources/mapper/task/InspectionReportImgMapper.xml @@ -9,12 +9,13 @@ + - select line_id, report_info_id, img, img_src, creat_time, img_type + select line_id, report_info_id, img, img_src, image_normal_url_path, creat_time, img_type from inspection_report_img @@ -87,9 +88,9 @@ - insert into inspection_report_img (line_id, report_info_id, img, img_src, creat_time, img_type) values + insert into inspection_report_img (line_id, report_info_id, img, img_src, image_normal_url_path, creat_time, img_type) values - (#{t.lineId}, #{t.reportInfoId}, #{t.img}, #{t.imgSrc}, #{t.creatTime}, #{t.imgType}) + (#{t.lineId}, #{t.reportInfoId}, #{t.img}, #{t.imgSrc}, #{t.imageNormalUrlPath}, #{t.creatTime}, #{t.imgType}) diff --git a/inspect-main/inspect-main-task/src/main/resources/report/logo.png b/inspect-main/inspect-main-task/src/main/resources/report/logo.png new file mode 100644 index 0000000..a83f630 Binary files /dev/null and b/inspect-main/inspect-main-task/src/main/resources/report/logo.png differ