From d24942ee210bcc108fe9218c3a6c448afa613d00 Mon Sep 17 00:00:00 2001
From: 云 <2163098428@qq.com>
Date: 星期二, 21 四月 2026 14:10:33 +0800
Subject: [PATCH] feat(inspectiontask): 新增巡检结果字段并支持批量操作

---
 src/main/java/com/ruoyi/inspectiontask/service/impl/InspectionTaskServiceImpl.java |  611 +++++++++++++++++++++++++++++++++++++++----------------
 1 files changed, 429 insertions(+), 182 deletions(-)

diff --git a/src/main/java/com/ruoyi/inspectiontask/service/impl/InspectionTaskServiceImpl.java b/src/main/java/com/ruoyi/inspectiontask/service/impl/InspectionTaskServiceImpl.java
index a84a70d..b49533a 100644
--- a/src/main/java/com/ruoyi/inspectiontask/service/impl/InspectionTaskServiceImpl.java
+++ b/src/main/java/com/ruoyi/inspectiontask/service/impl/InspectionTaskServiceImpl.java
@@ -5,33 +5,48 @@
 import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
-import com.ruoyi.basic.dto.StorageBlobDTO;
-import com.ruoyi.basic.mapper.StorageAttachmentMapper;
-import com.ruoyi.basic.mapper.StorageBlobMapper;
-import com.ruoyi.basic.pojo.StorageAttachment;
-import com.ruoyi.basic.pojo.StorageBlob;
-import com.ruoyi.basic.service.StorageAttachmentService;
-import com.ruoyi.common.utils.MinioUtils;
+import com.ruoyi.common.enums.FileNameType;
 import com.ruoyi.common.utils.SecurityUtils;
 import com.ruoyi.common.utils.StringUtils;
 import com.ruoyi.common.utils.bean.BeanUtils;
+import com.ruoyi.device.mapper.DeviceAreaMapper;
+import com.ruoyi.device.mapper.DeviceLedgerMapper;
+import com.ruoyi.device.mapper.DeviceRepairMapper;
+import com.ruoyi.device.pojo.DeviceArea;
+import com.ruoyi.device.pojo.DeviceLedger;
+import com.ruoyi.device.pojo.DeviceRepair;
 import com.ruoyi.inspectiontask.dto.InspectionTaskDto;
 import com.ruoyi.inspectiontask.mapper.InspectionTaskMapper;
 import com.ruoyi.inspectiontask.pojo.InspectionTask;
 import com.ruoyi.inspectiontask.service.InspectionTaskService;
 import com.ruoyi.project.system.domain.SysUser;
 import com.ruoyi.project.system.mapper.SysUserMapper;
+import com.ruoyi.sales.mapper.CommonFileMapper;
+import com.ruoyi.sales.pojo.CommonFile;
+import com.ruoyi.sales.service.impl.CommonFileServiceImpl;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
 
+import java.io.IOException;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
 import java.time.format.DateTimeFormatter;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
 import java.util.function.Function;
 import java.util.stream.Collectors;
