From 2cf1565485060fd56e1f1f1cffbba7a4d70d42a6 Mon Sep 17 00:00:00 2001
From: lyh <925863403@qq.com>
Date: 星期五, 11 四月 2025 11:06:22 +0800
Subject: [PATCH] 优化dnc,设备结构树查询,优化原有代码

---
 lxzn-module-dnc/src/main/java/org/jeecg/modules/dnc/service/impl/DevicePermissionServiceImpl.java |  235 ++++++++++++++++++++++++++++++++++++++++++----------------
 1 files changed, 169 insertions(+), 66 deletions(-)

diff --git a/lxzn-module-dnc/src/main/java/org/jeecg/modules/dnc/service/impl/DevicePermissionServiceImpl.java b/lxzn-module-dnc/src/main/java/org/jeecg/modules/dnc/service/impl/DevicePermissionServiceImpl.java
index 498a9e9..ce32abf 100644
--- a/lxzn-module-dnc/src/main/java/org/jeecg/modules/dnc/service/impl/DevicePermissionServiceImpl.java
+++ b/lxzn-module-dnc/src/main/java/org/jeecg/modules/dnc/service/impl/DevicePermissionServiceImpl.java
@@ -5,7 +5,9 @@
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import org.apache.commons.lang3.StringUtils;
+import org.apache.shiro.SecurityUtils;
 import org.jeecg.common.constant.CommonConstant;
+import org.jeecg.common.system.vo.LoginUser;
 import org.jeecg.modules.dnc.entity.DevicePermission;
 import org.jeecg.modules.dnc.mapper.DevicePermissionMapper;
 import org.jeecg.modules.dnc.service.IDevicePermissionService;
@@ -24,10 +26,10 @@
 import org.springframework.transaction.annotation.Transactional;
 
 import javax.annotation.Resource;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
+import java.util.*;
+import java.util.function.Function;
 import java.util.stream.Collectors;
