package cn.iocoder.yudao.module.mes.service.organization;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.erp.controller.admin.autocode.util.AutoCodeUtil;
import cn.iocoder.yudao.module.iot.dal.dataobject.device.DeviceDO;
import cn.iocoder.yudao.module.iot.dal.dataobject.devicecontactmodel.DeviceContactModelDO;
import cn.iocoder.yudao.module.iot.dal.mysql.device.DeviceMapper;
import cn.iocoder.yudao.module.iot.dal.mysql.devicecontactmodel.DeviceContactModelMapper;
import cn.iocoder.yudao.module.iot.service.device.DeviceService;
import cn.iocoder.yudao.module.mes.controller.admin.deviceledger.vo.DeviceLedgerSaveReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.organization.vo.*;
import cn.iocoder.yudao.module.mes.controller.admin.orgworker.vo.OrgWorkerPageReqVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.deviceledger.DeviceLedgerDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.organization.OrganizationDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.orgworker.OrgWorkerDO;
import cn.iocoder.yudao.module.mes.dal.mysql.organization.OrganizationMapper;
import cn.iocoder.yudao.module.mes.dal.mysql.orgworker.OrgWorkerMapper;
import cn.iocoder.yudao.module.mes.dal.redis.no.MesNoRedisDAO;
import cn.iocoder.yudao.module.mes.service.deviceledger.DeviceLedgerService;
import cn.iocoder.yudao.module.mes.service.deviceledger.DeviceLedgerServiceImpl;
import cn.iocoder.yudao.module.mes.service.machine.MachineComponentService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.module.mes.enums.ErrorCodeConstants.*;

/**
 * 产线工位 Service 实现类
 *
 * @author 内蒙必硕
 */
@Service
@Validated
public class OrganizationServiceImpl implements OrganizationService {

    @Resource
    private OrganizationMapper organizationMapper;
    @Resource
    private OrgWorkerMapper workerMapper;
    @Resource
    private MesNoRedisDAO noRedisDAO;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private DeviceContactModelMapper deviceContactModelMapper;
    @Resource
    private DeviceMapper deviceMapper;

    @Resource
    private DeviceLedgerService deviceLedgerService;

    @Autowired
    private AutoCodeUtil autoCodeUtil;
    @Override
    public Long createOrganization(OrganizationSaveReqVO createReqVO) {
        // 校验父组织id的有效性
        validateParentOrganization(null, createReqVO.getParentId());
        // 校验组织名称的唯一性
        validateOrganizationNameUnique(null, createReqVO.getParentId(), createReqVO.getName());
        // 插入
        OrganizationDO organization = BeanUtils.toBean(createReqVO, OrganizationDO.class);
        if (StringUtils.isEmpty(organization.getCode())) {
            // 1.4 编码，并校验唯一性
//            String no = null;
//            if(organization.getOrgClass().equals(OrgClassEnum.工位.getValue())){
//                no = noRedisDAO.generate2(MesNoRedisDAO.ORG_WORKPLACE);
//                if (organizationMapper.selectByNo(no) != null) {
//                    throw exception(PURCHASE_ORDER_NO_EXISTS);
//                }
//                organization.setCode(no);

//            }
            organization.setCode(autoCodeUtil.genSerialCode("ORG_CODE",null));
        } else {
                    if (organizationMapper.selectByNo(organization.getCode()) != null) {
                    throw exception(ORGANIZATION_CODE_EXISTS);
                }
        }
        organizationMapper.insert(organization);
        // 设备台账关联产线
        if (organization.getMachineId() != null) {
            DeviceLedgerDO deviceLedgerDO = deviceLedgerService.getDeviceLedger(organization.getMachineId());
            deviceLedgerDO.setWorkshop(String.valueOf(organization.getParentId()));
            deviceLedgerService.updateDeviceLedger(BeanUtils.toBean(deviceLedgerDO, DeviceLedgerSaveReqVO.class));
        }
        // 返回
        return organization.getId();
    }

