package com.bonus.material.common.service.impl;

import com.alibaba.nacos.common.utils.StringUtils;
import com.bonus.common.biz.config.DateTimeHelper;
import com.bonus.common.biz.domain.*;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.back.domain.BackApplyInfo;
import com.bonus.material.basic.domain.BmProject;
import com.bonus.material.basic.domain.BmUnit;
import com.bonus.material.basic.mapper.BmUnitMapper;
import com.bonus.material.clz.service.MaterialLeaseInfoService;
import com.bonus.material.common.domain.dto.SelectDto;
import com.bonus.material.common.domain.vo.AgreementVo;
import com.bonus.material.common.domain.vo.SelectVo;
import com.bonus.material.common.mapper.SelectMapper;
import com.bonus.material.common.service.SelectService;
import com.bonus.material.materialStation.domain.ProAuthorizeInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 10488
 * 统一下拉选
 */
@Service("SelectService")
@Slf4j
public class SelectServiceImpl implements SelectService {

    @Resource(name = "SelectMapper")
    private SelectMapper mapper;

    @Resource
    private BmUnitMapper bmUnitMapper;

    @Resource
    private MaterialLeaseInfoService materialLeaseInfoService;

    /**
     * 单位下拉类型树
     * @param bmUnit
     * @return
     */
    @Override
    public AjaxResult getUnitList(BmUnit bmUnit) {
        // 性能监控开始
        long startTime = System.currentTimeMillis();
        Map<String, Long> stepTimes = new LinkedHashMap<>();
        
        log.info("=== getUnitList开始执行，参数: {}", bmUnit);
        
        // 步骤1: 获取登陆用户的组织ID
        long step1Start = System.currentTimeMillis();
        Long thisLoginUserDeptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
        stepTimes.put("获取用户组织ID", System.currentTimeMillis() - step1Start);

        if (null == thisLoginUserDeptId || 0 == thisLoginUserDeptId) {
            long totalTime = System.currentTimeMillis() - startTime;
            log.info("用户组织ID为空，直接返回空列表，总耗时: {}ms", totalTime);
            return AjaxResult.success(Collections.emptyList());
        }
        
        // 步骤2: 判断是否开启过滤
        long step2Start = System.currentTimeMillis();
        if (Objects.nonNull(bmUnit) && Objects.nonNull(bmUnit.getEnableFilter()) && bmUnit.getEnableFilter()) {
            bmUnit.setDeptId(thisLoginUserDeptId);
        }
        stepTimes.put("过滤判断", System.currentTimeMillis() - step2Start);
        
        // 步骤3: 判断是否是app模式
        if (bmUnit.getIsApp() != null && bmUnit.getIsApp()) {
            long appStart = System.currentTimeMillis();
            List<BmUnit> list = mapper.getUnitListApp(bmUnit);
            stepTimes.put("App模式查询", System.currentTimeMillis() - appStart);
            
            long totalTime = System.currentTimeMillis() - startTime;
            DateTimeHelper.logPerformanceAnalysis("getUnitList(App模式)", totalTime, stepTimes);
            return AjaxResult.success(list);
        }
        
        List<ProjectTreeNode> groupList = new ArrayList<>();
        List<ProjectTreeNode> list;
        try {
            // 步骤4: 数据库查询
            long dbStart = System.currentTimeMillis();
            list = mapper.getUnitList(bmUnit);
            stepTimes.put("数据库查询", System.currentTimeMillis() - dbStart);
            
            // 步骤5: 数据过滤
            long filterStart = System.currentTimeMillis();
            if (list != null) {
                list = list.stream()
                        .filter(Objects::nonNull)
                        .filter(unit -> unit.getId() != null && unit.getParentId() != null)
                        .collect(Collectors.toList());

                if (bmUnit.isEnableFilterTeam()) {
                    list.removeIf(item -> Objects.equals("0101", item.getTypeKey()));
                }
            }
            stepTimes.put("数据过滤", System.currentTimeMillis() - filterStart);

            if (CollectionUtils.isNotEmpty(list)) {
                // 步骤6: 树形结构构建
                long buildStart = System.currentTimeMillis();
                groupList = buildTreeEfficiently(list);
                // 步骤7: 获取班组数据（可选）
                if (bmUnit.getDeptId() == null) {
                    long teamStart = System.currentTimeMillis();
                    List<ProjectTreeNode> newList = mapper.getTeam();
                    stepTimes.put("获取班组数据", System.currentTimeMillis() - teamStart);

                    if (CollectionUtils.isNotEmpty(newList) && !bmUnit.isEnableFilterTeam()) {
                        groupList.addAll(newList);
                    }
                } else {
                    stepTimes.put("获取班组数据", 0L); // 跳过此步骤
                }
                stepTimes.put("树形结构构建", System.currentTimeMillis() - buildStart);
            }
        } catch (Exception e) {
            log.error("单位类型树-查询失败", e);
        }
        
        // 性能分析总结
        long totalTime = System.currentTimeMillis() - startTime;
        DateTimeHelper.logPerformanceAnalysis("getUnitList", totalTime, stepTimes);
        
        return AjaxResult.success(groupList);
    }