-
-import static com.ruoyi.common.constant.StorageAttachmentConstants.StorageAttachmentFile;
-import static com.ruoyi.common.enums.StorageAttachmentRecordType.InspectionTasks;
 
 /**
  * @author :yys
@@ -41,223 +56,455 @@
 @Slf4j
 public class InspectionTaskServiceImpl extends ServiceImpl<InspectionTaskMapper, InspectionTask> implements InspectionTaskService {
 
+    private static final int INSPECTION_STATUS_PENDING = 1;
+    private static final int INSPECTION_STATUS_COMPLETED = 2;
+    private static final int INSPECTION_RESULT_NORMAL = 1;
+    private static final int INSPECTION_RESULT_ABNORMAL = 2;
+    private static final int DEVICE_REPAIR_STATUS_PENDING = 0;
+    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
 
     @Autowired
     private InspectionTaskMapper inspectionTaskMapper;
 
     @Autowired
-    private StorageAttachmentService storageAttachmentService;
-
-    @Autowired
-    private StorageBlobMapper storageBlobMapper;
-
-    @Autowired
-    private StorageAttachmentMapper storageAttachmentMapper;
-
-    @Autowired
-    private MinioUtils minioUtils;
-
-    @Autowired
     private SysUserMapper sysUserMapper;
+
+    @Autowired
+    private CommonFileMapper commonFileMapper;
+
+    @Autowired
+    private CommonFileServiceImpl commonFileService;
+
+    @Autowired
+    private DeviceLedgerMapper deviceLedgerMapper;
+
+    @Autowired
+    private DeviceAreaMapper deviceAreaMapper;
+
+    @Autowired
+    private DeviceRepairMapper deviceRepairMapper;
 
     @Override
     public IPage<InspectionTaskDto> selectInspectionTaskList(Page<InspectionTask> page, InspectionTaskDto inspectionTaskDto) {
         LambdaQueryWrapper<InspectionTask> queryWrapper = new LambdaQueryWrapper<>();
+        queryWrapper.orderByAsc(InspectionTask::getTimingId);
         queryWrapper.orderByDesc(InspectionTask::getCreateTime);
         if (StringUtils.isNotBlank(inspectionTaskDto.getTaskName())) {
             queryWrapper.like(InspectionTask::getTaskName, inspectionTaskDto.getTaskName());
         }
-        IPage<InspectionTask> entityPage = inspectionTaskMapper.selectPage(page, queryWrapper);
-
-        //  鏃犳暟鎹彁鍓嶈繑鍥�
-        if (CollectionUtils.isEmpty(entityPage.getRecords())) {
-            return new Page<>(entityPage.getCurrent(), entityPage.getSize(), entityPage.getTotal());
+        if (inspectionTaskDto.getAreaId() != null) {
+            queryWrapper.eq(InspectionTask::getAreaId, inspectionTaskDto.getAreaId());
         }
-        // 鑾峰彇id闆嗗悎
-        List<Long> ids = entityPage.getRecords().stream().map(InspectionTask::getId).collect(Collectors.toList());
-        //鐧昏浜篿ds
-        List<Long> registrantIds = entityPage.getRecords().stream().map(InspectionTask::getRegistrantId).collect(Collectors.toList());
-        // 鎵归噺鏌ヨ鐧昏浜�
-        Map<Long, SysUser> sysUserMap;
-        if (!registrantIds.isEmpty()) {
-            List<SysUser> sysUsers = sysUserMapper.selectUsersByIds(registrantIds);
-            sysUserMap = sysUsers.stream().collect(Collectors.toMap(SysUser::getUserId, Function.identity()));
+
+        LocalDateTime createTimeStart = inspectionTaskDto.getCreateTimeStart();
+        LocalDateTime createTimeEnd = inspectionTaskDto.getCreateTimeEnd();
+        if (createTimeStart == null && createTimeEnd == null) {
+            LocalDate today = LocalDate.now();
+            createTimeStart = today.atStartOfDay();
+            createTimeEnd = today.atTime(23, 59, 59);
+        }
+        if (createTimeStart != null) {
+            queryWrapper.ge(InspectionTask::getCreateTime, createTimeStart);
+        }
+        if (createTimeEnd != null) {
+            queryWrapper.le(InspectionTask::getCreateTime, createTimeEnd);
+        }
+
+        List<InspectionTask> inspectionTasks = inspectionTaskMapper.selectList(queryWrapper);
+        if (CollectionUtils.isEmpty(inspectionTasks)) {
+            return new Page<>(page.getCurrent(), page.getSize(), 0);
+        }
+
+        List<InspectionTaskDto> mergedRecords = mergeInspectionTasksByTimingId(inspectionTasks);
+        return buildPagedResult(page, mergedRecords);
+    }
+
+    @Override
+    public List<InspectionTaskDto> selectInspectionTaskRecordListByTimingId(Long timingId) {
+        LambdaQueryWrapper<InspectionTask> queryWrapper = new LambdaQueryWrapper<>();
+        LocalDate today = LocalDate.now();
+        queryWrapper.eq(InspectionTask::getTimingId, timingId);
+        queryWrapper.ge(InspectionTask::getCreateTime, today.atStartOfDay());
+        queryWrapper.le(InspectionTask::getCreateTime, today.atTime(23, 59, 59));
+        queryWrapper.orderByDesc(InspectionTask::getCreateTime);
+        queryWrapper.orderByDesc(InspectionTask::getId);
+
+        List<InspectionTask> records = inspectionTaskMapper.selectList(queryWrapper);
+        if (CollectionUtils.isEmpty(records)) {
+            return new ArrayList<>();
+        }
+        return buildInspectionTaskDtoList(records);
+    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public int addOrEditInspectionTask(List<InspectionTaskDto> inspectionTaskDtoList) throws IOException {
+        if (CollectionUtils.isEmpty(inspectionTaskDtoList)) {
+            return 0;
+        }
+
+        int affected = 0;
+        // 鍚屼竴娆℃彁浜ら噷鍚屼竴鍖哄煙鍙繚鐣欎竴鏉″紓甯歌褰曪紝鐢ㄤ簬鍚庣画鐢熸垚涓�寮犵淮淇崟銆�
+        Map<Long, InspectionTaskDto> abnormalAreaTaskMap = new LinkedHashMap<>();
+        for (InspectionTaskDto inspectionTaskDto : inspectionTaskDtoList) {
+            if (inspectionTaskDto == null) {
+                continue;
+            }
+            InspectionTask savedTask = saveOrUpdateInspectionTask(inspectionTaskDto);
+            affected++;
+            if (Objects.equals(savedTask.getInspectionResult(), INSPECTION_RESULT_ABNORMAL) && savedTask.getAreaId() != null) {
+                abnormalAreaTaskMap.putIfAbsent(savedTask.getAreaId(), copyRepairSourceTask(inspectionTaskDto, savedTask));
+            }
+        }
+        createDeviceRepairRecords(abnormalAreaTaskMap);
+        return affected;
+    }
+
+    private InspectionTask saveOrUpdateInspectionTask(InspectionTaskDto inspectionTaskDto) throws IOException {
+        InspectionTask inspectionTask = new InspectionTask();
+        BeanUtils.copyProperties(inspectionTaskDto, inspectionTask);
+        boolean hasUploadedFiles = CollectionUtils.isNotEmpty(inspectionTaskDto.getTempFileIds());
+
+        if (inspectionTask.getAreaId() == null && inspectionTask.getTaskId() != null) {
+            DeviceLedger deviceLedger = deviceLedgerMapper.selectById(Long.valueOf(inspectionTask.getTaskId()));
+            if (deviceLedger != null) {
+                inspectionTask.setAreaId(deviceLedger.getAreaId());
+            }
+        }
+
+        inspectionTask.setRegistrantId(SecurityUtils.getLoginUser().getUserId());
+        inspectionTask.setRegistrant(SecurityUtils.getLoginUser().getUsername());
+
+        if (inspectionTaskDto.getId() == null) {
+            inspectionTask.setInspectionStatus(hasUploadedFiles ? INSPECTION_STATUS_COMPLETED : INSPECTION_STATUS_PENDING);
+            inspectionTaskMapper.insert(inspectionTask);
         } else {
-            sysUserMap = new HashMap<>();
+            if (hasUploadedFiles) {
+                inspectionTask.setInspectionStatus(INSPECTION_STATUS_COMPLETED);
+            } else if (inspectionTask.getInspectionStatus() == null) {
+                InspectionTask existingTask = inspectionTaskMapper.selectById(inspectionTaskDto.getId());
+                if (existingTask != null) {
+                    inspectionTask.setInspectionStatus(existingTask.getInspectionStatus());
+                }
+            }
+            inspectionTaskMapper.updateById(inspectionTask);
         }
-        //宸℃浜篿ds
-        List<String> inspectorIds = entityPage.getRecords().stream().map(InspectionTask::getInspectorId).collect(Collectors.toList());
 
-        //鑾峰彇鎵�鏈変笉閲嶅鐨勭敤鎴稩D
-        Set<Long> allUserIds = entityPage.getRecords().stream()
-                .map(InspectionTask::getInspectorId) // 鑾峰彇"2,3"杩欐牱鐨勫瓧绗︿覆
-                .filter(StringUtils::isNotBlank)
-                .flatMap(idsStr -> Arrays.stream(idsStr.split(",")))
-                .map(idStr -> {
-                    try {
-                        return Long.parseLong(idStr.trim());
-                    } catch (NumberFormatException e) {
-                        return null;
-                    }
-                })
-                .filter(Objects::nonNull)
-                .collect(Collectors.toSet());
+        commonFileService.migrateTempFilesToFormal(inspectionTask.getId(), inspectionTaskDto.getTempFileIds());
+        return inspectionTask;
+    }
 
-        // 浣跨敤SQL鎵归噺鏌ヨ鐢ㄦ埛淇℃伅
-        Map<Long, String> userIdToNameMap = allUserIds.isEmpty()
-                ? Collections.emptyMap()
-                : sysUserMapper.selectUsersByIds(new ArrayList<>(allUserIds))
-                .stream()
-                .collect(Collectors.toMap(
-                        SysUser::getUserId,
-                        SysUser::getNickName,
-                        (existing, replacement) -> existing));
+    private InspectionTaskDto copyRepairSourceTask(InspectionTaskDto sourceDto, InspectionTask savedTask) {
+        InspectionTaskDto taskDto = new InspectionTaskDto();
+        BeanUtils.copyProperties(sourceDto, taskDto);
+        taskDto.setId(savedTask.getId());
+        taskDto.setAreaId(savedTask.getAreaId());
+        taskDto.setTaskId(savedTask.getTaskId());
+        taskDto.setTaskName(savedTask.getTaskName());
+        taskDto.setRemarks(savedTask.getRemarks());
+        taskDto.setInspectionLocation(savedTask.getInspectionLocation());
+        return taskDto;
+    }
 
-        //澶勭悊闄勪欢
-        Map<Long, List<StorageAttachment>> attachmentsMap = storageAttachmentMapper.selectList(new LambdaQueryWrapper<StorageAttachment>().in(StorageAttachment::getRecordId, ids)
-                        .eq(StorageAttachment::getRecordType, InspectionTasks.ordinal()))
-                .stream()
-                .collect(Collectors.groupingBy(StorageAttachment::getRecordId));
-        //  鎵归噺鏌ヨ鎵�鏈夐渶瑕佺殑鏂囦欢鏁版嵁
-        Set<Long> blobIds = attachmentsMap.values()
-                .stream()
-                .flatMap(List::stream)
-                .map(StorageAttachment::getStorageBlobId)
-                .collect(Collectors.toSet());
-        Map<Long, StorageBlob> blobMap = blobIds.isEmpty()
-                ? Collections.emptyMap()
-                : storageBlobMapper.selectList(new LambdaQueryWrapper<StorageBlob>().in(StorageBlob::getId, blobIds))
-                .stream()
-                .collect(Collectors.toMap(StorageBlob::getId, Function.identity()));
+    private void createDeviceRepairRecords(Map<Long, InspectionTaskDto> abnormalAreaTaskMap) {
+        if (abnormalAreaTaskMap.isEmpty()) {
+            return;
+        }
 
-        List<InspectionTaskDto> dtoList = entityPage.getRecords().stream().map(inspectionTask -> {
-            InspectionTaskDto dto = new InspectionTaskDto();
-            BeanUtils.copyProperties(inspectionTask, dto);  // 澶嶅埗涓诲璞″睘鎬�
+        LocalDate today = LocalDate.now();
+        LocalDateTime startOfDay = today.atStartOfDay();
+        LocalDateTime endOfDay = today.atTime(23, 59, 59);
 
-            // 璁剧疆鐧昏浜�
-            SysUser sysUser = sysUserMap.get(inspectionTask.getRegistrantId());
-            if (sysUser != null) {
-                dto.setRegistrant(sysUser.getNickName());
-            }
-            // 澶勭悊宸℃浜哄悕绉�
-            if (StringUtils.isNotBlank(inspectionTask.getInspectorId())) {
-                String inspectorNames = Arrays.stream(inspectionTask.getInspectorId().split(","))
-                        .map(String::trim)
-                        .map(idStr -> {
-                            try {
-                                Long userId = Long.parseLong(idStr);
-                                return userIdToNameMap.getOrDefault(userId, "鏈煡鐢ㄦ埛(" + idStr + ")");
-                            } catch (NumberFormatException e) {
-                                return "鏃犳晥ID(" + idStr + ")";
-                            }
-                        })
-                        .collect(Collectors.joining(","));
-                dto.setInspector(inspectorNames);
+        for (Map.Entry<Long, InspectionTaskDto> entry : abnormalAreaTaskMap.entrySet()) {
+            Long areaId = entry.getKey();
+            InspectionTaskDto inspectionTaskDto = entry.getValue();
+
+            // 褰撳ぉ璇ュ尯鍩熷凡缁忔湁寰呯淮淇崟鏃剁洿鎺ヨ烦杩囷紝閬垮厤閲嶅鐢熸垚銆�
+            Long count = deviceRepairMapper.selectCount(new LambdaQueryWrapper<DeviceRepair>()
+                    .eq(DeviceRepair::getAreaId, areaId)
+                    .eq(DeviceRepair::getStatus, DEVICE_REPAIR_STATUS_PENDING)
+                    .ge(DeviceRepair::getCreateTime, startOfDay)
+                    .le(DeviceRepair::getCreateTime, endOfDay));
+            if (count != null && count > 0) {
+                continue;
             }
 
-            dto.setDateStr(inspectionTask.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
+            DeviceRepair deviceRepair = new DeviceRepair();
+            deviceRepair.setAreaId(areaId);
+            if (inspectionTaskDto.getTaskId() != null) {
+                deviceRepair.setDeviceLedgerId(Long.valueOf(inspectionTaskDto.getTaskId()));
+            }
+            deviceRepair.setRepairName(SecurityUtils.getLoginUser().getUsername());
+            deviceRepair.setRepairTime(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()));
+            deviceRepair.setStatus(DEVICE_REPAIR_STATUS_PENDING);
+            deviceRepair.setRemark(buildRepairRemark(inspectionTaskDto));
+            deviceRepairMapper.insert(deviceRepair);
+        }
+    }
 
-            // 鍒濆鍖栦笁涓檮浠跺垪琛�
-            dto.setBeforeProduction(new ArrayList<>());
-            dto.setAfterProduction(new ArrayList<>());
-            dto.setProductionIssues(new ArrayList<>());
+    private String buildRepairRemark(InspectionTaskDto inspectionTaskDto) {
+        List<String> parts = new ArrayList<>();
+        if (StringUtils.isNotBlank(inspectionTaskDto.getTaskName())) {
+            parts.add("宸℃浠诲姟:" + inspectionTaskDto.getTaskName());
+        }
+        if (StringUtils.isNotBlank(inspectionTaskDto.getInspectionLocation())) {
+            parts.add("宸℃鍦扮偣:" + inspectionTaskDto.getInspectionLocation());
+        }
+        if (StringUtils.isNotBlank(inspectionTaskDto.getRemarks())) {
+            parts.add("寮傚父璇存槑:" + inspectionTaskDto.getRemarks());
+        } else {
+            parts.add("寮傚父璇存槑:宸℃寮傚父鑷姩鐢熸垚缁翠慨鍗�");
+        }
+        return String.join("锛�", parts);
+    }
 
-            // 澶勭悊闄勪欢鍒嗙被
-            Optional.ofNullable(attachmentsMap.get(inspectionTask.getId()))
-                    .orElse(Collections.emptyList())
-                    .forEach(attachment -> {
-                        StorageBlob blob = blobMap.get(attachment.getStorageBlobId());
-                        if (blob != null) {
-                            // 鍒涘缓闄勪欢DTO
-                            StorageBlobDTO blobDto = createBlobDto(blob);
+    private IPage<InspectionTaskDto> buildPagedResult(Page<InspectionTask> page, List<InspectionTaskDto> mergedRecords) {
+        long requestedSize = page.getSize();
+        long size = requestedSize <= 0 ? mergedRecords.size() : requestedSize;
+        long current = page.getCurrent() <= 0 ? 1 : page.getCurrent();
+        int fromIndex = (int) Math.min((current - 1) * size, mergedRecords.size());
+        int toIndex = (int) Math.min(fromIndex + size, mergedRecords.size());
 
-                            // 鏍规嵁type鍒嗙被
-                            switch ((int) blob.getType().longValue()) {
-                                case 0:
-                                    dto.getBeforeProduction().add(blobDto);
-                                    break;
-                                case 1:
-                                    dto.getAfterProduction().add(blobDto);
-                                    break;
-                                case 2:
-                                    dto.getProductionIssues().add(blobDto);
-                                    break;
-                                default:
-                                    // 鍙�夛細璁板綍鏈垎绫荤被鍨�
-                                    break;
-                            }
-                        }
-                    });
-
-            return dto;
-        }).collect(Collectors.toList());
-
-        // 7. 鏋勫缓杩斿洖鍒嗛〉瀵硅薄
-        IPage<InspectionTaskDto> resultPage = new Page<>();
-        BeanUtils.copyProperties(entityPage, resultPage);
-        resultPage.setRecords(dtoList);
+        Page<InspectionTaskDto> resultPage = new Page<>(current, size, mergedRecords.size());
+        resultPage.setRecords(mergedRecords.subList(fromIndex, toIndex));
         return resultPage;
     }
 
-    // 鎻愬彇鍒涘缓BlobDTO鐨勫叕鍏辨柟娉�
-    private StorageBlobDTO createBlobDto(StorageBlob blob) {
-        StorageBlobDTO dto = new StorageBlobDTO();
-        BeanUtils.copyProperties(blob, dto);
+    private List<InspectionTaskDto> mergeInspectionTasksByTimingId(List<InspectionTask> inspectionTasks) {
+        Map<Long, String> areaNameMap = buildAreaNameMap(inspectionTasks.stream()
+                .map(InspectionTask::getAreaId)
+                .filter(Objects::nonNull)
+                .collect(Collectors.toSet()));
+        Map<Long, SysUser> registrantMap = buildRegistrantMap(inspectionTasks);
+        Map<Long, String> inspectorNameMap = buildInspectorNameMap(inspectionTasks);
+        Map<Long, List<CommonFile>> commonFileMap = buildCommonFileMap(inspectionTasks);
 
-        // 璁剧疆URL
-        dto.setUrl(minioUtils.getPreviewUrls(
-                blob.getBucketFilename(),
-                blob.getBucketName(),
-                true
-        ));
+        Map<String, List<InspectionTask>> groupedTasks = inspectionTasks.stream()
+                .collect(Collectors.groupingBy(this::buildTimingGroupKey, LinkedHashMap::new, Collectors.toList()));
 
-        // 璁剧疆涓嬭浇URL
-        dto.setDownloadUrl(minioUtils.getDownloadUrls(
-                blob.getBucketFilename(),
-                blob.getBucketName(),
-                blob.getOriginalFilename(),
-                true
-        ));
+        // 鍒楄〃鎺ュ彛鎸� timingId 鑱氬悎锛屽悓涓�涓畾鏃朵换鍔″彧杩斿洖涓�鏉°��
+        return groupedTasks.values().stream()
+                .map(tasks -> buildMergedInspectionTaskDto(tasks, areaNameMap, registrantMap, inspectorNameMap, commonFileMap))
+                .sorted(Comparator.comparing(InspectionTaskDto::getTimingId, Comparator.nullsLast(Long::compareTo))
+                        .thenComparing(InspectionTaskDto::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder())))
+                .collect(Collectors.toList());
+    }
+
+    private List<InspectionTaskDto> buildInspectionTaskDtoList(List<InspectionTask> records) {
+        Map<Long, String> areaNameMap = buildAreaNameMap(records.stream()
+                .map(InspectionTask::getAreaId)
+                .filter(Objects::nonNull)
+                .collect(Collectors.toSet()));
+        Map<Long, SysUser> registrantMap = buildRegistrantMap(records);
+        Map<Long, String> inspectorNameMap = buildInspectorNameMap(records);
+        Map<Long, List<CommonFile>> commonFileMap = buildCommonFileMap(records);
+
+        return records.stream()
+                .map(task -> buildInspectionTaskDto(task, areaNameMap, registrantMap, inspectorNameMap, commonFileMap))
+                .collect(Collectors.toList());
+    }
+
+    private Map<Long, SysUser> buildRegistrantMap(List<InspectionTask> tasks) {
+        List<Long> registrantIds = tasks.stream()
+                .map(InspectionTask::getRegistrantId)
+                .filter(Objects::nonNull)
+                .distinct()
+                .collect(Collectors.toList());
+        if (registrantIds.isEmpty()) {
+            return new HashMap<>();
+        }
+        return sysUserMapper.selectUsersByIds(registrantIds).stream()
+                .collect(Collectors.toMap(SysUser::getUserId, Function.identity()));
+    }
+
+    private Map<Long, String> buildInspectorNameMap(List<InspectionTask> tasks) {
+        Set<Long> allUserIds = tasks.stream()
+                .map(InspectionTask::getInspectorId)
+                .filter(StringUtils::isNotBlank)
+                .flatMap(idsStr -> Arrays.stream(idsStr.split(",")))
+                .map(String::trim)
+                .map(this::parseLongSafely)
+                .filter(Objects::nonNull)
+                .collect(Collectors.toSet());
+        if (allUserIds.isEmpty()) {
+            return Collections.emptyMap();
+        }
+        return sysUserMapper.selectUsersByIds(new ArrayList<>(allUserIds)).stream()
+                .collect(Collectors.toMap(SysUser::getUserId, SysUser::getNickName, (left, right) -> left));
+    }
+
+    private Map<Long, List<CommonFile>> buildCommonFileMap(List<InspectionTask> tasks) {
+        List<Long> ids = tasks.stream()
+                .map(InspectionTask::getId)
+                .filter(Objects::nonNull)
+                .collect(Collectors.toList());
+        if (ids.isEmpty()) {
+            return Collections.emptyMap();
+        }
+        List<CommonFile> commonFiles = commonFileMapper.selectList(new LambdaQueryWrapper<CommonFile>()
+                .in(CommonFile::getCommonId, ids)
+                .in(CommonFile::getType, Arrays.asList(
+                        FileNameType.INSPECTION.getValue(),
+                        FileNameType.INSPECTION_PRODUCTION_BEFORE.getValue(),
+                        FileNameType.INSPECTION_PRODUCTION_AFTER.getValue()
+                )));
+        if (commonFiles == null || commonFiles.isEmpty()) {
+            return Collections.emptyMap();
+        }
+        return commonFiles.stream().collect(Collectors.groupingBy(CommonFile::getCommonId));
+    }
+
+    private String buildTimingGroupKey(InspectionTask inspectionTask) {
+        return inspectionTask.getTimingId() != null ? "TIMING_" + inspectionTask.getTimingId() : "TASK_" + inspectionTask.getId();
+    }
+
+    private InspectionTaskDto buildMergedInspectionTaskDto(List<InspectionTask> tasks,
+                                                           Map<Long, String> areaNameMap,
+                                                           Map<Long, SysUser> registrantMap,
+                                                           Map<Long, String> inspectorNameMap,
+                                                           Map<Long, List<CommonFile>> commonFileMap) {
+        List<InspectionTask> sortedTasks = tasks.stream()
+                .sorted(Comparator.comparing(InspectionTask::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder()))
+                        .thenComparing(InspectionTask::getId, Comparator.nullsLast(Comparator.reverseOrder())))
+                .collect(Collectors.toList());
+        InspectionTask latestTask = sortedTasks.get(0);
+
+        InspectionTaskDto dto = new InspectionTaskDto();
+        BeanUtils.copyProperties(latestTask, dto);
+        dto.setAreaName(areaNameMap.get(latestTask.getAreaId()));
+        dto.setTaskName(joinDistinctValues(sortedTasks.stream().map(InspectionTask::getTaskName).collect(Collectors.toList())));
+        dto.setInspectorId(joinDistinctValues(sortedTasks.stream()
+                .map(InspectionTask::getInspectorId)
+                .filter(StringUtils::isNotBlank)
+                .flatMap(idsStr -> Arrays.stream(idsStr.split(",")))
+                .map(String::trim)
+                .collect(Collectors.toList())));
+        dto.setInspector(joinDistinctValues(sortedTasks.stream()
+                .map(InspectionTask::getInspectorId)
+                .filter(StringUtils::isNotBlank)
+                .flatMap(idsStr -> Arrays.stream(idsStr.split(",")))
+                .map(String::trim)
+                .map(idStr -> resolveInspectorName(idStr, inspectorNameMap))
+                .collect(Collectors.toList())));
+        dto.setRegistrant(joinDistinctValues(sortedTasks.stream()
+                .map(InspectionTask::getRegistrantId)
+                .filter(Objects::nonNull)
+                .map(registrantMap::get)
+                .filter(Objects::nonNull)
+                .map(SysUser::getNickName)
+                .collect(Collectors.toList())));
+        dto.setRemarks(joinDistinctValues(sortedTasks.stream().map(InspectionTask::getRemarks).collect(Collectors.toList())));
+        dto.setInspectionLocation(joinDistinctValues(sortedTasks.stream().map(InspectionTask::getInspectionLocation).collect(Collectors.toList())));
+        dto.setFrequencyType(joinDistinctValues(sortedTasks.stream().map(InspectionTask::getFrequencyType).collect(Collectors.toList())));
+        dto.setFrequencyDetail(joinDistinctValues(sortedTasks.stream().map(InspectionTask::getFrequencyDetail).collect(Collectors.toList())));
+        dto.setInspectionStatus(sortedTasks.stream().allMatch(task -> Objects.equals(task.getInspectionStatus(), INSPECTION_STATUS_COMPLETED))
+                ? INSPECTION_STATUS_COMPLETED : INSPECTION_STATUS_PENDING);
+
+        List<Integer> inspectionResults = sortedTasks.stream()
+                .map(InspectionTask::getInspectionResult)
+                .filter(Objects::nonNull)
+                .collect(Collectors.toList());
+        if (inspectionResults.isEmpty()) {
+            dto.setInspectionResult(null);
+        } else {
+            dto.setInspectionResult(inspectionResults.stream().anyMatch(result -> Objects.equals(result, INSPECTION_RESULT_ABNORMAL))
+                    ? INSPECTION_RESULT_ABNORMAL : INSPECTION_RESULT_NORMAL);
+        }
+
+        if (dto.getCreateTime() != null) {
+            dto.setDateStr(dto.getCreateTime().format(DATE_FORMATTER));
+        }
+
+        List<CommonFile> mergedFiles = sortedTasks.stream()
+                .map(InspectionTask::getId)
+                .filter(Objects::nonNull)
+                .map(commonFileMap::get)
+                .filter(Objects::nonNull)
+                .flatMap(List::stream)
+                .collect(Collectors.toList());
+        dto.setCommonFileList(filterCommonFilesByType(mergedFiles, FileNameType.INSPECTION.getValue()));
+        dto.setCommonFileListBefore(filterCommonFilesByType(mergedFiles, FileNameType.INSPECTION_PRODUCTION_BEFORE.getValue()));
+        dto.setCommonFileListAfter(filterCommonFilesByType(mergedFiles, FileNameType.INSPECTION_PRODUCTION_AFTER.getValue()));
         return dto;
     }
 
-    @Override
-    public int addOrEditInspectionTask(InspectionTaskDto inspectionTaskDto) {
-        InspectionTask inspectionTask = new InspectionTask();
-        BeanUtils.copyProperties(inspectionTaskDto, inspectionTask);
-        inspectionTask.setRegistrantId(SecurityUtils.getLoginUser().getUserId());
-        inspectionTask.setRegistrant(SecurityUtils.getLoginUser().getUsername());
-        int i;
-        if (Objects.isNull(inspectionTaskDto.getId())) {
-            i = inspectionTaskMapper.insert(inspectionTask);
-        } else {
-            i = inspectionTaskMapper.updateById(inspectionTask);
+    private InspectionTaskDto buildInspectionTaskDto(InspectionTask task,
+                                                     Map<Long, String> areaNameMap,
+                                                     Map<Long, SysUser> registrantMap,
+                                                     Map<Long, String> inspectorNameMap,
+                                                     Map<Long, List<CommonFile>> commonFileMap) {
+        InspectionTaskDto dto = new InspectionTaskDto();
+        BeanUtils.copyProperties(task, dto);
+        dto.setAreaName(areaNameMap.get(task.getAreaId()));
+
+        SysUser registrant = registrantMap.get(task.getRegistrantId());
+        if (registrant != null) {
+            dto.setRegistrant(registrant.getNickName());
+        }
+        if (StringUtils.isNotBlank(task.getInspectorId())) {
+            dto.setInspector(Arrays.stream(task.getInspectorId().split(","))
+                    .map(String::trim)
+                    .map(idStr -> resolveInspectorName(idStr, inspectorNameMap))
+                    .collect(Collectors.joining("锛�")));
+        }
+        if (task.getCreateTime() != null) {
+            dto.setDateStr(task.getCreateTime().format(DATE_FORMATTER));
         }
 
-        if (inspectionTaskDto.getStorageBlobDTO() != null && !inspectionTaskDto.getStorageBlobDTO().isEmpty()) {
-            List<StorageAttachment> attachments = new ArrayList<>();
+        List<CommonFile> commonFiles = commonFileMap.getOrDefault(task.getId(), Collections.emptyList());
+        dto.setCommonFileList(filterCommonFilesByType(commonFiles, FileNameType.INSPECTION.getValue()));
+        dto.setCommonFileListBefore(filterCommonFilesByType(commonFiles, FileNameType.INSPECTION_PRODUCTION_BEFORE.getValue()));
+        dto.setCommonFileListAfter(filterCommonFilesByType(commonFiles, FileNameType.INSPECTION_PRODUCTION_AFTER.getValue()));
+        return dto;
+    }
 
-            for (StorageBlobDTO storageBlobDTO : inspectionTaskDto.getStorageBlobDTO()) {
-                StorageAttachment storageAttachment = new StorageAttachment(
-                        StorageAttachmentFile,
-                        (long) InspectionTasks.ordinal(),
-                        inspectionTask.getId()
-                );
-                storageAttachment.setStorageBlobDTO(storageBlobDTO);
-                attachments.add(storageAttachment);
-            }
-            storageAttachmentService.saveStorageAttachment(attachments, inspectionTask.getId(), InspectionTasks, StorageAttachmentFile);
+    private Long parseLongSafely(String value) {
+        try {
+            return Long.parseLong(value);
+        } catch (NumberFormatException e) {
+            return null;
         }
-        return i;
+    }
+
+    private String resolveInspectorName(String idStr, Map<Long, String> inspectorNameMap) {
+        Long userId = parseLongSafely(idStr);
+        if (userId == null) {
+            return "鏃犳晥ID(" + idStr + ")";
+        }
+        return inspectorNameMap.getOrDefault(userId, "鏈煡鐢ㄦ埛(" + idStr + ")");
+    }
+
+    private String joinDistinctValues(List<String> values) {
+        return values.stream()
+                .filter(StringUtils::isNotBlank)
+                .map(String::trim)
+                .distinct()
+                .collect(Collectors.joining("锛�"));
+    }
+
+    private List<CommonFile> filterCommonFilesByType(List<CommonFile> commonFiles, Integer type) {
+        return commonFiles.stream()
+                .filter(commonFile -> Objects.equals(commonFile.getType(), type))
+                .collect(Collectors.toList());
+    }
+
+    private Map<Long, String> buildAreaNameMap(Set<Long> areaIds) {
+        if (areaIds == null || areaIds.isEmpty()) {
+            return Collections.emptyMap();
+        }
+        return deviceAreaMapper.selectBatchIds(new ArrayList<>(areaIds)).stream()
+                .collect(Collectors.toMap(DeviceArea::getId, DeviceArea::getAreaName, (left, right) -> left));
     }
 
     @Override
+    @Transactional(rollbackFor = Exception.class)
     public int delByIds(Long[] ids) {
-        // 妫�鏌ュ弬鏁�
         if (ids == null || ids.length == 0) {
             return 0;
         }
+        commonFileService.deleteByBusinessIds(Arrays.asList(ids), FileNameType.INSPECTION.getValue());
+        commonFileService.deleteByBusinessIds(Arrays.asList(ids), FileNameType.INSPECTION_PRODUCTION_BEFORE.getValue());
+        commonFileService.deleteByBusinessIds(Arrays.asList(ids), FileNameType.INSPECTION_PRODUCTION_AFTER.getValue());
         return inspectionTaskMapper.deleteBatchIds(Arrays.asList(ids));
     }
-
 }

--
Gitblit v1.9.3