package com.inspect.metadata.prodevmnt.service.impl;

import com.inspect.base.core.enums.AlgTypeEnum;
import com.inspect.base.core.enums.DevTypeEnum;
import com.inspect.metadata.alg.domain.BasedataAlgSubtype;
import com.inspect.metadata.alg.mapper.BasedataAlgSubtypeMapper;
import com.inspect.metadata.area.domain.BaseDataArea;
import com.inspect.metadata.eqpbook.domain.BasedataEqpBook;
import com.inspect.metadata.eqpbook.mapper.BasedataEqpBookMapper;
import com.inspect.metadata.patrolpointmnt.domain.BasedataPatrolPoint;
import com.inspect.metadata.patrolpointmnt.domain.BasedataPatrolPointPreset;
import com.inspect.metadata.patrolpointmnt.mapper.BasedataPatrolPointMapper;
import com.inspect.metadata.patrolpointmnt.mapper.BasedataPatrolPointPresetMapper;
import com.inspect.metadata.patrolpointmnt.service.IBasedataPatrolPointService;
import com.inspect.metadata.prodevmnt.domain.BasedataDevice;
import com.inspect.metadata.prodevmnt.domain.BasedataDeviceType;
import com.inspect.metadata.prodevmnt.domain.BasedataModelDevice;
import com.inspect.metadata.prodevmnt.domain.TreeModule;
import com.inspect.metadata.prodevmnt.domain.vo.AreaDeviceTreeSelect;
import com.inspect.metadata.prodevmnt.domain.vo.BaseDataAreaProDeviceVO;
import com.inspect.metadata.prodevmnt.domain.vo.ProDeviceTreeSelectVO;
import com.inspect.metadata.prodevmnt.domain.vo.ProMainDevicePatrolEquTreeSelect;
import com.inspect.metadata.prodevmnt.mapper.BasedataDeviceMapper;
import com.inspect.metadata.prodevmnt.mapper.BasedataDeviceTypeMapper;
import com.inspect.metadata.prodevmnt.mapper.BasedataModelDeviceMapper;
import com.inspect.metadata.prodevmnt.service.IBasedataDeviceService;
import com.inspect.metadata.prodevmnt.util.AreaDeviceTreeSelectUtil;
import com.inspect.metadata.prodevmnt.util.ProDeviceTreeSelectUtil;
import com.inspect.metadata.prodevmnt.util.ProMainDevicePatrolEquTreeSelectUtil;
import com.inspect.base.core.utils.DateUtils;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.utils.bean.BeanUtils;

import java.util.*;
import java.util.stream.Collectors;