    /**
     * 工程类型树
     * @param bmProject
     * @return
     */
    @Override
    public AjaxResult getProjectList(BmProject bmProject) {
        List<BmProject> bmProjects = new ArrayList<>();
        if (bmProject.getIsApp() != null && bmProject.getIsApp()) {
            if (bmProject.getTeamId() != null) {
                bmProjects = mapper.getProjectListByClz(bmProject);
            } else {
                bmProjects = mapper.getProjectListApp(bmProject);
            }
            bmProjects.removeIf(Objects::isNull);
            return AjaxResult.success(bmProjects);
        }

        // 获取登陆用户的组织ID
        Long thisLoginUserDeptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
        if (null == thisLoginUserDeptId || 0 == thisLoginUserDeptId) {
            return AjaxResult.success(Collections.emptyList());
        }
        // 判断是否开启过滤
        if (Objects.nonNull(bmProject) && Objects.nonNull(bmProject.getEnableFilter()) && bmProject.getEnableFilter()) {
            bmProject.setDeptId(thisLoginUserDeptId);
        }

        List<ProjectTreeNode> groupList = new ArrayList<>();
        List<ProjectTreeNode> list = new ArrayList<>();
        try {
            list = mapper.getProjectList(bmProject);
            if (CollectionUtils.isNotEmpty(list)) {
                // 创建树形结构（数据集合作为参数）
                ProjectTreeBuild treeBuild = new ProjectTreeBuild(list);
                // 原查询结果转换树形结构
                groupList = treeBuild.buildTree();
            }
        } catch (Exception e) {
            log.error("工程类型树-查询失败", e);
        }
        return AjaxResult.success(groupList);
    }

    @Override
    public AjaxResult getMaTypeData(SelectDto dto) {
        List<SelectVo> list = new ArrayList<>();
        try {
            list = mapper.getMaTypeData(dto);
        } catch (Exception e) {
            log.error("机具类型-查询失败", e);
        }
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult getConfigList(BmUnit bmUnit) {
        List<ProjectTreeNode> groupList = new ArrayList<>();
        List<ProjectTreeNode> list;
        try {
            list = mapper.getConfigList(bmUnit);
            if (CollectionUtils.isNotEmpty(list)) {
                // 创建树形结构（数据集合作为参数）
                ProjectTreeBuild treeBuild = new ProjectTreeBuild(list);
                // 原查询结果转换树形结构
                groupList = treeBuild.buildTree();
            }
        } catch (Exception e) {
            log.error("标准配置-查询失败", e);
        }
        return AjaxResult.success(groupList);
    }

    @Override
    public AjaxResult getBranchProject() {
        List<SelectVo> list = new ArrayList<>();
        try {
            list = mapper.getBranchProject();
            return AjaxResult.success(list);
        } catch (Exception e) {
            log.error("机具类型-查询失败", e);
            return AjaxResult.success(new ArrayList<>());
        }
    }

    @Override
    public AjaxResult getTeamList(ProAuthorizeInfo bean) {
        List<ProjectTreeNode> groupList = new ArrayList<>();
        List<ProjectTreeNode> list;
        try {
            list = mapper.getUnitListPro(bean);
            list = list.stream()
                    .filter(Objects::nonNull)
                    .filter(unit -> unit.getId() != null && unit.getParentId() != null)
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(list)) {
                // 创建树形结构（数据集合作为参数）
                ProjectTreeBuild treeBuild = new ProjectTreeBuild(list);
                // 原查询结果转换树形结构
                groupList = treeBuild.buildTree();
                // 获取班组，进行数据拼接
                List<ProjectTreeNode> newList = mapper.getTeamList(bean);
                if (CollectionUtils.isNotEmpty(newList)) {
                    groupList.addAll(newList);
                }
            }
        } catch (Exception e) {
            log.error("单位类型树-查询失败", e);
        }
        return AjaxResult.success(groupList);
    }