    @Override
    public void updateOrganization(OrganizationSaveReqVO updateReqVO) {
        // 校验存在
        validateOrganizationExists(updateReqVO.getId());
        // 校验父组织id的有效性
        validateParentOrganization(updateReqVO.getId(), updateReqVO.getParentId());
        // 校验组织名称的唯一性
        validateOrganizationNameUnique(updateReqVO.getId(), updateReqVO.getParentId(), updateReqVO.getName());

        // 更新
        OrganizationDO updateObj = BeanUtils.toBean(updateReqVO, OrganizationDO.class);
        organizationMapper.updateById(updateObj);
        // 设备台账关联产线
        if (updateObj.getMachineId() != null) {
            DeviceLedgerDO deviceLedgerDO = deviceLedgerService.getDeviceLedger(updateObj.getMachineId());
            deviceLedgerDO.setWorkshop(String.valueOf(updateObj.getParentId()));
            deviceLedgerService.updateDeviceLedger(BeanUtils.toBean(deviceLedgerDO, DeviceLedgerSaveReqVO.class));
        }
    }

    @Override
    public void deleteOrganization(Long id) {
        // 校验存在
        validateOrganizationExists(id);
        // 校验是否有子产线工位
        if (organizationMapper.selectCountByParentId(id) > 0) {
            throw exception(ORGANIZATION_EXITS_CHILDREN);
        }
        DeviceLedgerDO deviceLedgerDO = deviceLedgerService.getDeviceLedger(organizationMapper.selectById(id).getMachineId());
        if (deviceLedgerDO != null) {
            deviceLedgerDO.setWorkshop(null);
            deviceLedgerService.updateDeviceLedger(BeanUtils.toBean(deviceLedgerDO, DeviceLedgerSaveReqVO.class));
        }
        // 删除
        organizationMapper.deleteById(id);
        // 设备台账关联产线

    }

    private void validateOrganizationExists(Long id) {
        if (organizationMapper.selectById(id) == null) {
            throw exception(ORGANIZATION_NOT_EXISTS);
        }
    }

    private void validateParentOrganization(Long id, Long parentId) {
        if (parentId == null || OrganizationDO.PARENT_ID_ROOT.equals(parentId)) {
            return;
        }
        // 1. 不能设置自己为父产线工位
        if (Objects.equals(id, parentId)) {
            throw exception(ORGANIZATION_PARENT_ERROR);
        }
        // 2. 父产线工位不存在
        OrganizationDO parentOrganization = organizationMapper.selectById(parentId);
        if (parentOrganization == null) {
            throw exception(ORGANIZATION_PARENT_NOT_EXITS);
        }
        // 3. 递归校验父产线工位，如果父产线工位是自己的子产线工位，则报错，避免形成环路
        if (id == null) { // id 为空，说明新增，不需要考虑环路
            return;
        }
        for (int i = 0; i < Short.MAX_VALUE; i++) {
            // 3.1 校验环路
            parentId = parentOrganization.getParentId();
            if (Objects.equals(id, parentId)) {
                throw exception(ORGANIZATION_PARENT_IS_CHILD);
            }
            // 3.2 继续递归下一级父产线工位
            if (parentId == null || OrganizationDO.PARENT_ID_ROOT.equals(parentId)) {
                break;
            }
            parentOrganization = organizationMapper.selectById(parentId);
            if (parentOrganization == null) {
                break;
            }
        }
    }