import com.inspect.system.base.domain.SysDictData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class BasedataDeviceServiceImpl implements IBasedataDeviceService {

    private final Logger logger = LoggerFactory.getLogger(BasedataDeviceServiceImpl.class);

    private final BasedataDeviceMapper basedataDeviceMapper;
    final
    BasedataPatrolPointMapper basedataPatrolPointMapper;
    final
    BasedataPatrolPointPresetMapper basedataPatrolPointPresetMapper;
    final
    BasedataEqpBookMapper basedataEqpbookMapper;
    final
    BasedataModelDeviceMapper basedataModelDeviceMapper;
    final
    BasedataDeviceTypeMapper basedataDevicetypeMapper;

    @Resource
    private BasedataPatrolPointMapper basedataPatrolpointMapper;

    @Resource
    private BasedataAlgSubtypeMapper basedataAlgSubtypeMapper;

    public BasedataDeviceServiceImpl(BasedataDeviceMapper basedataDeviceMapper, BasedataPatrolPointMapper basedataPatrolPointMapper, BasedataPatrolPointPresetMapper basedataPatrolPointPresetMapper, BasedataEqpBookMapper basedataEqpbookMapper, BasedataModelDeviceMapper basedataModelDeviceMapper, BasedataDeviceTypeMapper basedataDevicetypeMapper) {
        this.basedataDeviceMapper = basedataDeviceMapper;
        this.basedataPatrolPointMapper = basedataPatrolPointMapper;
        this.basedataPatrolPointPresetMapper = basedataPatrolPointPresetMapper;
        this.basedataEqpbookMapper = basedataEqpbookMapper;
        this.basedataModelDeviceMapper = basedataModelDeviceMapper;
        this.basedataDevicetypeMapper = basedataDevicetypeMapper;
    }

    public BasedataDevice selectBasedataDeviceByDeviceId(Long deviceId) {
        return this.basedataDeviceMapper.selectBasedataDeviceByDeviceId(deviceId);
    }

    @Override
    public BasedataDevice selectBasedataDeviceRelationByDeviceId(Long toDeviceId) {
        return this.basedataDeviceMapper.selectBasedataDeviceRelationByDeviceId(toDeviceId);
    }

    public List<BasedataDevice> selectBasedataDeviceList(BasedataDevice basedataDevice) {
        return this.basedataDeviceMapper.selectBasedataDeviceList(basedataDevice);
    }

    @Override
    public Boolean updateBasedataDeviceRelation(Long toAreaId, Long deviceId) {
        return basedataDeviceMapper.updateBasedataDeviceRelation(toAreaId, deviceId) > 0;
    }

    public List<TreeModule> selectAreaAndDeviceTree(BasedataDevice basedataDevice) {
        return this.basedataDeviceMapper.selectAreaAndDeviceTree(basedataDevice);
    }

    public List<TreeModule> selectPointList() {
        return this.basedataDeviceMapper.selectPointList();
    }

    public List<BasedataDevice> selectBasedataTreeByEqBookCode(BasedataDevice basedataDevice) {
        return this.basedataDeviceMapper.selectBasedataTreeByEqBookCode(basedataDevice);
    }

    public int insertBasedataDevice(BasedataDevice basedataDevice) {
        basedataDevice.setCreateTime(DateUtils.getNowDate());
        return this.basedataDeviceMapper.insertBasedataDevice(basedataDevice);
    }

    public int updateBasedataDevice(BasedataDevice basedataDevice) {
        basedataDevice.setUpdateTime(DateUtils.getNowDate());
        return this.basedataDeviceMapper.updateBasedataDevice(basedataDevice);
    }

    public int deleteBasedataDeviceByDeviceIds(Long[] deviceIds) {
        return this.basedataDeviceMapper.deleteBasedataDeviceByDeviceIds(deviceIds);
    }

    public int deleteBasedataDeviceByDeviceId(Long deviceId) {
        return this.basedataDeviceMapper.deleteBasedataDeviceByDeviceId(deviceId);
    }

    public BasedataDevice selectBasedataDeviceByPatrolPointId(String patrolPointId) {
        return this.basedataDeviceMapper.selectBasedataDeviceByPatrolPointId(patrolPointId);
    }

    public List buildAreaDeviceTreeSelect(List<BaseDataArea> areas) {
        List<BaseDataAreaProDeviceVO> deviceVOS = this.getAreaDeviceList(areas);
        List<BaseDataAreaProDeviceVO> areaVOS = new ArrayList<>();

        for (BaseDataArea area : areas) {
            BaseDataAreaProDeviceVO deviceVO = new BaseDataAreaProDeviceVO();
            BeanUtils.copyBeanProp(deviceVO, area);
            deviceVO.setAreaIdString(String.valueOf(deviceVO.getAreaId()));
            deviceVO.setParentIdString(String.valueOf(deviceVO.getParentId()));
            deviceVO.setAreaFlag("Yes");
            deviceVO.setAreaParentId(area.getParentId());
            areaVOS.add(deviceVO);
        }

        if (!deviceVOS.isEmpty()) {
            areaVOS.addAll(deviceVOS);
        }

        List<BaseDataAreaProDeviceVO> deptTrees = this.buildAreaTree(areaVOS);
        //return (List)deptTrees.stream().map(AreaDeviceTreeSelect::<init>).collect(Collectors.toList());
        return deptTrees.stream().map(AreaDeviceTreeSelect::new).collect(Collectors.toList());
    }

    public List<AreaDeviceTreeSelect> buildAreaDeviceTreeSelectByAreas(List<BaseDataArea> areas) {
        ArrayList<Long> areaIdList = new ArrayList<>();
        HashMap<Long, BaseDataArea> areaMap = new HashMap<>();
        HashMap<Long, BasedataDevice> deviceHashMap = new HashMap<>();
        List<AreaDeviceTreeSelect> areaVOS = new ArrayList<>();

        for (BaseDataArea area : areas) {
            areaIdList.add(area.getAreaId());
            areaMap.put(area.getAreaId(), area);
            AreaDeviceTreeSelect areaVO = new AreaDeviceTreeSelect();
            areaVO.setDataId(String.valueOf(area.getAreaId()));
            areaVO.setParentId(String.valueOf(area.getParentId()));
            areaVO.setAreaId(area.getAreaId());
            areaVO.setAreaFlag("Yes");
            areaVO.setAreaParentId(area.getParentId());
            areaVO.setAreaName(area.getAreaName());
            areaVO.setAreaType(area.getAreaType());
            areaVOS.add(areaVO);
        }

        BasedataDevice basedataDeviceQuery = new BasedataDevice();
        Map<String, Object> params = new HashMap<>();
        params.put("areaIdList", areaIdList);
        basedataDeviceQuery.setParams(params);
        List<BasedataDevice> deviceList = this.basedataDeviceMapper.selectBasedataDeviceList(basedataDeviceQuery);
        Iterator<BasedataDevice> iterator = deviceList.iterator();

        BasedataDevice basedataDevice;
        while (iterator.hasNext()) {
            basedataDevice = iterator.next();
            deviceHashMap.put(basedataDevice.getDeviceId(), basedataDevice);
        }

        iterator = deviceList.iterator();

        while (iterator.hasNext()) {
            basedataDevice = iterator.next();
            AreaDeviceTreeSelect deviceVO = new AreaDeviceTreeSelect();
            StringBuilder idBuilder = new StringBuilder();
            StringBuilder pIdBuilder = new StringBuilder();
            this.getAreaDeviceTreeDeviceCode(basedataDevice.getDeviceId(), areaMap, deviceHashMap, idBuilder, pIdBuilder);
            deviceVO.setDataId(idBuilder.toString());
            deviceVO.setParentId(pIdBuilder.toString());
            deviceVO.setAreaId(basedataDevice.getAreaId());
            deviceVO.setDeviceParentId(basedataDevice.getParentId());
            deviceVO.setDeviceId(basedataDevice.getDeviceId());
            deviceVO.setDeviceName(basedataDevice.getDeviceName());
            deviceVO.setPowerMainEquFlag(basedataDevice.getPowerMainEquFlag());
            deviceVO.setPositionX(basedataDevice.getPositionX());
            deviceVO.setPositionY(basedataDevice.getPositionY());
            deviceVO.setPositionZ(basedataDevice.getPositionZ());
            deviceVO.setDeviceLength(basedataDevice.getDeviceLength());
            deviceVO.setDeviceWidth(basedataDevice.getDeviceWidth());
            deviceVO.setDeviceHigh(basedataDevice.getDeviceHeight());
            areaVOS.add(deviceVO);
        }

        return AreaDeviceTreeSelectUtil.buildDeviceTree(areaVOS);
    }

    public List<AreaDeviceTreeSelect> buildAreaDeviceTreeSelectByAreasFilterByPresetRelationLeft(List<BaseDataArea> areas, List<String> filterNamelist) {
        ArrayList<Long> areaIdList = new ArrayList<>();
        HashMap<Long, BaseDataArea> areaMap = new HashMap<>();
        HashMap<Long, BasedataDevice> deviceHashMap = new HashMap<>();
        List<AreaDeviceTreeSelect> areaVOS = new ArrayList<>();

        for (BaseDataArea area : areas) {
            areaIdList.add(area.getAreaId());
            areaMap.put(area.getAreaId(), area);
            AreaDeviceTreeSelect areaVO = new AreaDeviceTreeSelect();
            areaVO.setDataId(String.valueOf(area.getAreaId()));
            areaVO.setParentId(String.valueOf(area.getParentId()));
            areaVO.setAreaId(area.getAreaId());
            areaVO.setAreaFlag("Yes");
            areaVO.setAreaParentId(area.getParentId());
            areaVO.setAreaName(area.getAreaName());
            areaVO.setAreaType(area.getAreaType());
            areaVOS.add(areaVO);
        }

        BasedataDevice basedataDeviceQuery = new BasedataDevice();
        Map<String, Object> params = new HashMap<>();
        params.put("areaIdList", areaIdList);
        basedataDeviceQuery.setParams(params);
        List<BasedataDevice> deviceList = this.basedataDeviceMapper.selectBasedataDeviceList(basedataDeviceQuery);
        Iterator<BasedataDevice> iterator = deviceList.iterator();

        BasedataDevice basedataDevice;
        while (iterator.hasNext()) {
            basedataDevice = iterator.next();
            deviceHashMap.put(basedataDevice.getDeviceId(), basedataDevice);
        }

        iterator = deviceList.iterator();

        while (iterator.hasNext()) {
            basedataDevice = iterator.next();
            AreaDeviceTreeSelect deviceVO = new AreaDeviceTreeSelect();
            StringBuilder idBuilder = new StringBuilder();
            StringBuilder pIdBuilder = new StringBuilder();
            this.getAreaDeviceTreeDeviceCode(basedataDevice.getDeviceId(), areaMap, deviceHashMap, idBuilder, pIdBuilder);
            deviceVO.setDataId(idBuilder.toString());
            deviceVO.setParentId(pIdBuilder.toString());
            deviceVO.setAreaId(basedataDevice.getAreaId());
            deviceVO.setDeviceParentId(basedataDevice.getParentId());
            deviceVO.setDeviceId(basedataDevice.getDeviceId());
            deviceVO.setDeviceName(basedataDevice.getDeviceName());
            deviceVO.setPowerMainEquFlag(basedataDevice.getPowerMainEquFlag());
            deviceVO.setPositionX(basedataDevice.getPositionX());
            deviceVO.setPositionY(basedataDevice.getPositionY());
            deviceVO.setPositionZ(basedataDevice.getPositionZ());
            deviceVO.setDeviceLength(basedataDevice.getDeviceLength());
            deviceVO.setDeviceWidth(basedataDevice.getDeviceWidth());
            deviceVO.setDeviceHigh(basedataDevice.getDeviceHeight());
            areaVOS.add(deviceVO);
        }

        List<AreaDeviceTreeSelect> treeList = AreaDeviceTreeSelectUtil.buildDeviceTreeFilterByAreaName(areaVOS, filterNamelist);

        // 新增：填充点位统计
        fillPointNumAndPatrolPoints(areaVOS, treeList);

        return treeList;
    }

    public List<AreaDeviceTreeSelect> buildAreaDeviceTreeSelectByAreasFilterByPreset(List<BaseDataArea> areas, List<String> filterNamelist) {
        ArrayList<Long> areaIdList = new ArrayList<>();
        HashMap<Long, BaseDataArea> areaMap = new HashMap<>();
        HashMap<Long, BasedataDevice> deviceHashMap = new HashMap<>();
        List<AreaDeviceTreeSelect> areaVOS = new ArrayList<>();

        for (BaseDataArea area : areas) {
            areaIdList.add(area.getAreaId());
            areaMap.put(area.getAreaId(), area);
            AreaDeviceTreeSelect areaVO = new AreaDeviceTreeSelect();
            areaVO.setDataId(String.valueOf(area.getAreaId()));
            areaVO.setParentId(String.valueOf(area.getParentId()));
            areaVO.setAreaId(area.getAreaId());
            areaVO.setAreaFlag("Yes");
            areaVO.setAreaParentId(area.getParentId());
            areaVO.setAreaName(area.getAreaName());
            areaVO.setAreaType(area.getAreaType());
            areaVOS.add(areaVO);
        }

        BasedataDevice basedataDeviceQuery = new BasedataDevice();
        Map<String, Object> params = new HashMap<>();
        params.put("areaIdList", areaIdList);
        basedataDeviceQuery.setParams(params);
        List<BasedataDevice> deviceList = this.basedataDeviceMapper.selectBasedataDeviceList(basedataDeviceQuery);
        Iterator<BasedataDevice> iterator = deviceList.iterator();

        BasedataDevice basedataDevice;
        while (iterator.hasNext()) {
            basedataDevice = iterator.next();
            deviceHashMap.put(basedataDevice.getDeviceId(), basedataDevice);
        }

        iterator = deviceList.iterator();

        while (iterator.hasNext()) {
            basedataDevice = iterator.next();
            AreaDeviceTreeSelect deviceVO = new AreaDeviceTreeSelect();
            StringBuilder idBuilder = new StringBuilder();
            StringBuilder pIdBuilder = new StringBuilder();
            this.getAreaDeviceTreeDeviceCode(basedataDevice.getDeviceId(), areaMap, deviceHashMap, idBuilder, pIdBuilder);
            deviceVO.setDataId(idBuilder.toString());
            deviceVO.setParentId(pIdBuilder.toString());
            deviceVO.setAreaId(basedataDevice.getAreaId());
            deviceVO.setDeviceParentId(basedataDevice.getParentId());
            deviceVO.setDeviceId(basedataDevice.getDeviceId());
            deviceVO.setDeviceName(basedataDevice.getDeviceName());
            deviceVO.setPowerMainEquFlag(basedataDevice.getPowerMainEquFlag());
            deviceVO.setPositionX(basedataDevice.getPositionX());
            deviceVO.setPositionY(basedataDevice.getPositionY());
            deviceVO.setPositionZ(basedataDevice.getPositionZ());
            deviceVO.setDeviceLength(basedataDevice.getDeviceLength());
            deviceVO.setDeviceWidth(basedataDevice.getDeviceWidth());
            deviceVO.setDeviceHigh(basedataDevice.getDeviceHeight());
            areaVOS.add(deviceVO);
        }

        List<AreaDeviceTreeSelect> treeList = AreaDeviceTreeSelectUtil.buildDeviceTreeFilterByAreaName(areaVOS, filterNamelist);

        // 新增：填充点位统计
        fillPointNum(areaVOS, treeList);

        return treeList;
    }

    /**
     * 填充 pointNum 和 basedataPatrolPoints
     * @param allNodes 平面节点列表（包含所有区域和设备节点）
     * @param treeList 构建后的树根节点列表
     */
    private void fillPointNumAndPatrolPoints(List<AreaDeviceTreeSelect> allNodes, List<AreaDeviceTreeSelect> treeList) {
        // 收集所有设备ID
        Set<Long> deviceIds = new HashSet<>();
        for (AreaDeviceTreeSelect node : allNodes) {
            if (node.getDeviceId() != null) {
                deviceIds.add(node.getDeviceId());
            }
        }
        if (deviceIds.isEmpty()) {
            return;
        }

        // 批量查询点位
        List<BasedataPatrolPoint> patrolPoints = basedataPatrolPointMapper.selectBasedataPatrolPointListByDeviceIds(new ArrayList<>(deviceIds));
        // 按设备ID分组
        Map<Long, List<BasedataPatrolPoint>> devicePatrolMap = patrolPoints.stream()
                .collect(Collectors.groupingBy(BasedataPatrolPoint::getDeviceId));

        // 递归设置统计值
        setPointNumAndPatrolPoints(treeList, devicePatrolMap);
    }

    /**
     * 递归设置 pointNum 和 basedataPatrolPoints信息
     */
    private void setPointNumAndPatrolPoints(List<AreaDeviceTreeSelect> nodes, Map<Long, List<BasedataPatrolPoint>> devicePatrolMap) {
        for (AreaDeviceTreeSelect node : nodes) {
            long pointNum = 0L;

            // 处理设备节点自身点位
            if (node.getDeviceId() != null) {
                List<BasedataPatrolPoint> patrols = devicePatrolMap.get(node.getDeviceId());
                if (patrols != null) {
                    pointNum += patrols.size();
                    // 叶子节点（无子节点）才设置点位列表
                    if (node.getChildren() == null || node.getChildren().isEmpty()) {
                        List<BasedataPatrolPoint> basedataPatrolPoints = devicePatrolMap.get(node.getDeviceId());
                        List<AreaDeviceTreeSelect> patrolPoints = new ArrayList<>();
                        for (BasedataPatrolPoint basedataPatrolPoint : basedataPatrolPoints) {
                            AreaDeviceTreeSelect patrolVO = new AreaDeviceTreeSelect();
                            patrolVO.setPatrolPointName(basedataPatrolPoint.getPatrolPointName());
                            patrolVO.setDeviceName(basedataPatrolPoint.getPatrolPointName());
                            patrolVO.setPatrolPointId(String.valueOf(basedataPatrolPoint.getPatrolPointId()));
                            patrolVO.setDataId(String.valueOf(basedataPatrolPoint.getPatrolPointId()));
                            patrolVO.setPatrolPointCode(basedataPatrolPoint.getPatrolPointCode());
                            patrolPoints.add(patrolVO);
                        }
                        // 设置点位列表到节点上
                        node.setChildren(patrolPoints);
                    }
                }
            }

            // 递归处理子节点
            if (node.getChildren() != null && !node.getChildren().isEmpty()) {
                setPointNumAndPatrolPoints(node.getChildren(), devicePatrolMap);
                // 累加子节点 pointNum
                for (AreaDeviceTreeSelect child : node.getChildren()) {
                    pointNum += child.getPointNum() != null ? child.getPointNum() : 0L;
                }
            }

            node.setPointNum(pointNum);
        }
    }


    private void fillPointNum(List<AreaDeviceTreeSelect> allNodes, List<AreaDeviceTreeSelect> treeList) {
        // 收集所有设备ID
        Set<Long> deviceIds = new HashSet<>();
        for (AreaDeviceTreeSelect node : allNodes) {
            if (node.getDeviceId() != null) {
                deviceIds.add(node.getDeviceId());
            }
        }
        if (deviceIds.isEmpty()) {
            return;
        }

        // 批量查询点位
        List<BasedataPatrolPoint> patrolPoints = basedataPatrolPointMapper.selectBasedataPatrolPointListByDeviceIds(new ArrayList<>(deviceIds));
        // 按设备ID分组
        Map<Long, List<BasedataPatrolPoint>> devicePatrolMap = patrolPoints.stream()
                .collect(Collectors.groupingBy(BasedataPatrolPoint::getDeviceId));

        // 递归设置统计值
        setPointNum(treeList, devicePatrolMap);
    }

    /**
     * 递归设置 pointNum 信息
     */
    private void setPointNum(List<AreaDeviceTreeSelect> nodes, Map<Long, List<BasedataPatrolPoint>> devicePatrolMap) {
        for (AreaDeviceTreeSelect node : nodes) {
            long pointNum = 0L;

            // 处理设备节点自身点位
            if (node.getDeviceId() != null) {
                List<BasedataPatrolPoint> patrols = devicePatrolMap.get(node.getDeviceId());
                if (patrols != null) {
                    pointNum += patrols.size();
                }
            }

            // 递归处理子节点
            if (node.getChildren() != null && !node.getChildren().isEmpty()) {
                setPointNum(node.getChildren(), devicePatrolMap);
                // 累加子节点 pointNum
                for (AreaDeviceTreeSelect child : node.getChildren()) {
                    pointNum += child.getPointNum() != null ? child.getPointNum() : 0L;
                }
            }

            node.setPointNum(pointNum);
        }
    }

    private void fillPointNumRelation(List<AreaDeviceTreeSelect> allNodes, List<AreaDeviceTreeSelect> treeList) {
        // 收集所有设备ID
        Set<Long> deviceIds = new HashSet<>();
        for (AreaDeviceTreeSelect node : allNodes) {
            if (node.getDeviceId() != null) {
                deviceIds.add(node.getDeviceId());
            }
        }
        if (deviceIds.isEmpty()) {
            return;
        }

        // 批量查询点位
        List<BasedataPatrolPoint> patrolPoints = basedataPatrolPointMapper.selectBasedataPatrolPointRelationListByDeviceIds(new ArrayList<>(deviceIds));
        // 按设备ID分组
        Map<Long, List<BasedataPatrolPoint>> devicePatrolMap = patrolPoints.stream()
                .collect(Collectors.groupingBy(BasedataPatrolPoint::getRelationDeviceId));

        // 递归设置统计值
        setPointNumRelation(treeList, devicePatrolMap);
    }

    /**
     * 递归设置 pointNum 信息
     */
    private void setPointNumRelation(List<AreaDeviceTreeSelect> nodes, Map<Long, List<BasedataPatrolPoint>> devicePatrolMap) {
        for (AreaDeviceTreeSelect node : nodes) {
            long pointNum = 0L;

            // 处理设备节点自身点位
            if (node.getDeviceId() != null) {
                List<BasedataPatrolPoint> patrols = devicePatrolMap.get(node.getDeviceId());
                if (patrols != null) {
                    pointNum += patrols.size();
                }
            }

            // 递归处理子节点
            if (node.getChildren() != null && !node.getChildren().isEmpty()) {
                setPointNumRelation(node.getChildren(), devicePatrolMap);
                // 累加子节点 pointNum
                for (AreaDeviceTreeSelect child : node.getChildren()) {
                    pointNum += child.getPointNum() != null ? child.getPointNum() : 0L;
                }
            }

            node.setPointNum(pointNum);
        }
    }

    /**
     * 与fillPointNumAndPatrolPoints区别在于查询的表不一样 此处用的是basedata_patrolpoint_relation表，用于迁移数据使用
     */
    private void fillPointNumAndPatrolPointsRelation(List<AreaDeviceTreeSelect> allNodes, List<AreaDeviceTreeSelect> treeList, BaseDataArea baseDataArea) {
        // 收集所有设备ID
        Set<Long> deviceIds = new HashSet<>();
        for (AreaDeviceTreeSelect node : allNodes) {
            if (node.getDeviceId() != null) {
                deviceIds.add(node.getDeviceId());
            }
        }
        if (deviceIds.isEmpty()) {
            return;
        }
        List<BasedataPatrolPoint> patrolPoints = null;
        // 批量查询点位
        if (baseDataArea != null && baseDataArea.getFilterByPreset() != null && baseDataArea.getFilterByPreset()) {
            // 剔除掉未配置预置位的点位
            patrolPoints = basedataPatrolPointMapper.selectBasedataPatrolPointWithPresetRelationListByDeviceIds(new ArrayList<>(deviceIds));
        } else {
            // 全部点位
            patrolPoints = basedataPatrolPointMapper.selectBasedataPatrolPointRelationListByDeviceIds(new ArrayList<>(deviceIds));

        }
        List<BasedataAlgSubtype> basedataAlgSubtypes = basedataAlgSubtypeMapper.selectBasedataAlgSubtypeList(new BasedataAlgSubtype());

        logger.info("[META] basedataAlgSubtypes cnt: {}", basedataAlgSubtypes.size());
        Map<String, String> algSubtypeMap = new HashMap<>();
        basedataAlgSubtypes.forEach((item) -> {
            algSubtypeMap.put(item.getAlgSubtypeId() + "", item.getAlgSubtypeName());
        });
        List<SysDictData> dictList = getSysDictDataList("point_device_type");
        Optional<SysDictData> defaultDictData = dictList.stream()
                .filter(SysDictData::getDefault)
                .findFirst();
        for (BasedataPatrolPoint basedataPatrolPoint : patrolPoints) {
            basedataPatrolPoint.loadAlgSubtypeName(algSubtypeMap);
            processPointType(basedataPatrolPoint, dictList, defaultDictData);
        }

        if (baseDataArea != null && baseDataArea.getDevTypeCodeList() != null && baseDataArea.getDevTypeCodeList().size() > 0) {
            // 设备
            dictList = dictList.stream().filter(item -> baseDataArea.getDevTypeCodeList().contains(item.getDictCode())).collect(Collectors.toList());
            patrolPoints = filterByDeviceTypes(patrolPoints, dictList);
        }

        if (baseDataArea != null && baseDataArea.getAlgTypeCodeList() != null && baseDataArea.getAlgTypeCodeList().size() > 0) {
            // 算法类型
            patrolPoints = filterByAlgTypes(patrolPoints, baseDataArea.getAlgTypeCodeList());
        }
        // 按设备ID分组
        Map<Long, List<BasedataPatrolPoint>> devicePatrolMap = patrolPoints.stream()
                .collect(Collectors.groupingBy(BasedataPatrolPoint::getRelationDeviceId));

        // 递归设置统计值和点位
        setPointNumAndPatrolPoints(treeList, devicePatrolMap);
    }

    private List<BasedataPatrolPoint> filterByAlgTypes(List<BasedataPatrolPoint> patrolPoints, List<Long> algTypeCodeList) {
        // 获取算法分类字典（dictCode=字典编码，dictValue=逗号分隔的子类型ID）
        List<SysDictData> algCategoryDict = getSysDictDataList("point_alg_category");
        // 构建字典编码 -> 子类型ID集合的映射 (例如，"886" -> {"1", "2"})
        Map<Long, Set<String>> labelToSubtypeIds = algCategoryDict.stream()
                .collect(Collectors.toMap(
                        SysDictData::getDictCode,
                        item -> Arrays.stream(item.getDictValue().split(","))
                                .filter(StringUtils::isNotBlank)
                                .collect(Collectors.toSet())
                ));
        logger.info("[META] labelToSubtypeIds : {}", labelToSubtypeIds);

        // 合并所有允许的子类型ID
        Set<String> allowedSubtypeIds = algTypeCodeList.stream()
                .filter(Objects::nonNull)
                .flatMap(dictCode -> labelToSubtypeIds.getOrDefault(dictCode, Collections.emptySet()).stream())
                .collect(Collectors.toSet());

        if (allowedSubtypeIds.isEmpty()) {
            return Collections.emptyList();
        }
        // 筛选出那些 algSubtypeIds 字段（逗号分隔的 ID 字符串）中至少有一个 ID 存在于 allowedSubtypeIds 集合中的对象
        return patrolPoints.stream()
                .filter(point -> {
                    String subtypeIds = point.getAlgSubtypeIds();
                    if (StringUtils.isBlank(subtypeIds)) {
                        return false;
                    }
                    return Arrays.stream(subtypeIds.split(","))
                            .anyMatch(allowedSubtypeIds::contains);
                })
                .collect(Collectors.toList());
    }

    private List<BasedataPatrolPoint> filterByDeviceTypes(List<BasedataPatrolPoint> patrolPoints, List<SysDictData> dictList) {
        Set<String> allowedPointTypeNames = dictList.stream().map(SysDictData::getDictLabel).collect(Collectors.toSet());

        if (allowedPointTypeNames.isEmpty()) {
            return Collections.emptyList();
        }
        return patrolPoints.stream()
                .filter(point -> allowedPointTypeNames.contains(point.getPointTypeName()))
                .collect(Collectors.toList());
    }

    private List<SysDictData> getSysDictDataList(String dictType) {
        return basedataPatrolpointMapper.selectDictDataByType(dictType);
    }

    /**
     * 处理点位的设备类型
     *
     * @param dictList
     * @param basedataPatrolPoint
     */
    private void processPointType(BasedataPatrolPoint basedataPatrolPoint, List<SysDictData> dictList, Optional<SysDictData> defaultDictData) {
        String patrolPointCode = basedataPatrolPoint.getPatrolPointCode();
        if (StringUtils.isNotEmpty(patrolPointCode)) {
            if (patrolPointCode.contains("|")) {
                String finalPatrolPointCode = patrolPointCode.substring(0, patrolPointCode.indexOf("|"));
                Optional<String> pointTypeName = dictList.stream()
                        .filter(dict -> {
                            String valueStr = dict.getDictValue(); // 调用 getter
                            if (valueStr == null) {
                                return false;
                            }
                            return Arrays.stream(valueStr.split(","))
                                    .map(String::trim)
                                    .anyMatch(code -> code.equals(finalPatrolPointCode));
                        })
                        .map(SysDictData::getDictLabel)
                        .findFirst();
                basedataPatrolPoint.setPointTypeName(pointTypeName.orElse("未知设备类型"));
                basedataPatrolPoint.setPointTypeCode(finalPatrolPointCode);
            } else {
                defaultDictData.ifPresent(dict -> {
                    basedataPatrolPoint.setPointTypeName(dict.getDictLabel());
                    String[] codes = dict.getDictValue().split(",");
                    logger.info("[META] pointTypeCode: {}", codes);
                    if (codes.length > 0) {
                        basedataPatrolPoint.setPointTypeCode(codes[0]);
                    }
                });
            }
        }
    }

    public List<AreaDeviceTreeSelect> buildAreaDeviceTreeSelectByAreasFilterByPresetRelation(List<BaseDataArea> areas, List<String> filterNamelist) {
        ArrayList<Long> areaIdList = new ArrayList<>();
        HashMap<Long, BaseDataArea> areaMap = new HashMap<>();
        HashMap<Long, BasedataDevice> deviceHashMap = new HashMap<>();
        List<AreaDeviceTreeSelect> areaVOS = new ArrayList<>();

        // 根据新的relationParentId和relationAncestors构建树结构
        for (BaseDataArea area : areas) {
            areaIdList.add(area.getAreaId());
            areaMap.put(area.getAreaId(), area);
            AreaDeviceTreeSelect areaVO = new AreaDeviceTreeSelect();
            areaVO.setDataId(String.valueOf(area.getAreaId()));
            areaVO.setParentId(String.valueOf(area.getRelationParentId()));
            areaVO.setAreaId(area.getAreaId());
            areaVO.setAreaFlag("Yes");
            areaVO.setAreaParentId(area.getRelationParentId());
            areaVO.setAreaName(area.getAreaName());
            areaVO.setAreaType(area.getAreaType());
            areaVOS.add(areaVO);
        }

        BasedataDevice basedataDeviceQuery = new BasedataDevice();
        Map<String, Object> params = new HashMap<>();
        params.put("areaIdList", areaIdList);
        basedataDeviceQuery.setParams(params);
        // 根据新的relation_area_id查询设备信息，构建树结构
        List<BasedataDevice> deviceList = this.basedataDeviceMapper.selectBasedataDeviceRelationList(basedataDeviceQuery);
        Iterator<BasedataDevice> iterator = deviceList.iterator();

        BasedataDevice basedataDevice;
        while (iterator.hasNext()) {
            basedataDevice = iterator.next();
            deviceHashMap.put(basedataDevice.getDeviceId(), basedataDevice);
        }

        iterator = deviceList.iterator();

        while (iterator.hasNext()) {
            basedataDevice = iterator.next();
            AreaDeviceTreeSelect deviceVO = new AreaDeviceTreeSelect();
            StringBuilder idBuilder = new StringBuilder();
            StringBuilder pIdBuilder = new StringBuilder();
            this.getAreaDeviceTreeDeviceCodeRelation(basedataDevice.getDeviceId(), areaMap, deviceHashMap, idBuilder, pIdBuilder);
            deviceVO.setDataId(idBuilder.toString());
            deviceVO.setParentId(pIdBuilder.toString());
            deviceVO.setAreaId(basedataDevice.getRelationAreaId());
            deviceVO.setDeviceParentId(basedataDevice.getParentId());
            deviceVO.setDeviceId(basedataDevice.getDeviceId());
            deviceVO.setDeviceName(basedataDevice.getDeviceName());
            deviceVO.setPowerMainEquFlag(basedataDevice.getPowerMainEquFlag());
            deviceVO.setPositionX(basedataDevice.getPositionX());
            deviceVO.setPositionY(basedataDevice.getPositionY());
            deviceVO.setPositionZ(basedataDevice.getPositionZ());
            deviceVO.setDeviceLength(basedataDevice.getDeviceLength());
            deviceVO.setDeviceWidth(basedataDevice.getDeviceWidth());
            deviceVO.setDeviceHigh(basedataDevice.getDeviceHeight());
            areaVOS.add(deviceVO);
        }

        List<AreaDeviceTreeSelect> treeList = AreaDeviceTreeSelectUtil.buildDeviceTreeFilterByAreaName(areaVOS, filterNamelist);

        // 新增：填充点位统计
        fillPointNumRelation(areaVOS, treeList);

        return treeList;
    }

    public List<AreaDeviceTreeSelect> buildAreaDeviceTreeSelectByAreasFilterByPresetRelationRight(List<BaseDataArea> areas, List<String> filterNamelist, BaseDataArea baseDataArea) {
        ArrayList<Long> areaIdList = new ArrayList<>();
        HashMap<Long, BaseDataArea> areaMap = new HashMap<>();
        HashMap<Long, BasedataDevice> deviceHashMap = new HashMap<>();
        List<AreaDeviceTreeSelect> areaVOS = new ArrayList<>();

        for (BaseDataArea area : areas) {
            areaIdList.add(area.getAreaId());
            areaMap.put(area.getAreaId(), area);
            AreaDeviceTreeSelect areaVO = new AreaDeviceTreeSelect();
            areaVO.setDataId(String.valueOf(area.getAreaId()));
            areaVO.setParentId(String.valueOf(area.getRelationParentId()));
            areaVO.setAreaId(area.getAreaId());
            areaVO.setAreaFlag("Yes");
            areaVO.setAreaParentId(area.getRelationParentId());
            areaVO.setAreaName(area.getAreaName());
            areaVO.setAreaType(area.getAreaType());
            areaVOS.add(areaVO);
        }

        BasedataDevice basedataDeviceQuery = new BasedataDevice();
        Map<String, Object> params = new HashMap<>();
        params.put("areaIdList", areaIdList);
        basedataDeviceQuery.setParams(params);
        List<BasedataDevice> deviceList = this.basedataDeviceMapper.selectBasedataDeviceRelationList(basedataDeviceQuery);
        Iterator<BasedataDevice> iterator = deviceList.iterator();

        BasedataDevice basedataDevice;
        while (iterator.hasNext()) {
            basedataDevice = iterator.next();
            deviceHashMap.put(basedataDevice.getDeviceId(), basedataDevice);
        }

        iterator = deviceList.iterator();

        while (iterator.hasNext()) {
            basedataDevice = iterator.next();
            AreaDeviceTreeSelect deviceVO = new AreaDeviceTreeSelect();
            StringBuilder idBuilder = new StringBuilder();
            StringBuilder pIdBuilder = new StringBuilder();
            this.getAreaDeviceTreeDeviceCodeRelation(basedataDevice.getDeviceId(), areaMap, deviceHashMap, idBuilder, pIdBuilder);
            deviceVO.setDataId(idBuilder.toString());
            deviceVO.setParentId(pIdBuilder.toString());
            deviceVO.setAreaId(basedataDevice.getRelationAreaId());
            deviceVO.setDeviceParentId(basedataDevice.getParentId());
            deviceVO.setDeviceId(basedataDevice.getDeviceId());
            deviceVO.setDeviceName(basedataDevice.getDeviceName());
            deviceVO.setPowerMainEquFlag(basedataDevice.getPowerMainEquFlag());
            deviceVO.setPositionX(basedataDevice.getPositionX());
            deviceVO.setPositionY(basedataDevice.getPositionY());
            deviceVO.setPositionZ(basedataDevice.getPositionZ());
            deviceVO.setDeviceLength(basedataDevice.getDeviceLength());
            deviceVO.setDeviceWidth(basedataDevice.getDeviceWidth());
            deviceVO.setDeviceHigh(basedataDevice.getDeviceHeight());
            areaVOS.add(deviceVO);
        }

        List<AreaDeviceTreeSelect> treeList = AreaDeviceTreeSelectUtil.buildDeviceTreeFilterByAreaName(areaVOS, filterNamelist);

        // 新增：填充点位统计
        fillPointNumAndPatrolPointsRelation(areaVOS, treeList, baseDataArea);
        for (AreaDeviceTreeSelect area : treeList) {
            area.cleanEmptyPatrolPoints();
        }
        return treeList;
    }
    public List<AreaDeviceTreeSelect> buildAreaDeviceTreeSelectByAreasFilterByMeter(List<BaseDataArea> areas) {
        ArrayList<Long> areaIdList = new ArrayList<>();
        HashMap<Long, BaseDataArea> areaMap = new HashMap<>();
        HashMap<Long, BasedataDevice> deviceHashMap = new HashMap<>();
        List<AreaDeviceTreeSelect> areaVOS = new ArrayList<>();

        for (BaseDataArea area : areas) {
            areaIdList.add(area.getAreaId());
            areaMap.put(area.getAreaId(), area);
            AreaDeviceTreeSelect areaVO = new AreaDeviceTreeSelect();
            areaVO.setDataId(String.valueOf(area.getAreaId()));
            areaVO.setParentId(String.valueOf(area.getParentId()));
            areaVO.setAreaId(area.getAreaId());
            areaVO.setAreaFlag("Yes");
            areaVO.setAreaParentId(area.getParentId());
            areaVO.setAreaName(area.getAreaName());
            areaVO.setAreaType(area.getAreaType());
            areaVOS.add(areaVO);
        }

        BasedataDevice basedataDeviceQuery = new BasedataDevice();
        Map<String, Object> params = new HashMap<>();
        params.put("areaIdList", areaIdList);
        basedataDeviceQuery.setParams(params);
        List<BasedataDevice> deviceList = basedataDeviceMapper.selectBasedataDeviceListFilterByMeter(basedataDeviceQuery);
        Iterator<BasedataDevice> iterator = deviceList.iterator();

        BasedataDevice basedataDevice;
        while (iterator.hasNext()) {
            basedataDevice = iterator.next();
            deviceHashMap.put(basedataDevice.getDeviceId(), basedataDevice);
        }

        iterator = deviceList.iterator();

        while (iterator.hasNext()) {
            basedataDevice = iterator.next();
            logger.info("DEVICE_TREE_BY_METER patrolPointId: {}, patrolPointName: {}", basedataDevice.getPatrolPointId(), basedataDevice.getPatrolPointName());
            AreaDeviceTreeSelect deviceVO = new AreaDeviceTreeSelect();
            StringBuilder idBuilder = new StringBuilder();
            StringBuilder pIdBuilder = new StringBuilder();
            getAreaDeviceTreeDeviceCode(basedataDevice.getDeviceId(), areaMap, deviceHashMap, idBuilder, pIdBuilder);
            deviceVO.setDataId(idBuilder.toString());
            deviceVO.setParentId(pIdBuilder.toString());
            deviceVO.setAreaId(basedataDevice.getAreaId());
            deviceVO.setDeviceParentId(basedataDevice.getParentId());
            deviceVO.setDeviceId(basedataDevice.getDeviceId());
            deviceVO.setDeviceName(basedataDevice.getDeviceName());
            deviceVO.setPowerMainEquFlag(basedataDevice.getPowerMainEquFlag());
            deviceVO.setPositionX(basedataDevice.getPositionX());
            deviceVO.setPositionY(basedataDevice.getPositionY());
            deviceVO.setPositionZ(basedataDevice.getPositionZ());
            deviceVO.setDeviceLength(basedataDevice.getDeviceLength());
            deviceVO.setDeviceWidth(basedataDevice.getDeviceWidth());
            deviceVO.setDeviceHigh(basedataDevice.getDeviceHeight());
            deviceVO.setPatrolPointId(basedataDevice.getPatrolPointId());
            deviceVO.setPatrolPointName(basedataDevice.getPatrolPointName());
            //deviceVO.setDeviceName(basedataDevice.getPatrolPointName());
            areaVOS.add(deviceVO);
        }

        List<AreaDeviceTreeSelect> results = AreaDeviceTreeSelectUtil.buildDeviceTreeByAreaMeter(areaVOS);
        for (AreaDeviceTreeSelect area : results) {
            area.cleanEmptyPatrolPoints();
        }
        return results;
    }

    public List<AreaDeviceTreeSelect> buildAreaDeviceTreeSelectByAreasFilterByFault(List<BaseDataArea> areas) {
        ArrayList<Long> areaIdList = new ArrayList<>();
        HashMap<Long, BaseDataArea> areaMap = new HashMap<>();
        HashMap<Long, BasedataDevice> deviceHashMap = new HashMap<>();
        List<AreaDeviceTreeSelect> areaVOS = new ArrayList<>();

        for (BaseDataArea area : areas) {
            areaIdList.add(area.getAreaId());
            areaMap.put(area.getAreaId(), area);
            AreaDeviceTreeSelect areaVO = new AreaDeviceTreeSelect();
            areaVO.setDataId(String.valueOf(area.getAreaId()));
            areaVO.setParentId(String.valueOf(area.getParentId()));
            areaVO.setAreaId(area.getAreaId());
            areaVO.setAreaFlag("Yes");
            areaVO.setAreaParentId(area.getParentId());
            areaVO.setAreaName(area.getAreaName());
            areaVO.setAreaType(area.getAreaType());
            areaVOS.add(areaVO);
        }

        BasedataDevice basedataDeviceQuery = new BasedataDevice();
        Map<String, Object> params = new HashMap<>();
        params.put("areaIdList", areaIdList);
        basedataDeviceQuery.setParams(params);
        List<BasedataDevice> deviceList = basedataDeviceMapper.selectBasedataDeviceListWithPreset(basedataDeviceQuery);
        Iterator<BasedataDevice> iterator = deviceList.iterator();

        BasedataDevice basedataDevice;
        while (iterator.hasNext()) {
            basedataDevice = iterator.next();
            deviceHashMap.put(basedataDevice.getDeviceId(), basedataDevice);
        }

        iterator = deviceList.iterator();

        while (iterator.hasNext()) {
            basedataDevice = iterator.next();
            logger.info("DEVICE_TREE_BY_FAULT patrolPointId: {}, patrolPointName: {}", basedataDevice.getPatrolPointId(), basedataDevice.getPatrolPointName());
            AreaDeviceTreeSelect deviceVO = new AreaDeviceTreeSelect();
            StringBuilder idBuilder = new StringBuilder();
            StringBuilder pIdBuilder = new StringBuilder();
            getAreaDeviceTreeDeviceCode(basedataDevice.getDeviceId(), areaMap, deviceHashMap, idBuilder, pIdBuilder);
            deviceVO.setDataId(idBuilder.toString());
            deviceVO.setParentId(pIdBuilder.toString());
            deviceVO.setAreaId(basedataDevice.getAreaId());
            deviceVO.setDeviceParentId(basedataDevice.getParentId());
            deviceVO.setDeviceId(basedataDevice.getDeviceId());
            deviceVO.setDeviceName(basedataDevice.getDeviceName());
            deviceVO.setPowerMainEquFlag(basedataDevice.getPowerMainEquFlag());
            deviceVO.setPositionX(basedataDevice.getPositionX());
            deviceVO.setPositionY(basedataDevice.getPositionY());
            deviceVO.setPositionZ(basedataDevice.getPositionZ());
            deviceVO.setDeviceLength(basedataDevice.getDeviceLength());
            deviceVO.setDeviceWidth(basedataDevice.getDeviceWidth());
            deviceVO.setDeviceHigh(basedataDevice.getDeviceHeight());
            deviceVO.setPatrolPointId(basedataDevice.getPatrolPointId());
            deviceVO.setPatrolPointName(basedataDevice.getPatrolPointName());
            //deviceVO.setDeviceName(basedataDevice.getPatrolPointName());
            areaVOS.add(deviceVO);
        }

        List<AreaDeviceTreeSelect> results = AreaDeviceTreeSelectUtil.buildDeviceTreeByAreaMeter(areaVOS);
        for (AreaDeviceTreeSelect area : results) {
            area.cleanEmptyPatrolPoints();
        }

        return results;
    }


    private void getAreaDeviceTreeDeviceCode(Long deviceId, HashMap<Long, BaseDataArea> areaMap, HashMap<Long, BasedataDevice> deviceHashMap, StringBuilder idBuilder, StringBuilder pIdBuilder) {
        if (deviceHashMap.containsKey(deviceId)) {
            BasedataDevice device = deviceHashMap.get(deviceId);
            idBuilder.insert(0, "-" + deviceId);
            Long parentId = device.getParentId();
            Long areaId;
            if (deviceId.longValue() == parentId.longValue()) {
                areaId = device.getAreaId();
                idBuilder.insert(0, areaId);
                pIdBuilder.insert(0, areaId);
                return;
            }

            if (deviceHashMap.containsKey(parentId)) {
                pIdBuilder.insert(0, "-" + parentId);
                this.getAreaDeviceTreeDeviceCode(parentId, areaMap, deviceHashMap, idBuilder, pIdBuilder);
            } else {
                areaId = device.getAreaId();
                idBuilder.insert(0, areaId);
                pIdBuilder.insert(0, areaId);
            }
        }

    }

    private void getAreaDeviceTreeDeviceCodeRelation(Long deviceId, HashMap<Long, BaseDataArea> areaMap, HashMap<Long, BasedataDevice> deviceHashMap, StringBuilder idBuilder, StringBuilder pIdBuilder) {
        if (deviceHashMap.containsKey(deviceId)) {
            BasedataDevice device = deviceHashMap.get(deviceId);
            idBuilder.insert(0, "-" + deviceId);
            Long parentId = device.getParentId();
            Long areaId;
            if (deviceId.longValue() == parentId.longValue()) {
                areaId = device.getRelationAreaId();
                idBuilder.insert(0, areaId);
                pIdBuilder.insert(0, areaId);
                return;
            }

            if (deviceHashMap.containsKey(parentId)) {
                pIdBuilder.insert(0, "-" + parentId);
                this.getAreaDeviceTreeDeviceCodeRelation(parentId, areaMap, deviceHashMap, idBuilder, pIdBuilder);
            } else {
                areaId = device.getRelationAreaId();
                idBuilder.insert(0, areaId);
                pIdBuilder.insert(0, areaId);
            }
        }

    }

    public List<BaseDataAreaProDeviceVO> getAreaDeviceList(List<BaseDataArea> areas) {
        List<BaseDataAreaProDeviceVO> proDeviceVOS = new ArrayList<>();
        List<BasedataDevice> mainDeviceList = this.basedataDeviceMapper.selectBasedataDeviceMainEquBatchByAreas(areas);

        for (BasedataDevice basedataDevice : mainDeviceList) {
            BaseDataAreaProDeviceVO baseDataAreaProDeviceVO = new BaseDataAreaProDeviceVO();
            BeanUtils.copyBeanProp(baseDataAreaProDeviceVO, basedataDevice);
            baseDataAreaProDeviceVO.setParentIdString(String.valueOf(baseDataAreaProDeviceVO.getAreaId()));
            baseDataAreaProDeviceVO.setAreaIdString(baseDataAreaProDeviceVO.getAreaId() + "-" + baseDataAreaProDeviceVO.getDeviceId());
            baseDataAreaProDeviceVO.setDeviceParentId(basedataDevice.getParentId());
            this.getPositionByModel(baseDataAreaProDeviceVO);
            proDeviceVOS.add(baseDataAreaProDeviceVO);
            this.getCompDeviceVo(proDeviceVOS, baseDataAreaProDeviceVO);
        }

        return proDeviceVOS;
    }

    public void getCompDeviceVo(List<BaseDataAreaProDeviceVO> proDeviceVOS, BaseDataAreaProDeviceVO baseDataAreaProDeviceVO) {
        BasedataDevice basedataDeviceQuery = new BasedataDevice();
        basedataDeviceQuery.setParentId(baseDataAreaProDeviceVO.getDeviceId());
        List<BasedataDevice> compontlist = this.basedataDeviceMapper.selectBasedataDeviceList(basedataDeviceQuery);
        if (!compontlist.isEmpty()) {

            for (BasedataDevice basedataDevice : compontlist) {
                BaseDataAreaProDeviceVO areaProDeviceVO = new BaseDataAreaProDeviceVO();
                BeanUtils.copyBeanProp(areaProDeviceVO, basedataDevice);
                areaProDeviceVO.setAreaIdString(baseDataAreaProDeviceVO.getAreaIdString() + "-" + basedataDevice.getDeviceId());
                areaProDeviceVO.setParentIdString(String.valueOf(baseDataAreaProDeviceVO.getAreaIdString()));
                areaProDeviceVO.setDeviceParentId(basedataDevice.getParentId());
                this.getPositionByModel(baseDataAreaProDeviceVO);
                proDeviceVOS.add(areaProDeviceVO);
                this.getCompDeviceVo(proDeviceVOS, areaProDeviceVO);
            }

        }
    }

    public void getPositionByModel(BaseDataAreaProDeviceVO baseDataAreaProDeviceVO) {
        BasedataModelDevice basedataModelDevice = new BasedataModelDevice();
        basedataModelDevice.setDeviceId(baseDataAreaProDeviceVO.getDeviceId());
        List<BasedataModelDevice> models = this.basedataModelDeviceMapper.selectBasedataModelDeviceList(basedataModelDevice);
        if (!models.isEmpty()) {
            BasedataModelDevice model = models.get(0);
            baseDataAreaProDeviceVO.setPositionX(model.getPositionX());
            baseDataAreaProDeviceVO.setPositionY(model.getPositionY());
            baseDataAreaProDeviceVO.setPositionZ(model.getPositionZ());
            baseDataAreaProDeviceVO.setDeviceLength(model.getDeviceLength());
            baseDataAreaProDeviceVO.setDeviceWidth(model.getDeviceWidth());
            baseDataAreaProDeviceVO.setDeviceHigh(model.getDeviceHigh());
        }

    }

    public List buildAreaTree(List<BaseDataAreaProDeviceVO> areas) {
        List<BaseDataAreaProDeviceVO> returnList = new ArrayList<>();
        List<String> tempList = new ArrayList<>();
        Iterator<BaseDataAreaProDeviceVO> iterator = areas.iterator();

        BaseDataAreaProDeviceVO area;
        while (iterator.hasNext()) {
            area = iterator.next();
            tempList.add(area.getAreaIdString());
        }

        iterator = areas.iterator();

        while (iterator.hasNext()) {
            area = iterator.next();
            if (!tempList.contains(area.getParentIdString())) {
                this.recursionFn(areas, area);
                returnList.add(area);
            }
        }

        if (returnList.isEmpty()) {
            returnList = areas;
        }

        return returnList;
    }

    private void recursionFn(List<BaseDataAreaProDeviceVO> list, BaseDataAreaProDeviceVO t) {
        List<BaseDataAreaProDeviceVO> childList = this.getChildList(list, t);
        t.setChildren(childList);

        for (BaseDataAreaProDeviceVO tChild : childList) {
            if (this.hasChild(list, tChild)) {
                this.recursionFn(list, tChild);
            }
        }

    }

    private List<BaseDataAreaProDeviceVO> getChildList(List<BaseDataAreaProDeviceVO> list, BaseDataAreaProDeviceVO t) {
        List<BaseDataAreaProDeviceVO> tlist = new ArrayList<>();

        for (BaseDataAreaProDeviceVO n : list) {
            if (StringUtils.isNotNull(n.getParentIdString()) && n.getParentIdString().equals(t.getAreaIdString())) {
                tlist.add(n);
            }
        }

        return tlist;
    }

    private boolean hasChild(List<BaseDataAreaProDeviceVO> list, BaseDataAreaProDeviceVO t) {
        return !this.getChildList(list, t).isEmpty();
    }

    public List<ProMainDevicePatrolEquTreeSelect> treeProMainDevicePatrolEquSelectOld(List<BasedataDevice> mainDevices) {
        List<ProMainDevicePatrolEquTreeSelect> mainDevVOS = new ArrayList<>();
        List<BasedataDevice> mainDeviceExistPointList = new ArrayList<>();
        if (!mainDevices.isEmpty()) {
            Iterator<BasedataDevice> iterator = mainDevices.iterator();
            logger.info("---111-------mainDevices:{}", mainDevices);
            BasedataDevice mainDevice;
            BasedataPatrolPoint basedataPatrolpoint;
            while (iterator.hasNext()) {
                mainDevice = iterator.next();
                BasedataPatrolPoint patrolPointMainDevQuery = new BasedataPatrolPoint();
                patrolPointMainDevQuery.setMainDeviceId(mainDevice.getDeviceId());
                // 查询设备下有预置点的点位信息（一个）
                basedataPatrolpoint = this.basedataPatrolPointMapper.selectBasedataPatrolPointPresetForOne(patrolPointMainDevQuery);
                // 该设备下存在预置点位信息
                if (null != basedataPatrolpoint) {
                    BasedataDevice mainDeviceForQuery = new BasedataDevice();
                    BeanUtils.copyBeanProp(mainDeviceForQuery, mainDevice);
                    mainDeviceExistPointList.add(mainDeviceForQuery);
                    ProMainDevicePatrolEquTreeSelect mainDevVO = new ProMainDevicePatrolEquTreeSelect();
                    mainDevVO.setDataId(String.valueOf(mainDevice.getDeviceId()));
                    mainDevVO.setMainDeviceId(mainDevice.getDeviceId());
                    mainDevVO.setLabel(mainDevice.getDeviceName());
                    mainDevVO.setMainDeviceName(mainDevice.getDeviceName());
                    mainDevVO.setPowerMainEquFlag("Yes");
                    mainDevVO.setPositionX(mainDevice.getPositionX());
                    mainDevVO.setPositionY(mainDevice.getPositionY());
                    mainDevVO.setPositionZ(mainDevice.getPositionZ());
                    // 添加设备信息
                    mainDevVOS.add(mainDevVO);
                }
            }

            iterator = mainDeviceExistPointList.iterator();
            logger.info("---222------存在预置位的点位设备-mainDeviceExistPointList:{}", mainDeviceExistPointList);
            label70:
            while (true) {
                List patrolpointList;
                String mainDeviceName;
                HashMap mapDevToPoint;
                do {
                    if (!iterator.hasNext()) {
                        break label70;
                    }

                    mainDevice = iterator.next();
                    mainDeviceName = mainDevice.getDeviceName();
                    basedataPatrolpoint = new BasedataPatrolPoint();
                    basedataPatrolpoint.setMainDeviceId(mainDevice.getDeviceId());
                    mapDevToPoint = new HashMap<>();
                    // 查询设备下的所有点位信息
                    patrolpointList = this.basedataPatrolPointMapper.selectBasedataPatrolPointList(basedataPatrolpoint);
                } while (patrolpointList.isEmpty());

                Iterator iterator1 = patrolpointList.iterator();
                logger.info("---333-------patrolpointList:{}", patrolpointList);
                BasedataPatrolPoint patrolpoint;
                while (iterator1.hasNext()) {
                    patrolpoint = (BasedataPatrolPoint) iterator1.next();
                    BasedataPatrolPoint patrolPointIsExistPreset = new BasedataPatrolPoint();
                    patrolPointIsExistPreset.setPatrolPointId(patrolpoint.getPatrolPointId());
                    // 判断点位下是否存在预置信息
                    BasedataPatrolPoint patrolPointExistOne = this.basedataPatrolPointMapper.selectBasedataPatrolPointPresetForOne(patrolPointIsExistPreset);
                    // 存在预置信息
                    if (null != patrolPointExistOne) {
                        Long mainDeviceId = patrolpoint.getMainDeviceId();
                        Long deviceId = patrolpoint.getDeviceId();
                        if (deviceId.longValue() != mainDeviceId.longValue() && !mapDevToPoint.containsKey(deviceId)) {
                            this.recursionGetProMainDevice(mainDeviceId, mainDeviceName, deviceId, mainDevVOS, mapDevToPoint);
                        }

                        ProMainDevicePatrolEquTreeSelect pointTreeVO = new ProMainDevicePatrolEquTreeSelect();
                        pointTreeVO.setPatrolpointId(patrolpoint.getPatrolPointId());
                        pointTreeVO.setDataId(deviceId + "-" + patrolpoint.getPatrolPointId());
                        pointTreeVO.setLabel(patrolpoint.getPatrolPointName());
                        pointTreeVO.setPatrolpointName(patrolpoint.getPatrolPointName());
                        pointTreeVO.setMainDeviceName(mainDeviceName);
                        pointTreeVO.setParentId(String.valueOf(deviceId));
                        pointTreeVO.setPatrolpointFlag("Yes");
                        pointTreeVO.setPositionX(patrolpoint.getPositionX());
                        pointTreeVO.setPositionY(patrolpoint.getPositionY());
                        pointTreeVO.setPositionZ(patrolpoint.getPositionZ());
                        // 添加点位信息
                        mainDevVOS.add(pointTreeVO);
                    }
                }

                iterator1 = patrolpointList.iterator();

                while (true) {
                    List patrolpointPresetS;
                    do {
                        if (!iterator1.hasNext()) {
                            continue label70;
                        }

                        patrolpoint = (BasedataPatrolPoint) iterator1.next();
                        BasedataPatrolPointPreset basedataPatrolpointPreset = new BasedataPatrolPointPreset();
                        basedataPatrolpointPreset.setPatrolPointId(patrolpoint.getPatrolPointId());
                        // 查询点位下预置位信息
                        patrolpointPresetS = this.basedataPatrolPointPresetMapper.selectBasedataPatrolPointPresetList(basedataPatrolpointPreset);
                    } while (patrolpointPresetS.isEmpty());
                    logger.info("---444-------patrolpointPresetS:{}", patrolpointPresetS);
                    HashMap<Long, Long> map = new HashMap<>();
                    for (Object patrolPointPreset : patrolpointPresetS) {
                        BasedataPatrolPointPreset preset = (BasedataPatrolPointPreset) patrolPointPreset;
                        if (!map.containsKey(preset.getEqpBookId())) {
                            ProMainDevicePatrolEquTreeSelect pointPreSetTreeVO = new ProMainDevicePatrolEquTreeSelect();
                            pointPreSetTreeVO.setParentId(patrolpoint.getDeviceId() + "-" + patrolpoint.getPatrolPointId());
                            pointPreSetTreeVO.setEqpbookId(preset.getEqpBookId());
                            pointPreSetTreeVO.setPresetCode(preset.getPresetCode());
                            logger.info("---555-------BasedataPatrolPointPreset:{}", preset);
                            if (null != preset.getEqpBookId()) {
                                BasedataEqpBook basedataEqpbook = this.basedataEqpbookMapper.selectBasedataEqpBookByEqpBookId(preset.getEqpBookId());
                                if (null != basedataEqpbook) {
                                    pointPreSetTreeVO.setPatroldeviceName(basedataEqpbook.getPatrolDeviceName());
                                    pointPreSetTreeVO.setMainDeviceName(basedataEqpbook.getPatrolDeviceName());
                                    pointPreSetTreeVO.setLabel(basedataEqpbook.getPatrolDeviceName());
                                    pointPreSetTreeVO.setPatroldeviceCode(basedataEqpbook.getPatrolDeviceCode());
                                    pointPreSetTreeVO.setPatroldeviceName(basedataEqpbook.getPatrolDeviceName());
                                    pointPreSetTreeVO.setDataId(patrolpoint.getDeviceId() + "-" + patrolpoint.getPatrolPointId() + basedataEqpbook.getEqpBookId());
                                    pointPreSetTreeVO.setPatroldeviceFlag("Yes");
                                    map.put(basedataEqpbook.getEqpBookId(), basedataEqpbook.getEqpBookId());
                                    // 添加巡视设备（ebook）信息
                                    mainDevVOS.add(pointPreSetTreeVO);
                                }
                            }
                        }
                    }
                }
            }
        }
        logger.info("----------------mainDevVOS:{} ", mainDevVOS);
        return (List<ProMainDevicePatrolEquTreeSelect>) ProMainDevicePatrolEquTreeSelectUtil.buildDeviceTree(mainDevVOS);
    }


    public List<ProMainDevicePatrolEquTreeSelect> treeProMainDevicePatrolEquSelect(List<BasedataDevice> mainDevices) {
        List<ProMainDevicePatrolEquTreeSelect> mainDevVOS = new ArrayList<>();
        List<BasedataDevice> mainDeviceExistPointList = new ArrayList<>();

        if (mainDevices == null || mainDevices.isEmpty()) {
            return mainDevVOS;
        }

        logger.info("---111-------mainDevices:{}", mainDevices);
        // 第一层处理：主设备预置点检查
        List<Long> deviceIds = mainDevices.stream().map(BasedataDevice::getDeviceId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        List<BasedataPatrolPoint> basedataPatrolpoints = this.basedataPatrolPointMapper.selectBasedataPatrolPointPresetByMainDeviceIds(deviceIds);
        for (BasedataDevice mainDevice : mainDevices) {
            // 查询设备下的预置点是否存在
            boolean exists = basedataPatrolpoints.stream()
                    .filter(Objects::nonNull)
                    .anyMatch(device -> mainDevice.getDeviceId().equals(device.getMainDeviceId()));
            if (exists) {
                //  复制设备信息到新对象
                BasedataDevice mainDeviceForQuery = new BasedataDevice();
                BeanUtils.copyBeanProp(mainDeviceForQuery, mainDevice);
                mainDeviceExistPointList.add(mainDeviceForQuery);

                // 创建主设备节点
                ProMainDevicePatrolEquTreeSelect mainDevVO = new ProMainDevicePatrolEquTreeSelect();
                mainDevVO.setDataId(String.valueOf(mainDevice.getDeviceId()));
                mainDevVO.setMainDeviceId(mainDevice.getDeviceId());
                mainDevVO.setLabel(mainDevice.getDeviceName());
                mainDevVO.setMainDeviceName(mainDevice.getDeviceName());
                mainDevVO.setPowerMainEquFlag("Yes");
                mainDevVO.setPositionX(mainDevice.getPositionX());
                mainDevVO.setPositionY(mainDevice.getPositionY());
                mainDevVO.setPositionZ(mainDevice.getPositionZ());
                mainDevVOS.add(mainDevVO);
            }
        }

        logger.info("---222------存在预置位的点位设备-mainDeviceExistPointList:{}", mainDeviceExistPointList);

        // 第二层处理：设备下的点位信息
        if (!mainDeviceExistPointList.isEmpty()) {
            // 批量获取所有相关点位信息
            List<Long> mainDeviceIds = mainDeviceExistPointList.stream()
                    .map(BasedataDevice::getDeviceId)
                    .collect(Collectors.toList());
            // 查询所有设备下的所有点位信息
            List<BasedataPatrolPoint> allPatrolPoints = basedataPatrolPointMapper
                    .selectBasedataPatrolPointListByMainDeviceIds(mainDeviceIds);

            // 按mainDeviceId分组点位信息
            Map<Long, List<BasedataPatrolPoint>> patrolPointsByMainDevice = allPatrolPoints.stream()
                    .filter(Objects::nonNull)
                    .collect(Collectors.groupingBy(BasedataPatrolPoint::getMainDeviceId));

            // 批量获取所有相关点位的预置信息
            List<Long> allPatrolPointIds = allPatrolPoints.stream()
                    .filter(Objects::nonNull)
                    .map(BasedataPatrolPoint::getPatrolPointId)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.toList());

            List<BasedataPatrolPointPreset> allPresets = new ArrayList<>();
            if (!allPatrolPointIds.isEmpty()) {
                allPresets = basedataPatrolPointPresetMapper
                        .selectBasedataPatrolPointPresetListByPointIds(allPatrolPointIds);
            }

            // 按点位ID分组预置信息
            Map<Long, List<BasedataPatrolPointPreset>> presetsByPointId = allPresets.stream()
                    .filter(Objects::nonNull)
                    .collect(Collectors.groupingBy(BasedataPatrolPointPreset::getPatrolPointId));

            // 批量获取所有相关的设备信息
            List<Long> pointDeviceIds = allPatrolPoints.stream()
                    .filter(Objects::nonNull)
                    .map(BasedataPatrolPoint::getDeviceId)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.toList());

            // 批量获取所有相关的设备手册信息
            List<Long> eqpBookIds = allPresets.stream()
                    .filter(Objects::nonNull)
                    .map(BasedataPatrolPointPreset::getEqpBookId)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.toList());

            List<BasedataEqpBook> allEqpBooks = new ArrayList<>();
            if (!eqpBookIds.isEmpty()) {
                allEqpBooks = basedataEqpbookMapper.selectBasedataEqpBookByEqpBookIds(eqpBookIds);
            }

            Map<Long, BasedataEqpBook> eqpBookMap = allEqpBooks.stream()
                    .filter(Objects::nonNull)
                    .collect(Collectors.toMap(BasedataEqpBook::getEqpBookId, e -> e));

            for (BasedataDevice mainDevice : mainDeviceExistPointList) {
                String mainDeviceName = mainDevice.getDeviceName();
                Long mainDeviceId = mainDevice.getDeviceId();

                List<BasedataPatrolPoint> patrolpointList = patrolPointsByMainDevice.getOrDefault(
                        mainDeviceId, new ArrayList<>());

                if (patrolpointList.isEmpty()) {
                    continue;
                }

                logger.info("---333-------patrolpointList:{}", patrolpointList);

                Map<Long, BasedataDevice> mapDevToPoint = new HashMap<>();

                // 合并处理每个点位及其预置位，避免重复查询与循环
                for (BasedataPatrolPoint patrolpoint : patrolpointList) {
                    Long patrolPointId = patrolpoint.getPatrolPointId();
                    List<BasedataPatrolPointPreset> presets = presetsByPointId.getOrDefault(
                            patrolPointId, new ArrayList<>());

                    if (presets.isEmpty()) {
                        continue;
                    }

                    Long deviceId = patrolpoint.getDeviceId();

                    // 处理非主设备的情况
                    if (deviceId.longValue() != mainDeviceId.longValue() && !mapDevToPoint.containsKey(deviceId)) {
                        this.recursionGetProMainDevice(mainDeviceId, mainDeviceName, deviceId, mainDevVOS, mapDevToPoint);
                    }

                    String pointKey = deviceId + "-" + patrolPointId;
                    // 创建点位节点
                    ProMainDevicePatrolEquTreeSelect pointTreeVO = new ProMainDevicePatrolEquTreeSelect();
                    pointTreeVO.setPatrolpointId(patrolPointId);
                    pointTreeVO.setDataId(pointKey);
                    pointTreeVO.setLabel(patrolpoint.getPatrolPointName());
                    pointTreeVO.setPatrolpointName(patrolpoint.getPatrolPointName());
                    pointTreeVO.setMainDeviceName(mainDeviceName);
                    pointTreeVO.setParentId(String.valueOf(deviceId));
                    pointTreeVO.setPatrolpointFlag("Yes");
                    pointTreeVO.setPositionX(patrolpoint.getPositionX());
                    pointTreeVO.setPositionY(patrolpoint.getPositionY());
                    pointTreeVO.setPositionZ(patrolpoint.getPositionZ());
                    mainDevVOS.add(pointTreeVO);

                    logger.info("---444-------patrolpointPresetS:{}", presets);

                    // 添加预置位节点（去重eqpBookId）
                    Set<Long> addedEqpBookIds = new HashSet<>();
                    for (BasedataPatrolPointPreset preset : presets) {
                        Long eqpBookId = preset.getEqpBookId();
                        if (eqpBookId == null || addedEqpBookIds.contains(eqpBookId)) {
                            continue;
                        }

                        BasedataEqpBook basedataEqpbook = eqpBookMap.get(eqpBookId);
                        if (basedataEqpbook == null) {
                            continue;
                        }

                        ProMainDevicePatrolEquTreeSelect pointPreSetTreeVO = new ProMainDevicePatrolEquTreeSelect();
                        pointPreSetTreeVO.setParentId(pointKey);
                        pointPreSetTreeVO.setEqpbookId(eqpBookId);
                        pointPreSetTreeVO.setPresetCode(preset.getPresetCode());
                        pointPreSetTreeVO.setPatroldeviceName(basedataEqpbook.getPatrolDeviceName());
                        pointPreSetTreeVO.setMainDeviceName(basedataEqpbook.getPatrolDeviceName());
                        pointPreSetTreeVO.setLabel(basedataEqpbook.getPatrolDeviceName());
                        pointPreSetTreeVO.setPatroldeviceCode(basedataEqpbook.getPatrolDeviceCode());
                        pointPreSetTreeVO.setDataId(pointKey + basedataEqpbook.getEqpBookId());
                        pointPreSetTreeVO.setPatroldeviceFlag("Yes");

                        mainDevVOS.add(pointPreSetTreeVO);
                        addedEqpBookIds.add(eqpBookId);
                    }
                }
            }
        }

        logger.info("----------------mainDevVOS:{} ", mainDevVOS);
        return ProMainDevicePatrolEquTreeSelectUtil.buildDeviceTree(mainDevVOS);
    }

    public void recursionGetProMainDevice(Long mainDeviceId, String mainDeviceName, Long deviceId,
                                          List<ProMainDevicePatrolEquTreeSelect> mainDevVOS,
                                          Map<Long, BasedataDevice> mapDevToPoint) {
        if (mapDevToPoint.containsKey(deviceId)) {
            return;
        }

        if (mainDeviceId.longValue() != deviceId.longValue()) {
            BasedataDevice basedataDevice = this.basedataDeviceMapper.selectBasedataDeviceByDeviceId(deviceId);
            if (basedataDevice == null) {
                return;
            }

            ProMainDevicePatrolEquTreeSelect mainDevVO = new ProMainDevicePatrolEquTreeSelect();
            mainDevVO.setDataId(String.valueOf(deviceId));
            mainDevVO.setLabel(basedataDevice.getDeviceName());
            mainDevVO.setParentId(String.valueOf(basedataDevice.getParentId()));
            mainDevVO.setMainDeviceId(mainDeviceId);
            mainDevVO.setMainDeviceName(mainDeviceName);
            mainDevVO.setComponentName(basedataDevice.getDeviceName());
            mainDevVO.setDeviceId(deviceId);
            mainDevVO.setPowerMainEquFlag("No");
            mainDevVO.setComponentFlag("Yes");
            mainDevVO.setPositionX(basedataDevice.getPositionX());
            mainDevVO.setPositionY(basedataDevice.getPositionY());
            mainDevVO.setPositionZ(basedataDevice.getPositionZ());

            mainDevVOS.add(mainDevVO);
            mapDevToPoint.put(deviceId, basedataDevice);

            if (basedataDevice.getParentId() == null ||
                    mainDeviceId.longValue() == basedataDevice.getParentId().longValue()) {
                return;
            }

            this.recursionGetProMainDevice(
                    mainDeviceId,
                    mainDeviceName,
                    basedataDevice.getParentId(),
                    mainDevVOS,
                    mapDevToPoint
            );
        }
    }

    public void recursionGetProMainDeviceOld(Long mainDeviceId, String mainDeviceName, Long deviceId, List<ProMainDevicePatrolEquTreeSelect> mainDevVOS, HashMap<Long, BasedataDevice> mapDevToPoint) {
        if (!mapDevToPoint.containsKey(deviceId)) {
            if (mainDeviceId.longValue() != deviceId.longValue()) {
                BasedataDevice basedataDevice = this.basedataDeviceMapper.selectBasedataDeviceByDeviceId(deviceId);
                if (null != basedataDevice) {
                    ProMainDevicePatrolEquTreeSelect mainDevVO = new ProMainDevicePatrolEquTreeSelect();
                    mainDevVO.setDataId(String.valueOf(deviceId));
                    mainDevVO.setLabel(basedataDevice.getDeviceName());
                    mainDevVO.setParentId(String.valueOf(basedataDevice.getParentId()));
                    mainDevVO.setMainDeviceId(mainDeviceId);
                    mainDevVO.setMainDeviceName(mainDeviceName);
                    mainDevVO.setComponentName(basedataDevice.getDeviceName());
                    mainDevVO.setDeviceId(deviceId);
                    mainDevVO.setPowerMainEquFlag("No");
                    mainDevVO.setComponentFlag("Yes");
                    mainDevVO.setPositionX(basedataDevice.getPositionX());
                    mainDevVO.setPositionY(basedataDevice.getPositionY());
                    mainDevVO.setPositionZ(basedataDevice.getPositionZ());
                    mainDevVOS.add(mainDevVO);
                    mapDevToPoint.put(deviceId, basedataDevice);
                    if (null == basedataDevice.getParentId() || mainDeviceId.longValue() == basedataDevice.getParentId().longValue()) {
                        return;
                    }

                    deviceId = basedataDevice.getParentId();
                    this.recursionGetProMainDeviceOld(mainDeviceId, mainDeviceName, deviceId, mainDevVOS, mapDevToPoint);

                }
            }
        }
    }

    public BasedataDevice insertMainDeviceAndCommByDeviceType(BasedataDevice basedataDevice) {
        basedataDevice.setCreateTime(DateUtils.getNowDate());
        basedataDevice.setPowerMainEquFlag("Yes");
        this.basedataDeviceMapper.insertBasedataDevice(basedataDevice);
        BasedataDeviceType basedataDeviceTypeQuery = new BasedataDeviceType();
        basedataDeviceTypeQuery.setParentId(basedataDevice.getDeviceTypeId());
        logger.info("basedataDevice.getDeviceTypeId(): " + basedataDevice.getDeviceTypeId());
        List<BasedataDeviceType> commTypeList = this.basedataDevicetypeMapper.selectBasedataDeviceTypeList(basedataDeviceTypeQuery);
        if (!commTypeList.isEmpty()) {
            int i = 0;
            Iterator<BasedataDeviceType> iterator = commTypeList.iterator();

            while (true) {
                BasedataDeviceType commType;
                BasedataDevice basedataDeviceComm;
                List commType2List;
                do {
                    do {
                        if (!iterator.hasNext()) {
                            return basedataDevice;
                        }

                        commType = iterator.next();
                        ++i;
                        basedataDeviceComm = new BasedataDevice();
                        basedataDeviceComm.setParentId(basedataDevice.getDeviceId());
                        basedataDeviceComm.setPowerMainEquFlag("No");
                        basedataDeviceComm.setDeviceTypeId(commType.getDeviceTypeId());
                        basedataDeviceComm.setDeviceTypeName(commType.getDeviceTypeName());
                        basedataDeviceComm.setAreaId(basedataDevice.getAreaId());
                        basedataDeviceComm.setAreaName(basedataDevice.getAreaName());
                        basedataDeviceComm.setPhase(commType.getPhase());
                        basedataDeviceComm.setPhaseNum(commType.getPhaseNum());
                        basedataDeviceComm.setDeviceCode(basedataDevice.getDeviceCode() + "_" + i);
                        basedataDeviceComm.setDeviceName(basedataDevice.getDeviceName() + "_" + commType.getDeviceTypeName());
                        BasedataDevice basedata = new BasedataDevice();
                        basedata.setDeviceName(basedataDevice.getDeviceName());
                        this.basedataDeviceMapper.insertBasedataDevice(basedataDeviceComm);
                        Long commType2Id = commType.getDeviceTypeId();
                        BasedataDeviceType basedataDeviceType2 = new BasedataDeviceType();
                        basedataDeviceType2.setParentId(commType2Id);
                        commType2List = this.basedataDevicetypeMapper.selectBasedataDeviceTypeList(basedataDeviceType2);
                    } while (commType2List.isEmpty());
                } while (basedataDeviceComm.getDeviceId() == null);

                int j = 0;

                for (Object object : commType2List) {
                    BasedataDeviceType commType2 = (BasedataDeviceType) object;
                    ++j;
                    BasedataDevice basedataDeviceComm2 = new BasedataDevice();
                    basedataDeviceComm2.setParentId(basedataDeviceComm.getDeviceId());
                    basedataDeviceComm2.setDeviceTypeId(commType2.getDeviceTypeId());
                    basedataDeviceComm2.setDeviceTypeName(commType2.getDeviceTypeName());
                    basedataDeviceComm2.setPowerMainEquFlag("No");
                    basedataDeviceComm2.setAreaId(basedataDevice.getAreaId());
                    basedataDeviceComm2.setAreaName(basedataDevice.getAreaName());
                    basedataDeviceComm2.setDeviceCode(basedataDevice.getDeviceCode() + "_" + i + "_" + j);
                    basedataDeviceComm2.setPhase(commType2.getPhase());
                    basedataDeviceComm2.setPhaseNum(commType2.getPhaseNum());
                    basedataDeviceComm2.setDeviceName(basedataDevice.getDeviceName() + "_" + commType.getDeviceTypeName() + "_" + commType2.getDeviceTypeName());
                    this.basedataDeviceMapper.insertBasedataDevice(basedataDeviceComm2);
                }
            }
        } else {
            return basedataDevice;
        }
    }

    public List<ProDeviceTreeSelectVO> getProDeviceTreeSelect(BasedataDevice basedataDevice) {
        List<ProDeviceTreeSelectVO> mainDevVOS = new ArrayList<>();
        List<BasedataDevice> list = this.basedataDeviceMapper.selectBasedataDeviceList(basedataDevice);
        if (!list.isEmpty()) {
            for (BasedataDevice device : list) {
                ProDeviceTreeSelectVO proDeviceTreeSelect = new ProDeviceTreeSelectVO();
                BeanUtils.copyBeanProp(proDeviceTreeSelect, device);
                mainDevVOS.add(proDeviceTreeSelect);
            }
        }

        return ProDeviceTreeSelectUtil.buildDeviceTree(mainDevVOS);
    }

    public Map<String, Long> getProDeviceAllPatchNameId() {
        BasedataDevice basedataDevice = new BasedataDevice();
        List<BasedataDevice> list = this.basedataDeviceMapper.selectBasedataDeviceList(basedataDevice);
        Map<String, Long> map = new HashMap<>();
        BasedataDevice device;
        StringBuilder builder;
        if (!list.isEmpty()) {
            for (Iterator<BasedataDevice> iterator = list.iterator(); iterator.hasNext(); map.put(builder.toString(), device.getDeviceId())) {
                device = iterator.next();
                builder = new StringBuilder();
                builder.append(device.getDeviceName());
                Long parentId = device.getParentId();
                if (null != parentId) {
                    this.recursionGetNameId(parentId, builder);
                }
            }
        }

        return map;
    }

    public void recursionGetNameId(Long parentId, StringBuilder builder) {
        BasedataDevice basedataDevice = this.basedataDeviceMapper.selectBasedataDeviceByDeviceId(parentId);
        if (null != basedataDevice) {
            builder.insert(0, basedataDevice.getDeviceName() + "/");
            if (null != basedataDevice.getParentId()) {
                this.recursionGetNameId(basedataDevice.getParentId(), builder);
            }
        }

    }

    public List getDeviceAllDeviceCode() {
        return this.basedataDeviceMapper.getDeviceAllDeviceCode();
    }

    public List checkDeviceNameIsExist(String deviceName, String deviceId) {
        return this.basedataDeviceMapper.checkDeviceNameIsExist(deviceName, deviceId);
    }

    public String checkDeviceNameUnique(BasedataDevice basedataDevice) {
        long deviceId = StringUtils.isNull(basedataDevice.getDeviceId()) ? -1L : basedataDevice.getDeviceId();
        BasedataDevice info = this.basedataDeviceMapper.checkDeviceNameUnique(basedataDevice.getDeviceName(), basedataDevice.getDeviceId());
        return StringUtils.isNotNull(info) && info.getDeviceId() != deviceId ? "1" : "0";
    }

    public String checkDeviceCodeUnique(BasedataDevice basedataDevice) {
        long deviceId = StringUtils.isNull(basedataDevice.getDeviceId()) ? -1L : basedataDevice.getDeviceId();
        BasedataDevice info = this.basedataDeviceMapper.checkDeviceCodeUnique(basedataDevice.getDeviceCode(), basedataDevice.getDeviceId());
        return StringUtils.isNotNull(info) && info.getDeviceId() != deviceId ? "1" : "0";
    }
}