    /**
     * 分部工程类型树
     * @param bmProject
     * @return
     */
    @Override
    public AjaxResult getProjectInfo(BmProject bmProject) {
        String username = SecurityUtils.getLoginUser().getUsername();
        // 根据用户名查询项目部信息
        List<String> departId = mapper.getDepartId(username);
        // 根据项目部id查询工程信息
        List<String> projectIdList = mapper.getProjectId(departId);
        List<BmProject> list = new ArrayList<>();
        if (bmProject.getIsApp() != null && bmProject.getIsApp()) {
            list = mapper.getProjectInfo(bmProject);
            if (CollectionUtils.isNotEmpty(list)) {
                if (CollectionUtils.isNotEmpty(projectIdList)) {
                    // 找出list中projectId与projectIdList中相同的数据
                    list = list.stream().filter(info -> projectIdList.contains(info.getProjectId())).collect(Collectors.toList());
                }
            }
        }
        return AjaxResult.success(list);
    }

    /**
     * 领用申请往来单位下拉选专用
     * @param bmUnit
     * @return
     */
    @Override
    public AjaxResult getUnitListLease(@NotNull(message = "参数不能为空") BmUnit bmUnit) {
        // 获取登陆用户的组织ID
        Long thisLoginUserDeptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
        if (null == thisLoginUserDeptId || 0 == thisLoginUserDeptId) {
            return AjaxResult.success(Collections.emptyList());
        }
        // 判断是否开启过滤
        if (Objects.nonNull(bmUnit) && Objects.nonNull(bmUnit.getEnableFilter()) && bmUnit.getEnableFilter()) {
            bmUnit.setDeptId(thisLoginUserDeptId);
        }

        if (bmUnit.getIsApp() != null && bmUnit.getIsApp()) {
            List<BmUnit> list = mapper.getUnitListApp(bmUnit);
            return AjaxResult.success(list);
        }
        List<ProjectTreeNode> groupList = new ArrayList<>();
        List<ProjectTreeNode> list;
        try {
            list = mapper.getUnitListXm(bmUnit);
            // 根据leaseId查询授权单位
            BmUnit info = mapper.selectUnitByLeaseId(bmUnit);
            if (info != null && info.getUnitId() != null) {
                // 根据单位id查询授权单位树
                bmUnit.setUnitId(info.getUnitId());
                List<ProjectTreeNode> unitList = mapper.getUnitList(bmUnit);
                if (CollectionUtils.isNotEmpty(unitList)) {
                    // 将unitList数据添加到list中，但需进行去重
                    for (ProjectTreeNode projectTreeNode : unitList) {
                        if (!list.contains(projectTreeNode)) {
                            list.add(projectTreeNode);
                        }
                    }
                }
            }
            list = list.stream()
                    .filter(Objects::nonNull)
                    .filter(unit -> unit.getId() != null && unit.getParentId() != null)
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(list)) {
                // 创建树形结构（数据集合作为参数）
                ProjectTreeBuild treeBuild = new ProjectTreeBuild(list);
                // 原查询结果转换树形结构
                if (bmUnit.getDeptId() != null) {
                    groupList = treeBuild.buildTree();
                } else if (bmUnit.getProjectId() != null && bmUnit.getLeaseId() != null) {
                    groupList = treeBuild.buildTree();
                    // 获取已授权班组，进行数据拼接
                    List<ProjectTreeNode> newList = mapper.getTeamLeaseList(bmUnit);
                    if (CollectionUtils.isNotEmpty(newList)) {
                        groupList.addAll(newList);
                    }
                }
            }
        } catch (Exception e) {
            log.error("单位类型树-查询失败", e);
        }
        return AjaxResult.success(groupList);
    }

    /**
     * 领用申请往来单位授权人员下拉
     * @param bmUnit
     * @return
     */
    @Override
    public AjaxResult getUnitListLeasePerson(BmUnit bmUnit) {
        return AjaxResult.success(mapper.getUnitListLeasePerson(bmUnit));
    }

    /**
     * 材料站退料往来单位id和标段工程id获取协议信息
     * @param dto
     * @return
     */
    @Override
    public AjaxResult getAgreementInfoByIdBack(SelectDto dto) {
        AgreementVo vo = new AgreementVo();
        try {
            if (dto != null  && dto.getTeamId() != null) {
                dto.setUnitId(Integer.parseInt(dto.getTeamId()));
            }
            List<AgreementVo> list = mapper.getAgreementInfoByIdBack(dto);
            if (CollectionUtils.isNotEmpty(list)) {
                vo = list.get(0);
            }
        } catch (Exception e) {
            log.error("往来单位id和标段工程id获取协议信息", e);
        }
        return AjaxResult.success(vo);
    }

    /**
     * 获取班组在用量
     * @param bean
     * @return
     */
    @Override
    public AjaxResult getBzUseTypeTree(BackApplyInfo bean) {
        List<TypeTreeNode> groupList = new ArrayList<>();
        List<TypeTreeNode> list = new ArrayList<>();
        List<TypeTreeNode> listL4 = new ArrayList<>();
        List<TypeTreeNode> listL3 = new ArrayList<>();
        List<TypeTreeNode> listL21 = new ArrayList<>();
        try {
            // 先查第四层类型
            SelectDto dto = new SelectDto();
            dto.setUnitId(bean.getUnitId().intValue());
            dto.setProjectId(bean.getProId().toString());
            List<AgreementVo> newList = mapper.getAgreementInfoByIdBack(dto);
            if (CollectionUtils.isNotEmpty(newList)) {
                bean.setAgreementId(newList.get(0).getAgreementId().longValue());
            } else {
                return AjaxResult.success(groupList);
            }
            listL4 = mapper.getBzUseTypeTreeL4(bean);
            if (CollectionUtils.isNotEmpty(listL4)) {
                List<Long> list4ParentIds = listL4.stream().map(TypeTreeNode::getParentId).collect(Collectors.toList());
                // 根据第四层parentId 查第三层类型
                listL3 = mapper.getUseTypeTreeL3(list4ParentIds);
                List<Long> list3ParentIds = listL3.stream().map(TypeTreeNode::getParentId).collect(Collectors.toList());
                // 根据第三层parentId 查第1.2层类型
                listL21 = mapper.getUseTypeTreeL21(list3ParentIds);
                list.addAll(listL4);
                list.addAll(listL3);
                list.addAll(listL21);
            }
            if (CollectionUtils.isNotEmpty(list)) {
                // 创建树形结构（数据集合作为参数）
                TypeTreeBuild treeBuild = new TypeTreeBuild(list);
                // 原查询结果转换树形结构
                groupList = treeBuild.buildTree();
            }
        } catch (Exception e) {
            AjaxResult.error("类型树-查询失败", e);
        }
        return AjaxResult.success(groupList);
    }

    /**
     * 领用工程下拉选
     * @param bmProject
     * @return
     */
    @Override
    public AjaxResult getLeaseProjectList(BmProject bmProject) {
        // 获取登陆用户的组织ID
        Long thisLoginUserDeptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
        // 判断是否开启过滤
        if (Objects.nonNull(bmProject) && Objects.nonNull(bmProject.getEnableFilter()) && bmProject.getEnableFilter()) {
            bmProject.setDeptId(thisLoginUserDeptId);
        }

        List<ProjectTreeNode> groupList = new ArrayList<>();
        List<ProjectTreeNode> list = new ArrayList<>();
        try {
            list = mapper.getLeaseProjectList(bmProject);
            if (CollectionUtils.isNotEmpty(list)) {
                // 创建树形结构（数据集合作为参数）
                ProjectTreeBuild treeBuild = new ProjectTreeBuild(list);
                // 原查询结果转换树形结构
                groupList = treeBuild.buildTree();
            }
        } catch (Exception e) {
            log.error("工程类型树-查询失败", e);
        }
        return AjaxResult.success(groupList);
    }

    @Override
    public AjaxResult getDeviceTypeTreeThree(SelectDto dto) {
        List<TreeNode> groupList = new ArrayList<>();
        List<TreeNode> list = new ArrayList<>();
        try {
            list = mapper.getDeviceTypeTreeThree(dto);
            if (CollectionUtils.isNotEmpty(list)) {
                // 创建树形结构（数据集合作为参数）
                TreeBuild treeBuild = new TreeBuild(list);
                // 原查询结果转换树形结构
                groupList = treeBuild.buildTree();
            }
        } catch (Exception e) {
            log.error("单位树/归属部门/所属上级-查询失败", e);
        }
        return AjaxResult.success(groupList);
    }

    @Override
    public AjaxResult getDeviceTypeTree(SelectDto dto) {
        List<TreeNode> groupList = new ArrayList<>();
        List<TreeNode> list = new ArrayList<>();
        try {
            list = mapper.getDeviceTypeTree(dto);
            if (CollectionUtils.isNotEmpty(list)) {
                // 创建树形结构（数据集合作为参数）
                TreeBuild treeBuild = new TreeBuild(list);
                // 原查询结果转换树形结构
                groupList = treeBuild.buildTree();
            }
        } catch (Exception e) {
            log.error("单位树/归属部门/所属上级-查询失败", e);
        }
        return AjaxResult.success(groupList);
    }

    @Override
    public AjaxResult getDeviceTypeTreeTwo(SelectDto dto) {
        List<TreeNode> groupList = new ArrayList<>();
        List<TreeNode> list = new ArrayList<>();
        try {
            list = mapper.getDeviceTypeTreeTwo(dto);
            if (CollectionUtils.isNotEmpty(list)) {
                // 创建树形结构（数据集合作为参数）
                TreeBuild treeBuild = new TreeBuild(list);
                // 原查询结果转换树形结构
                groupList = treeBuild.buildTree();
            }
        } catch (Exception e) {
            log.error("单位树/归属部门/所属上级-查询失败", e);
        }
        return AjaxResult.success(groupList);
    }

    @Override
    public AjaxResult getBackDeviceTypeTree(SelectDto dto) {
        List<TypeTreeNode> groupList = new ArrayList<>();
        List<TypeTreeNode> list = new ArrayList<>();
        List<TypeTreeNode> listL4 = new ArrayList<>();
        List<TypeTreeNode> listL3 = new ArrayList<>();
        List<TypeTreeNode> listL21 = new ArrayList<>();
        try {
            // 先查第四层类型
            dto.setUserId(SecurityUtils.getLoginUser().getUserid());
            listL4 = mapper.getUseTypeTreeL4Back(dto);
            if (CollectionUtils.isNotEmpty(listL4)) {
                List<Long> list4ParentIds = listL4.stream().map(o -> o.getParentId()).collect(Collectors.toList());
                // 根据第四层parentId 查第三层类型
                listL3 = mapper.getUseTypeTreeL3(list4ParentIds);
                List<Long> list3ParentIds = listL3.stream().map(o -> o.getParentId()).collect(Collectors.toList());
                // 根据第三层parentId 查第1.2层类型
                listL21 = mapper.getUseTypeTreeL21(list3ParentIds);
                list.addAll(listL4);
                list.addAll(listL3);
                list.addAll(listL21);
            }
            if (CollectionUtils.isNotEmpty(list)) {
                // 创建树形结构（数据集合作为参数）
                TypeTreeBuild treeBuild = new TypeTreeBuild(list);
                // 原查询结果转换树形结构
                groupList = treeBuild.buildTree();
            }
        } catch (Exception e) {
            AjaxResult.error("类型树-查询失败", e);
        }
        return AjaxResult.success(groupList);















//        List<TreeNode> groupList = new ArrayList<>();
//        List<TreeNode> list = new ArrayList<>();
//        try {
//            list = mapper.getBackDeviceTypeTree(dto);
//            if (CollectionUtils.isNotEmpty(list)) {
//                // 创建树形结构（数据集合作为参数）
//                TreeBuild treeBuild = new TreeBuild(list);
//                // 原查询结果转换树形结构
//                groupList = treeBuild.buildTree();
//            }
//        } catch (Exception e) {
//            log.error("单位树/归属部门/所属上级-查询失败", e);
//        }
//        return AjaxResult.success(groupList);
    }

    @Override
    public AjaxResult getAssetAttributesCbx(SelectDto dto) {
        List<SelectVo> list = new ArrayList<>();
        try {
            list = mapper.getAssetAttributesCbx(dto);
        } catch (Exception e) {
            log.error("资产属性-查询失败", e);
        }
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult getDeviceFactoryCbx(SelectDto dto) {
        List<SelectVo> list = new ArrayList<>();
        try {
            list = mapper.getDeviceFactoryCbx(dto);
        } catch (Exception e) {
            log.error("机具厂家-查询失败", e);
        }
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult getAccessoryTree() {
        List<TreeNode> groupList = new ArrayList<>();
        List<TreeNode> list = new ArrayList<>();
        try {
            list = mapper.getAccessoryTree();
            if (CollectionUtils.isNotEmpty(list)) {
                // 创建树形结构（数据集合作为参数）
                TreeBuild treeBuild = new TreeBuild(list);
                // 原查询结果转换树形结构
                groupList = treeBuild.buildTree();
            }
        } catch (Exception e) {
            log.error("配件所属上级树-查询失败", e);
        }
        return AjaxResult.success(groupList);
    }

    @Override
    public AjaxResult getPartTree(SelectDto dto) {
        List<TreeNode> groupList = new ArrayList<>();
        List<TreeNode> list = new ArrayList<>();
        try {
            list = mapper.getPartTree(dto);
            if (CollectionUtils.isNotEmpty(list)) {
                // 创建树形结构（数据集合作为参数）
                TreeBuild treeBuild = new TreeBuild(list);
                // 原查询结果转换树形结构
                groupList = treeBuild.buildTree();
            }
        } catch (Exception e) {
            log.error("配件所属上级树-查询失败", e);
        }
        return AjaxResult.success(groupList);
    }

    /**
     * 在用设备类型树
     * @param bean
     * @return
     */
    @Override
    public AjaxResult getUseTypeTree(BackApplyInfo bean) {
        List<TypeTreeNode> groupList = new ArrayList<>();
        List<TypeTreeNode> list = new ArrayList<>();
        List<TypeTreeNode> listL4 = new ArrayList<>();
        List<TypeTreeNode> listL3 = new ArrayList<>();
        List<TypeTreeNode> listL21 = new ArrayList<>();
        try {
            // 先查第四层类型
            listL4 = mapper.getUseTypeTreeL4(bean);
            if (CollectionUtils.isNotEmpty(listL4)) {
                List<Long> list4ParentIds = listL4.stream().map(TypeTreeNode::getParentId).collect(Collectors.toList());
                // 根据第四层parentId 查第三层类型
                listL3 = mapper.getUseTypeTreeL3(list4ParentIds);
                List<Long> list3ParentIds = listL3.stream().map(TypeTreeNode::getParentId).collect(Collectors.toList());
                // 根据第三层parentId 查第1.2层类型
                listL21 = mapper.getUseTypeTreeL21(list3ParentIds);
                list.addAll(listL4);
                list.addAll(listL3);
                list.addAll(listL21);
            }
            if (CollectionUtils.isNotEmpty(list)) {
                // 创建树形结构（数据集合作为参数）
                TypeTreeBuild treeBuild = new TypeTreeBuild(list);
                // 原查询结果转换树形结构
                groupList = treeBuild.buildTree();
            }
        } catch (Exception e) {
            AjaxResult.error("类型树-查询失败", e);
        }
        return AjaxResult.success(groupList);
    }

    /**
     * 获取设备类型 app用
     * @param bean
     * @return
     */
    @Override
    public AjaxResult getUseType(BackApplyInfo bean) {
        //四级类型只查询数量管理类型数据
        bean.setUserId(SecurityUtils.getLoginUser().getUserid());
        List<TypeTreeNode> listL4 = mapper.getUseTypeTreeApp(bean);
        if (CollectionUtils.isEmpty(listL4)) {
               return AjaxResult.success();
         }
        // 根据四级查询三级类型信息
        List<Long> list4ParentIds = listL4.stream()
                                  .map(TypeTreeNode::getParentId)
                                  .collect(Collectors.toList());
         // 根据第四层 parentId 查第三层类型
          List<TypeTreeNode> listL3 = mapper.getUseTypeTreeL3(list4ParentIds);
         // 如果 bean.getTypeId() 不为 null，筛选符合条件的 listL4 数据
         if (bean.getTypeId() != null) {
            List<TypeTreeNode> filteredListL4 = listL4.stream()
                                              .filter(node -> String.valueOf(node.getParentId()).equals(bean.getTypeId()))
                                              .collect(Collectors.toList());
           return AjaxResult.success(filteredListL4);
         }
        // 如果 bean.getTypeId() 为 null，则返回 listL3
           return AjaxResult.success(listL3);
    }

    /**
     * 机具类型查询
     * @param dto
     * @return
     */
    @Override
    public AjaxResult getMaType(SelectDto dto) {
        List<SelectVo> list = new ArrayList<>();
        try {
            list = mapper.getMaType(dto);
        } catch (Exception e) {
            log.error("机具类型-查询失败", e);
        }
        return AjaxResult.success(list);
    }

    @Override
    public AjaxResult getGoodsShelvesCbx(SelectDto dto) {
        List<TreeNode> groupList = new ArrayList<>();
        List<TreeNode> list = new ArrayList<>();
        try {
            list = mapper.getGoodsShelvesCbx(dto);
            if (CollectionUtils.isNotEmpty(list)) {
                // 创建树形结构（数据集合作为参数）
                TreeBuild treeBuild = new TreeBuild(list);
                // 原查询结果转换树形结构
                groupList = treeBuild.buildTree();
            }
        } catch (Exception e) {
            log.error("货架-查询失败", e);
        }
        return AjaxResult.success(groupList);
    }

    @Override
    public AjaxResult getAgreementInfoById(SelectDto dto) {
        List<Integer> agreementIdList = new ArrayList<>();
        AgreementVo vo = new AgreementVo();
        try {
            if (dto != null && StringUtils.isNotBlank(dto.getTeamId())) {
                List<AgreementVo> list = mapper.getAgreementInfoBy(dto);
                if (CollectionUtils.isNotEmpty(list)) {
                    for (AgreementVo agreementVo : list) {
                        agreementIdList.add(agreementVo.getAgreementId());
                    }
                }
                return AjaxResult.success(agreementIdList);
            } else {
                List<AgreementVo> list = mapper.getAgreementInfoById(dto);
                if (CollectionUtils.isNotEmpty(list)) {
                    vo = list.get(0);
                }
            }
        } catch (Exception e) {
            log.error("往来单位id和标段工程id获取协议信息", e);
        }
        return AjaxResult.success(vo);
    }

    /**
     * 通过hashMap构建高效的树构建方法，时间复杂度O(n)
     * @param nodes 节点列表
     * @return 树形结构
     */
    private List<ProjectTreeNode> buildTreeEfficiently(List<ProjectTreeNode> nodes) {
        if (CollectionUtils.isEmpty(nodes)) {
            return new ArrayList<>();
        }
        
        // 使用Map来存储节点，提高查找效率
        Map<String, ProjectTreeNode> nodeMap = new HashMap<>();
        Map<String, List<ProjectTreeNode>> childrenMap = new HashMap<>();
        
        // 第一遍遍历：建立Map索引
        for (ProjectTreeNode node : nodes) {
            nodeMap.put(node.getId(), node);
            childrenMap.put(node.getId(), new ArrayList<>());
        }
        
        List<ProjectTreeNode> rootNodes = new ArrayList<>();
        
        // 第二遍遍历：建立父子关系
        for (ProjectTreeNode node : nodes) {
            String parentId = node.getParentId();
            if ("0".equals(parentId)) {
                // 根节点
                rootNodes.add(node);
            } else {
                // 子节点
                List<ProjectTreeNode> siblings = childrenMap.get(parentId);
                if (siblings != null) {
                    siblings.add(node);
                }
            }
        }
        
        // 第三遍遍历：设置children
        for (ProjectTreeNode node : nodes) {
            List<ProjectTreeNode> children = childrenMap.get(node.getId());
            node.setChildren(children);
        }
        
        return rootNodes;
    }


}