+import java.util.stream.Stream;
 
 @Service
 public class DevicePermissionServiceImpl extends ServiceImpl<DevicePermissionMapper, DevicePermission> implements IDevicePermissionService {
@@ -92,80 +94,181 @@
 
 
     /**
-     * 鍔犺浇浜х嚎璁惧鏍�
+     * * 鍔犺浇浜х嚎璁惧鏍�
      */
     @Override
-    public List<MdcEquipmentTree> DncLoadTreeListByProduction(String userId){
-        //鑾峰彇鎵�鏈変骇绾挎暟鎹�
-        List<MdcProduction> productionList = mdcProductionService.list(new LambdaQueryWrapper<MdcProduction>().eq(MdcProduction::getDelFlag, CommonConstant.DEL_FLAG_0.toString()).orderByAsc(MdcProduction::getProductionOrder));
-        //鏍规嵁鐢ㄦ埛id鑾峰彇鎷ユ湁鐨勪骇绾夸俊鎭泦鍚�
-        List<String> productionIds = mdcUserProductionService.queryProductionIdsByUserId(userId);
-        List<String> allProductionIds = new ArrayList<>();
-        //鎵惧埌鎵�鏈変骇绾縤d鐨勪笂绾d
-        if (productionIds != null && !productionIds.isEmpty()) {
-            for (String productionId : productionIds) {
-                this.getAllProductionIds(productionList, productionId, allProductionIds);
-            }
-        }
-        //杩囨护浜х嚎鏁版嵁
-        List<MdcProduction> list = productionList.stream().filter((MdcProduction mdcProduction) -> allProductionIds.contains(mdcProduction.getId())).collect(Collectors.toList());
-        //缁勮浜х嚎璁惧鏍�
-        List<MdcEquipmentTree> treeList = FindsEquipmentProductionUtil.wrapEquipmentProductionTreeList(list);
-        //濉厖璁惧鏁版嵁
-        FillEquipmentByProduction(treeList,userId);
+    public List<MdcEquipmentTree> DncLoadTreeListByProduction() {
+        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
+
+        // 鑾峰彇鎵�鏈夋湁鏁堜骇绾垮苟寤虹珛蹇�熸煡璇㈡槧灏�
+        Map<String, MdcProduction> productionMap = getValidProductions();
+
+        // 鑾峰彇鐢ㄦ埛鏉冮檺鐩稿叧鐨勬墍鏈変骇绾縄D锛堝寘鍚眰绾х鍏堬級
+        Set<String> authorizedProductionIds = getAuthorizedProductionIds(user.getId(), productionMap);
+
+        // 鏋勫缓浜х嚎鏍戠粨鏋�
+        List<MdcEquipmentTree> treeList = buildProductionTree(new ArrayList<>(authorizedProductionIds), productionMap);
+
+        // 鎵归噺濉厖璁惧鏁版嵁
+        fillEquipmentData(treeList, user);
+
         return treeList;
     }
 
     /**
-     * 鑾峰彇鎵�鏈夌殑浜х嚎id锛堝寘鍚墍鏈変笂绾э級
-     */
-    private void getAllProductionIds(List<MdcProduction> productionList, String productionId, List<String> allProductionIds) {
-        if (!allProductionIds.contains(productionId)) {
-            allProductionIds.add(productionId);
-        }
-        for (MdcProduction mdcProduction : productionList) {
-            if (StringUtils.isEmpty(mdcProduction.getParentId())) {
-                continue;
-            }
-            if (productionId.equals(mdcProduction.getId())) {
-                if (!allProductionIds.contains(mdcProduction.getParentId())) {
-                    allProductionIds.add(mdcProduction.getParentId());
-                    getAllProductionIds(productionList, mdcProduction.getParentId(), allProductionIds);
-                }
-            }
+     * 鑾峰彇鎵�鏈夋湁鏁堜骇绾垮苟寤虹珛ID鏄犲皠
+    */
+    private Map<String, MdcProduction> getValidProductions() {
+        List<MdcProduction> productions = mdcProductionService.list(
+                new LambdaQueryWrapper<MdcProduction>()
+                        .eq(MdcProduction::getDelFlag, CommonConstant.DEL_FLAG_0)
+                        .orderByAsc(MdcProduction::getProductionOrder)
+        );
+        return productions.stream().collect(Collectors.toMap(MdcProduction::getId, Function.identity()));
+    }
+
+    /**
+     * 鑾峰彇鐢ㄦ埛鏉冮檺鐩稿叧鐨勬墍鏈変骇绾縄D锛堝寘鍚眰绾х鍏堬級
+    */
+    private Set<String> getAuthorizedProductionIds(String userId, Map<String, MdcProduction> productionMap) {
+        Set<String> result = new HashSet<>();
+
+        // 鑾峰彇鐩存帴鍏宠仈鐨勪骇绾縄D
+        List<String> directProductionIds = Optional.ofNullable(mdcUserProductionService.queryProductionIdsByUserId(userId))
+                .orElse(Collections.emptyList());
+
+        // 閫掑綊鏀堕泦鎵�鏈夊眰绾D
+        directProductionIds.forEach(id -> collectHierarchyIds(id, productionMap, result));
+
+        return result;
+    }
+
+    /**
+    * 閫掑綊鏀堕泦灞傜骇ID锛堝寘鍚嚜韬強鎵�鏈夌鍏堬級
+    */
+    private void collectHierarchyIds(String productionId, Map<String, MdcProduction> productionMap, Set<String> collector) {
+        if (collector.contains(productionId)) return;
+
+        MdcProduction current = productionMap.get(productionId);
+        if (current == null) return;
+
+        collector.add(productionId);
+        if (StringUtils.isNotBlank(current.getParentId())) {
+            collectHierarchyIds(current.getParentId(), productionMap, collector);
         }
     }
 
     /**
-     * 浜х嚎璁惧鏍戝~鍏呰澶囨暟鎹�
-     */
-    private void FillEquipmentByProduction(List<MdcEquipmentTree> treeList,String userId) {
-        //鑾峰彇宸插垎閰嶆潈闄愯澶囨暟鎹�
-        List<String> deviceIds=super.list(new QueryWrapper<DevicePermission>().eq("user_id",userId)).stream().map(DevicePermission::getDeviceId).collect(Collectors.toList());
-        if (!deviceIds.isEmpty()){
-            for (MdcEquipmentTree mdcEquipmentTree : treeList) {
-                List<MdcEquipment> equipmentList = mdcEquipmentMapper.queryByProductionIdAndType(mdcEquipmentTree.getKey(),deviceIds);
-                if (equipmentList != null && !equipmentList.isEmpty()) {
-                    for (MdcEquipment mdcEquipment : equipmentList) {
-                        if (mdcEquipment.getCreateBy()!=null&& !mdcEquipment.getCreateBy().isEmpty()){
-                            mdcEquipment.setCreateBy(sysUserService.getUserByName(mdcEquipment.getCreateBy()).getRealname());
-                        }
-                        if (mdcEquipment.getUpdateBy()!=null&& !mdcEquipment.getUpdateBy().isEmpty()){
-                            mdcEquipment.setUpdateBy(sysUserService.getUserByName(mdcEquipment.getUpdateBy()).getRealname());
-                        }
-                        MdcEquipmentTree tree = new MdcEquipmentTree().convert(mdcEquipment);
-                        tree.setParentId(mdcEquipmentTree.getKey());
-                        tree.setEntity(mdcEquipment);
-                        tree.setType(2);
-                        mdcEquipmentTree.getChildren().add(tree);
-                    }
-                    mdcEquipmentTree.setLeaf(false);
-                }
-                if (!mdcEquipmentTree.getChildren().isEmpty()) {
-                    FillEquipmentByProduction(mdcEquipmentTree.getChildren(),userId);
-                }
-            }
+     鏋勫缓浜х嚎鏍戠粨鏋�
+    */
+    private List<MdcEquipmentTree> buildProductionTree(List<String> productionIds, Map<String, MdcProduction> productionMap) {
+
+        List<MdcProduction> filteredProductions = new ArrayList<>();
+        productionIds.forEach(id -> {
+        MdcProduction production = productionMap.get(id);
+        if (production != null) {
+            filteredProductions.add(production);
         }
+        });
+        return FindsEquipmentProductionUtil.wrapEquipmentProductionTreeList(filteredProductions);
+    }
+    /**
+    * 鎵归噺濉厖璁惧鏁版嵁
+    */
+    private void fillEquipmentData(List<MdcEquipmentTree> treeList, LoginUser user) {
+        // 鑾峰彇鐢ㄦ埛璁惧鏉冮檺
+        Set<String> deviceIds = getAuthorizedDeviceIds(user.getId());
+        if (deviceIds.isEmpty()) return;
+
+        // 鎵归噺鑾峰彇鎵�鏈夌浉鍏宠澶�
+        Map<String, List<MdcEquipment>> equipmentMap = getEquipmentMap(user, deviceIds);
+
+        // 鎵归噺鑾峰彇鐢ㄦ埛淇℃伅
+        Map<String, String> userRealNameMap = getUserRealNameMapping(equipmentMap.values());
+
+        // 濉厖璁惧鏁版嵁鍒版爲鑺傜偣
+        populateEquipmentNodes(treeList, equipmentMap, userRealNameMap);
+    }
+
+/**
+        * 鑾峰彇鎺堟潈璁惧ID闆嗗悎
+ */
+    private Set<String> getAuthorizedDeviceIds(String userId) {
+        return super.list(new QueryWrapper<DevicePermission>().select("device_id").eq("user_id", userId))
+                .stream()
+                .map(DevicePermission::getDeviceId)
+                .collect(Collectors.toSet());
+    }
+
+    /**
+     * 鎵归噺鑾峰彇璁惧鏁版嵁骞舵寜浜х嚎鍒嗙粍
+    */
+    private Map<String, List<MdcEquipment>> getEquipmentMap(LoginUser user, Set<String> deviceIds) {
+        List<String> productionIds=Arrays.asList(user.getProductionIds().split(","));
+        return mdcEquipmentMapper.queryByDepartIdsAndType(productionIds, new ArrayList<>(deviceIds))
+                .stream()
+                .collect(Collectors.groupingBy(MdcEquipment::getProductionId));
+    }
+
+
+    /*** 鎵归噺鑾峰彇鐢ㄦ埛鐪熷疄濮撳悕鏄犲皠
+    */
+    private Map<String, String> getUserRealNameMapping(Collection<List<MdcEquipment>> equipmentLists) {
+        Set<String> userNames = equipmentLists.stream()
+                .flatMap(List::stream)
+                .flatMap(e -> Stream.of(e.getCreateBy(), e.getUpdateBy()))
+                .filter(StringUtils::isNotBlank)
+                .collect(Collectors.toSet());
+
+        return sysUserService.getUserRealNamesByUserNames(new ArrayList<>(userNames));
+    }
+
+    /**
+     * 濉厖璁惧鑺傜偣鏁版嵁
+    */
+    private void populateEquipmentNodes(List<MdcEquipmentTree> nodes,
+                                        Map<String, List<MdcEquipment>> equipmentMap,
+                                        Map<String, String> userRealNameMap) {
+        for (MdcEquipmentTree node : nodes) {
+            if (!isProductionNode(node)) continue;
+
+            List<MdcEquipment> equipments = equipmentMap.getOrDefault(node.getKey(), Collections.emptyList());
+            List<MdcEquipmentTree> equipmentNodes = convertToEquipmentNodes(equipments, userRealNameMap, node.getKey());
+
+            node.getChildren().addAll(equipmentNodes);
+            node.setLeaf(equipmentNodes.isEmpty());
+
+            // 閫掑綊澶勭悊瀛愯妭鐐�
+            populateEquipmentNodes(node.getChildren(), equipmentMap, userRealNameMap);
+        }
+    }
+
+/**
+        * 杞崲璁惧鏁版嵁涓烘爲鑺傜偣
+ */
+    private List<MdcEquipmentTree> convertToEquipmentNodes(List<MdcEquipment> equipments,
+                                                           Map<String, String> userRealNameMap,
+                                                           String parentId) {
+        return equipments.stream().map(e -> {
+            // 鏇存柊鐢ㄦ埛鏄剧ず鍚嶇О
+            Optional.ofNullable(e.getCreateBy()).ifPresent(name ->
+                    e.setCreateBy(userRealNameMap.getOrDefault(name, name)));
+            Optional.ofNullable(e.getUpdateBy()).ifPresent(name ->
+                    e.setUpdateBy(userRealNameMap.getOrDefault(name, name)));
+
+            MdcEquipmentTree node = new MdcEquipmentTree().convert(e);
+            node.setParentId(parentId);
+            node.setEntity(e);
+            node.setType(2); // 璁惧鑺傜偣绫诲瀷
+            return node;
+        }).collect(Collectors.toList());
+    }
+
+/**
+        * 鍒ゆ柇鏄惁涓轰骇绾胯妭鐐癸紙鏍规嵁涓氬姟閫昏緫瀹氫箟锛�
+            */
+    private boolean isProductionNode(MdcEquipmentTree node) {
+        return node.getType() == 1; // 鍋囪绫诲瀷1琛ㄧず浜х嚎鑺傜偣
     }
 
 }

--
Gitblit v1.9.3