    private void validateOrganizationNameUnique(Long id, Long parentId, String name) {
        OrganizationDO organization = organizationMapper.selectByParentIdAndName(parentId, name);
        if (organization == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的产线工位
        if (id == null) {
            throw exception(ORGANIZATION_NAME_DUPLICATE);
        }
        if (!Objects.equals(organization.getId(), id)) {
            throw exception(ORGANIZATION_NAME_DUPLICATE);
        }
    }

    @Override
    public OrganizationDO getOrganization(Long id) {
        return organizationMapper.selectById(id);
    }

    @Override
    public List<OrganizationDO> getOrganizationList(OrganizationListReqVO listReqVO) {
        return organizationMapper.selectList(listReqVO);
    }
    @Override
    public List<OrganizationDO> getOrganizationListNoParent(OrganizationListReqVO listReqVO) {
        return organizationMapper.selectList2(listReqVO);
    }
    @Resource
    public MachineComponentService machineComponentService;

    @Resource
    public DeviceService deviceService;

    @Override
    public List<OrganizationRespVO> buildVOList(List<OrganizationDO> list) {
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        //关联机台
//        Map<Long, MachineComponentDO> map = machineComponentService.getMap(
//                convertSet(list, OrganizationDO::getMachineId));
//
//        return BeanUtils.toBean(list, OrganizationRespVO.class, item -> {
//            MapUtils.findAndThen(map, item.getMachineId(),
//                    machine -> item.setMachineName(machine.getName()));
//
//        });
        //关联设备
//        Map<Long, DeviceDO> map = deviceService.getMap(
//                convertSet(list, OrganizationDO::getMachineId));

        List<DeviceLedgerDO> deviceLedgerDOList = deviceLedgerService.getDeviceLedgerList();
        Map<Long, DeviceLedgerDO> resultMap = deviceLedgerDOList.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toMap(
                        DeviceLedgerDO::getId,
                        Function.identity(),
                        (existing, replacement) -> existing  // 处理重复key
                ));

        return BeanUtils.toBean(list, OrganizationRespVO.class, item -> {
            MapUtils.findAndThen(resultMap, item.getMachineId(),
                    device -> item.setMachineName(device.getDeviceName()));
        });
    }
    @Override
    public List<OrganizationRespVO> buildWorkerVOList(List<OrganizationDO> list) {
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        //查找工位今日的派工情况
        List<Long> idList = list.stream().map(OrganizationDO::getId).collect(Collectors.toList());
        OrgWorkerPageReqVO reqVO = new OrgWorkerPageReqVO().setOrgIds(idList).setWorkDate(getDateRange(null));
        List<OrgWorkerDO> orgWorkerList =  workerMapper.selectList(reqVO);
        Map<Long,OrgWorkerDO> orgWorkMap = CollectionUtils.convertMap(orgWorkerList, OrgWorkerDO::getOrgId);

        //查找对应的工人姓名
        List<Long> userIds = orgWorkerList.stream().map(OrgWorkerDO::getWorkerId).collect(Collectors.toList());
        Map<Long,AdminUserRespDTO>userMap = adminUserApi.getUserMap(userIds);

        return BeanUtils.toBean(list, OrganizationRespVO.class, item -> {
            MapUtils.findAndThen(orgWorkMap, item.getId(),
                    //如果这个org在orgWorkMap里面则根据org的workerId去userMap找到对应的人名
                    org -> item.setWorkerUserName(userMap.get(org.getWorkerId()).getNickname()));

        });
    }
    public static LocalDateTime[] getDateRange(LocalDateTime base){
        if(base==null)base = LocalDateTime.now();
        LocalDateTime start = LocalDateTime.of(base.getYear(),base.getMonth(),base.getDayOfMonth(),0,0,0);
        LocalDateTime end = LocalDateTime.of(base.getYear(),base.getMonth(),base.getDayOfMonth(),23,59,59);
        return new LocalDateTime[]{start,end};
    }
    @Override
    public List<OrganizationDO> getList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        return organizationMapper.selectBatchIds(ids);
    }

    @Override
    public List<OrganizationDO> getOrganizationListByOutIds(Collection<Long> outIds) {
        if (CollUtil.isEmpty(outIds)) {
            return Collections.emptyList();
        }
        return organizationMapper.selectListByOutIds(outIds);
    }

    @Override
    public List<OrganizationDO> getOrganizationVOList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        return(organizationMapper.selectBatchIds(ids));
    }

    @Override
    public List<LineAnalysisTreeDTO.LineNode> deviceParameterAnalysis(String keyword, Integer showDevices) {
        // 参数验证
        if (showDevices == null || (showDevices != 1 && showDevices != 2)) {
            showDevices = 1; // 默认展示设备和参数
        }

        boolean needShowDevices = showDevices == 1; // 1-展示，2-不展示

        // 1. 获取产线集合
        OrganizationListReqVO organizationListReqVO = new OrganizationListReqVO();
        List<OrganizationDO> organizationDOS = getOrganizationList(organizationListReqVO);
        List<OrganizationRespVO> organizationRespVOS = buildVOList(organizationDOS);
        if (organizationRespVOS.isEmpty()) {
            return Collections.emptyList();
        }

        // 2. 获取所有有machineId的组织
        List<Long> deviceIds = organizationRespVOS.stream()
                .map(OrganizationRespVO::getMachineId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        // 3. 查询设备信息
        Map<Long, DeviceDO> deviceMap;
        if (!deviceIds.isEmpty()) {
            LambdaQueryWrapper<DeviceDO> deviceWrapper = new LambdaQueryWrapper<>();
            deviceWrapper.in(DeviceDO::getId, deviceIds)
                    .eq(DeviceDO::getIsEnable, true);
            List<DeviceDO> devices = deviceMapper.selectList(deviceWrapper);
            deviceMap = devices.stream()
                    .collect(Collectors.toMap(DeviceDO::getId, Function.identity()));
        } else {
            deviceMap = new HashMap<>();
        }

        // 4. 查询设备参数
        Map<Long, List<DeviceContactModelDO>> paramsByDeviceId;
        if (!deviceIds.isEmpty()) {
            LambdaQueryWrapper<DeviceContactModelDO> paramWrapper = new LambdaQueryWrapper<>();
            paramWrapper.in(DeviceContactModelDO::getDeviceId, deviceIds)
                    .orderByAsc(DeviceContactModelDO::getSort);
            List<DeviceContactModelDO> allParameters = deviceContactModelMapper.selectList(paramWrapper);

            paramsByDeviceId = allParameters.stream()
                    .filter(param -> param.getDeviceId() != null)
                    .collect(Collectors.groupingBy(DeviceContactModelDO::getDeviceId));
        } else {
            paramsByDeviceId = new HashMap<>();
        }

        // 5. 构建产线ID到orgClass的映射
        Map<Long, String> lineOrgClassMap = new HashMap<>();
        for (int i = 0; i < organizationDOS.size(); i++) {
            OrganizationDO orgDO = organizationDOS.get(i);
            OrganizationRespVO orgVO = organizationRespVOS.get(i);
            if (orgDO.getOrgClass() != null && orgVO != null) {
                lineOrgClassMap.put(orgVO.getId(), orgDO.getOrgClass());
            }
        }

        // 6. 构建组织ID到子节点的映射
        Map<Long, List<OrganizationRespVO>> childrenByParentId = organizationRespVOS.stream()
                .filter(org -> org.getParentId() != null && org.getParentId() != 0L)
                .collect(Collectors.groupingBy(OrganizationRespVO::getParentId));

        // 7. 如果有搜索关键词，筛选匹配的节点
        Set<Long> matchedNodeIds = new HashSet<>();
        boolean hasKeyword = StringUtils.isNotBlank(keyword);

        if (hasKeyword) {
            String lowerKeyword = keyword.toLowerCase();

            // 查找组织名称匹配的节点
            for (OrganizationRespVO node : organizationRespVOS) {
                boolean nodeMatched = false;

                // 1. 检查组织名称是否匹配
                if (node.getName() != null && node.getName().toLowerCase().contains(lowerKeyword)) {
                    nodeMatched = true;
                }

                // 2. 如果没有组织名称匹配，检查该节点是否有设备匹配
                if (!nodeMatched && needShowDevices && node.getMachineId() != null) {
                    DeviceDO device = deviceMap.get(node.getMachineId());
                    if (device != null) {
                        // 检查设备名称是否匹配
                        if (device.getDeviceName() != null &&
                                device.getDeviceName().toLowerCase().contains(lowerKeyword)) {
                            nodeMatched = true;
                        }

                        // 检查设备参数是否匹配
                        if (!nodeMatched) {
                            List<DeviceContactModelDO> deviceParams = paramsByDeviceId.getOrDefault(device.getId(), new ArrayList<>());
                            boolean hasMatchingParam = deviceParams.stream()
                                    .anyMatch(param -> param.getAttributeName() != null &&
                                            param.getAttributeName().toLowerCase().contains(lowerKeyword));
                            if (hasMatchingParam) {
                                nodeMatched = true;
                            }
                        }
                    }
                }

                if (nodeMatched) {
                    // 将当前节点加入匹配列表
                    matchedNodeIds.add(node.getId());
                    // 迭代添加所有子节点
                    addAllDescendants(node.getId(), childrenByParentId, matchedNodeIds);
                }
            }

            // 如果没有匹配任何节点，返回空列表
            if (matchedNodeIds.isEmpty()) {
                return Collections.emptyList();
            }
        } else {
            // 无关键词时，包含所有节点
            matchedNodeIds.addAll(organizationRespVOS.stream()
                    .map(OrganizationRespVO::getId)
                    .collect(Collectors.toSet()));
        }

        // 8. 找到最顶层的匹配节点（没有匹配的父节点）
        Set<Long> topLevelNodeIds = new HashSet<>(matchedNodeIds);

        // 从匹配节点中移除那些父节点也在匹配列表中的节点
        for (OrganizationRespVO node : organizationRespVOS) {
            if (matchedNodeIds.contains(node.getId()) && node.getParentId() != null &&
                    node.getParentId() != 0L && matchedNodeIds.contains(node.getParentId())) {
                topLevelNodeIds.remove(node.getId());
            }
        }

        // 9. 获取顶层节点
        Map<Long, OrganizationRespVO> nodeMap = organizationRespVOS.stream()
                .collect(Collectors.toMap(OrganizationRespVO::getId, Function.identity()));

        List<OrganizationRespVO> topLevelNodes = topLevelNodeIds.stream()
                .map(nodeMap::get)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        // 10. 构建树结构
        return buildOrganizationTreeWithChildren(topLevelNodes, matchedNodeIds, childrenByParentId,
                deviceMap, paramsByDeviceId, lineOrgClassMap, keyword, organizationRespVOS, needShowDevices, hasKeyword);
    }

    /**
     * 迭代添加所有子孙节点
     */
    private void addAllDescendants(Long nodeId,
                                   Map<Long, List<OrganizationRespVO>> childrenByParentId,
                                   Set<Long> matchedNodeIds) {
        if (childrenByParentId == null || childrenByParentId.isEmpty()) {
            return;
        }

        // 使用队列进行广度优先遍历
        Queue<Long> queue = new LinkedList<>();
        queue.offer(nodeId);

        while (!queue.isEmpty()) {
            Long currentId = queue.poll();

            List<OrganizationRespVO> children = childrenByParentId.get(currentId);
            if (children != null && !children.isEmpty()) {
                for (OrganizationRespVO child : children) {
                    matchedNodeIds.add(child.getId());
                    queue.offer(child.getId());
                }
            }
        }
    }

    /**
     * 构建组织树（包含当前节点及其所有子节点）
     */
    private List<LineAnalysisTreeDTO.LineNode> buildOrganizationTreeWithChildren(
            List<OrganizationRespVO> topLevelNodes,
            Set<Long> matchedNodeIds,
            Map<Long, List<OrganizationRespVO>> childrenByParentId,
            Map<Long, DeviceDO> deviceMap,
            Map<Long, List<DeviceContactModelDO>> paramsByDeviceId,
            Map<Long, String> lineOrgClassMap,
            String keyword,
            List<OrganizationRespVO> allOrganizationRespVOS,
            boolean needShowDevices,
            boolean hasKeyword) {

        // 创建节点映射
        Map<Long, LineAnalysisTreeDTO.LineNode> nodeMap = new HashMap<>();

        // 创建所有组织节点的映射
        Map<Long, OrganizationRespVO> allNodesMap = allOrganizationRespVOS.stream()
                .collect(Collectors.toMap(OrganizationRespVO::getId, Function.identity()));

        // 获取所有匹配节点的完整列表（包括所有子孙节点）
        Set<Long> allMatchedAndDescendantIds = new HashSet<>();
        for (Long matchedId : matchedNodeIds) {
            allMatchedAndDescendantIds.add(matchedId);
            addAllDescendants(matchedId, childrenByParentId, allMatchedAndDescendantIds);
        }

        // 构建所有匹配节点的树节点
        for (OrganizationRespVO node : allOrganizationRespVOS) {
            if (!allMatchedAndDescendantIds.contains(node.getId())) {
                continue;
            }

            // 构建设备节点
            List<LineAnalysisTreeDTO.EquipmentNode> equipmentNodes = new ArrayList<>();

            if (needShowDevices) {
                // 有搜索关键词时获取所有设备，无关键词时只获取当前节点的设备
                List<Long> deviceIds = hasKeyword ?
                        getAllDeviceIdsForNode(node.getId(), childrenByParentId, allNodesMap, allMatchedAndDescendantIds) :
                        getCurrentDeviceId(node, allNodesMap);

                for (Long deviceId : deviceIds) {
                    DeviceDO device = deviceMap.get(deviceId);
                    if (device != null) {
                        // 获取设备参数
                        List<DeviceContactModelDO> deviceParams = paramsByDeviceId.getOrDefault(device.getId(), new ArrayList<>());

                        // 检查设备和参数是否匹配关键词
                        boolean shouldIncludeDevice = false;
                        List<DeviceContactModelDO> filteredParams = new ArrayList<>();

                        if (hasKeyword) {
                            String lowerKeyword = keyword.toLowerCase();
                            // 检查当前节点是否匹配关键词（组织名称匹配）
                            boolean isNodeNameMatched = node.getName() != null &&
                                    node.getName().toLowerCase().contains(lowerKeyword);

                            if (!isNodeNameMatched) {
                                // 有关键词但不是组织名称匹配的情况
                                boolean deviceNameMatches = device.getDeviceName() != null &&
                                        device.getDeviceName().toLowerCase().contains(lowerKeyword);

                                // 检查参数是否匹配
                                filteredParams = deviceParams.stream()
                                        .filter(param -> param.getAttributeName() != null &&
                                                param.getAttributeName().toLowerCase().contains(lowerKeyword))
                                        .collect(Collectors.toList());

                                boolean hasMatchingParam = !filteredParams.isEmpty();

                                // 如果设备名称或参数匹配，则包含设备
                                if (deviceNameMatches || hasMatchingParam) {
                                    shouldIncludeDevice = true;
                                    // 如果设备名称匹配但参数不匹配，包含所有参数
                                    if (deviceNameMatches && filteredParams.isEmpty()) {
                                        filteredParams = new ArrayList<>(deviceParams);
                                    }
                                }
                            } else {
                                // 是组织名称匹配的情况：包含所有设备和参数
                                shouldIncludeDevice = true;
                                filteredParams = new ArrayList<>(deviceParams);
                            }
                        } else {
                            // 无关键词的情况：包含所有设备和参数
                            shouldIncludeDevice = true;
                            filteredParams = new ArrayList<>(deviceParams);
                        }

                        if (shouldIncludeDevice) {
                            List<LineAnalysisTreeDTO.ParameterNode> paramInfos = filteredParams.stream()
                                    .map(this::convertToSimpleInfo)
                                    .collect(Collectors.toList());

                            // 检查设备是否已添加（避免重复）
                            boolean alreadyAdded = equipmentNodes.stream()
                                    .anyMatch(e -> e.getId().equals(device.getId()));

                            if (!alreadyAdded) {
                                equipmentNodes.add(LineAnalysisTreeDTO.EquipmentNode.builder()
                                        .id(device.getId())
                                        .name(device.getDeviceName())
                                        .parameters(paramInfos)
                                        .build());
                            }
                        }
                    }
                }
            }

            LineAnalysisTreeDTO.LineNode lineNode = LineAnalysisTreeDTO.LineNode.builder()
                    .id(node.getId())
                    .name(node.getName())
                    .orgClass(lineOrgClassMap.getOrDefault(node.getId(), null))
                    .parentId(node.getParentId())
                    .equipments(equipmentNodes)
                    .children(new ArrayList<>())
                    .build();

            nodeMap.put(node.getId(), lineNode);
        }

        // 构建父子关系
        List<LineAnalysisTreeDTO.LineNode> result = new ArrayList<>();

        for (LineAnalysisTreeDTO.LineNode lineNode : nodeMap.values()) {
            if (lineNode.getParentId() == null || lineNode.getParentId() == 0L) {
                // 根节点
                result.add(lineNode);
            } else {
                // 查找父节点
                LineAnalysisTreeDTO.LineNode parentNode = nodeMap.get(lineNode.getParentId());
                if (parentNode != null) {
                    parentNode.getChildren().add(lineNode);
                } else {
                    // 父节点不在当前构建的节点中，但当前节点是匹配的
                    // 这种情况下，当前节点应该作为根节点展示
                    result.add(lineNode);
                }
            }
        }

        // 过滤：只保留顶层节点
        List<LineAnalysisTreeDTO.LineNode> filteredResult = new ArrayList<>();
        Set<Long> topLevelNodeIds = topLevelNodes.stream()
                .map(OrganizationRespVO::getId)
                .collect(Collectors.toSet());

        for (LineAnalysisTreeDTO.LineNode node : result) {
            if (topLevelNodeIds.contains(node.getId())) {
                filteredResult.add(node);
            } else if (node.getParentId() == null || node.getParentId() == 0L) {
                // 或者是没有父节点的根节点
                filteredResult.add(node);
            }
        }

        return filteredResult;
    }

    /**
     * 获取当前节点自身的设备ID
     */
    private List<Long> getCurrentDeviceId(OrganizationRespVO node, Map<Long, OrganizationRespVO> allNodesMap) {
        List<Long> deviceIds = new ArrayList<>();

        // 获取当前节点
        OrganizationRespVO currentNode = allNodesMap.get(node.getId());
        if (currentNode != null && currentNode.getMachineId() != null) {
            deviceIds.add(currentNode.getMachineId());
        }

        return deviceIds;
    }

    /**
     * 获取节点及其子孙节点的设备ID
     */
    private List<Long> getAllDeviceIdsForNode(Long nodeId,
                                              Map<Long, List<OrganizationRespVO>> childrenByParentId,
                                              Map<Long, OrganizationRespVO> allNodesMap,
                                              Set<Long> matchedNodeIds) {
        Set<Long> deviceIds = new HashSet<>();

        // 先检查当前节点是否有设备
        OrganizationRespVO currentNode = allNodesMap.get(nodeId);
        if (currentNode != null && currentNode.getMachineId() != null) {
            deviceIds.add(currentNode.getMachineId());
        }

        // 使用队列迭代获取所有子孙节点
        Queue<Long> queue = new LinkedList<>();
        queue.offer(nodeId);

        while (!queue.isEmpty()) {
            Long currentId = queue.poll();

            // 获取当前节点的子节点
            List<OrganizationRespVO> children = childrenByParentId.get(currentId);
            if (children != null) {
                for (OrganizationRespVO child : children) {
                    if (matchedNodeIds.contains(child.getId())) {
                        // 如果子节点有设备，添加到设备列表
                        if (child.getMachineId() != null) {
                            deviceIds.add(child.getMachineId());
                        }
                        // 继续处理子节点的子节点
                        queue.offer(child.getId());
                    }
                }
            }
        }

        return new ArrayList<>(deviceIds);
    }

    /**
     * 将设备参数转换为简化的参数信息
     */
    private LineAnalysisTreeDTO.ParameterNode convertToSimpleInfo(DeviceContactModelDO param) {
        return LineAnalysisTreeDTO.ParameterNode.builder()
                .id(param.getId())
                .name(param.getAttributeName())
                .code(param.getAttributeCode())
                .type(param.getAttributeType())
                .dataType(param.getDataType())
                .unit(param.getDataUnit())
                .ratio(param.getRatio())
                .build();
    }

}