package com.njcn.device.pq.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.njcn.common.pojo.enums.common.ServerEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.device.biz.pojo.vo.TerminalSelectTreeVO;
import com.njcn.device.common.service.GeneralDeviceService;
import com.njcn.device.line.mapper.DeptLineMapper;
import com.njcn.device.line.mapper.LineDetailMapper;
import com.njcn.device.line.mapper.LineMapper;
import com.njcn.device.pq.enums.LineBaseEnum;
import com.njcn.device.pq.mapper.TreeMapper;
import com.njcn.device.pq.pojo.dto.GeneralDeviceDTO;
import com.njcn.device.pq.pojo.param.DeviceInfoParam;
import com.njcn.device.pq.pojo.po.Line;
import com.njcn.device.pq.pojo.po.LineDetail;
import com.njcn.device.pq.pojo.vo.DeptLineTreeVO;
import com.njcn.device.pq.pojo.vo.TerminalTree;
import com.njcn.device.pq.service.TerminalTreeService;
import com.njcn.device.userledger.service.UserLedgerService;
import com.njcn.supervision.pojo.param.user.UserReportParam;
import com.njcn.supervision.pojo.vo.user.UserLedgerVO;
import com.njcn.system.api.AreaFeignClient;
import com.njcn.system.pojo.enums.StatisticsEnum;
import com.njcn.system.pojo.po.Area;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.web.utils.RequestUtil;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * pqs
 * 终端设备树
 *
 * @author cdf
 * @date 2021/7/19
 */
@Service
@RequiredArgsConstructor
public class TerminalTreeServiceImpl implements TerminalTreeService {

    private final LineMapper lineMapper;

    private final DeptFeignClient deptFeignClient;

    private final LineDetailMapper lineDetailMapper;

    private final AreaFeignClient areaFeignClient;

    private final DeptLineMapper deptLineMapper;

    private final GeneralDeviceService generalDeviceService;

    private final TreeMapper treeMapper;

    private final UserLedgerService userLedgerService;

    @Value("${version.used:master}")
    private String versionUsed;
    /**
     * 台账页面终端树
     *
     * @author cdf
     * @date 2022/1/13
     */
    @Override
    public List<TerminalTree> getTerminalTree() {
        List<TerminalTree> allList = lineMapper.getAllList();
        List<TerminalTree> projectList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.PROJECT_LEVEL.getCode())).sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());
        List<TerminalTree> provinceList = lineMapper.getProvinceList(null, 0);
        List<TerminalTree> gdList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.GD_LEVEL.getCode())).sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());
        List<TerminalTree> subList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.SUB_LEVEL.getCode())).sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());
        List<TerminalTree> devList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.DEVICE_LEVEL.getCode())).sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());
        List<TerminalTree> subvList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.SUB_V_LEVEL.getCode())).sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());


        //处理存在用户的台账
        List<TerminalTree> newLineList = lineMapper.getLineAndLineDetail();
        //用户侧测点
        List<TerminalTree> userLineList = newLineList.stream().filter(it -> StrUtil.isNotBlank(it.getObjId())).collect(Collectors.toList());

        //用户侧装置
        List<String> devIds = userLineList.stream().map(it -> it.getPids().split(StrUtil.COMMA)[LineBaseEnum.DEVICE_LEVEL.getCode()]).distinct().collect(Collectors.toList());
        List<TerminalTree> devUserList = devList.stream().filter(it -> devIds.contains(it.getId())).collect(Collectors.toList());

        //用户侧线路
        List<TerminalTree> subvUserList = subvList.stream().filter(it -> devIds.contains(it.getPid())).collect(Collectors.toList());
        List<String> subvUserIds = subvUserList.stream().map(TerminalTree::getId).distinct().collect(Collectors.toList());

        //电网侧测点
        List<TerminalTree> otherLineList = newLineList.stream().filter(it -> StrUtil.isBlank(it.getObjId())).collect(Collectors.toList());
        List<String> devOtherIds = otherLineList.stream().map(it -> it.getPids().split(StrUtil.COMMA)[LineBaseEnum.DEVICE_LEVEL.getCode()]).distinct().collect(Collectors.toList());

        //电网侧装置
        List<TerminalTree> devOtherList = devList.stream().filter(it -> devOtherIds.contains(it.getId())).collect(Collectors.toList());
        List<TerminalTree> noBindDevList = devList.stream().filter(it -> !devOtherIds.contains(it.getId()) && !devIds.contains(it.getId())).collect(Collectors.toList());
        devOtherList.addAll(noBindDevList);
        //电网侧线路
        List<TerminalTree> subvOtherList = subvList.stream().filter(it -> devOtherIds.contains(it.getPid())).collect(Collectors.toList());
        List<String> otherBusBarIds = subvOtherList.stream().map(TerminalTree::getId).distinct().collect(Collectors.toList());
        List<TerminalTree> noBindList = subvList.stream().filter(it -> !subvUserIds.contains(it.getId()) && !otherBusBarIds.contains(it.getId())).collect(Collectors.toList());
        subvOtherList.addAll(noBindList);


        UserReportParam userReportParam = new UserReportParam();
        List<UserLedgerVO> userReportPOList = userLedgerService.selectUserList(userReportParam);
        userReportPOList = userReportPOList.stream().filter(it -> StrUtil.isNotBlank(it.getStationId())).collect(Collectors.toList());
        Map<String, List<UserLedgerVO>> userMap = userReportPOList.stream().collect(Collectors.groupingBy(UserLedgerVO::getStationId));

        subvOtherList.forEach(subv -> subv.setChildren(getChildren(subv, otherLineList)));
        devOtherList.forEach(dev -> dev.setChildren(getChildren(dev, subvOtherList)));

        subList.forEach(sub -> sub.setChildren(specialDealSubChildren(sub, userLineList, devOtherList, subvUserList, devUserList, userMap.get(sub.getId()))));
        //subList.forEach(sub -> sub.setChildren(getChildren(sub, devList)));
        gdList.forEach(gd -> gd.setChildren(getChildren(gd, subList)));
        provinceList.forEach(province -> province.setChildren(getChildren(province, gdList)));
        projectList.forEach(project -> project.setChildren(getChildren(project, provinceList)));


        return projectList;
    }


    private List<TerminalTree> specialDealSubChildren(TerminalTree sub, List<TerminalTree> lineUserList, List<TerminalTree> devOtherList, List<TerminalTree> busBarList, List<TerminalTree> devAllList, List<UserLedgerVO> userReportPOList) {
        List<TerminalTree> list = new ArrayList<>();
        //电网侧
        List<TerminalTree> devTree = devOtherList.stream().filter(it -> it.getPid().equals(sub.getId())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(devTree)) {
            list.addAll(devTree);
        }
        //非电网侧
        if (CollUtil.isNotEmpty(userReportPOList)) {
            Map<String, UserLedgerVO> userLedgerVOMap = userReportPOList.stream().collect(Collectors.toMap(UserLedgerVO::getId, Function.identity()));

            List<TerminalTree> userLineList = lineUserList.stream().filter(it -> it.getPids().split(StrUtil.COMMA)[LineBaseEnum.SUB_LEVEL.getCode()].equals(sub.getId())).collect(Collectors.toList());
            Map<String, List<TerminalTree>> map = userLineList.stream().collect(Collectors.groupingBy(TerminalTree::getObjId));

            map.forEach((objId, lineList) -> {
                List<String> devIds = lineList.stream()
                        .map(it -> it.getPids().split(StrUtil.COMMA)[LineBaseEnum.DEVICE_LEVEL.getCode()])
                        .distinct()
                        .collect(Collectors.toList());
                List<TerminalTree> busList = busBarList.stream()
                        .filter(it -> devIds.contains(it.getPid()))
                        .collect(Collectors.toList());

                List<TerminalTree> temBus = new ArrayList<>();
                busList.forEach(it -> {
                    TerminalTree busCopy = new TerminalTree();
                    busCopy.setName(it.getName());
                    busCopy.setId(it.getId());
                    busCopy.setPid(it.getPid());
                    busCopy.setSort(it.getSort());
                    busCopy.setChildren(getChildren(it, lineList));
                    busCopy.setPowerFlag(1);
                    busCopy.setLevel(LineBaseEnum.SUB_V_LEVEL.getCode());
                    temBus.add(busCopy);
                });
                List<TerminalTree> devUsrList = devAllList.stream()
                        .filter(it -> devIds.contains(it.getId()))
                        .collect(Collectors.toList());

                List<TerminalTree> temDevList = new ArrayList<>();
                devUsrList.forEach(it -> {
                    TerminalTree devCopy = new TerminalTree();
                    devCopy.setName(it.getName());
                    devCopy.setId(it.getId());
                    devCopy.setPid(it.getPid());
                    devCopy.setSort(it.getSort());
                    devCopy.setChildren(getChildren(it, temBus));
                    devCopy.setPowerFlag(1);
                    devCopy.setLevel(LineBaseEnum.DEVICE_LEVEL.getCode());
                    temDevList.add(devCopy);
                });

                UserLedgerVO userReportPO = userLedgerVOMap.get(objId);
                TerminalTree terminalTree = new TerminalTree();
                if (Objects.isNull(userReportPO)) {
                    terminalTree.setName("用户对象缺失");
                    terminalTree.setId(objId);
                    terminalTree.setPid("");
                }else {
                    terminalTree.setName(userReportPO.getProjectName());
                    terminalTree.setId(userReportPO.getId());
                    terminalTree.setPid(userReportPO.getStationId());
                }
                terminalTree.setPowerFlag(1);
                terminalTree.setLevel(LineBaseEnum.USER_LEVEL.getCode());
                terminalTree.setChildren(temDevList);
                terminalTree.setSort(0);
                list.add(terminalTree);
            });

        }
        return list;
    }


    /**
     * 5层树排除设备 母线监测点合并
     *
     * @author cdf
     * @date 2022/1/13
     */
    @Override
    public List<TerminalTree> getTerminalTreeForFive(DeviceInfoParam deviceInfoParam) {
        //deviceInfoParam.setDeptIndex(RequestUtil.getDeptIndex());
        // 获取所有数据
        List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceService.getDeviceInfo(deviceInfoParam, Stream.of(0).collect(Collectors.toList()), Stream.of(1).collect(Collectors.toList()));
        // 判断所有数据集合状态
        if (CollectionUtil.isNotEmpty(generalDeviceDTOList)) {
            // 创建集合
            List<TerminalTree> taiZhang = new ArrayList<>();
            if (StrUtil.isNotBlank(deviceInfoParam.getStatisticalType().getDeptName())) {
                // 遍历集合
                for (GeneralDeviceDTO generalDeviceDTO : generalDeviceDTOList) {
                    // 创建实体类
                    TerminalTree terminalTree = new TerminalTree();
                    terminalTree.setName(generalDeviceDTO.getName());
                    terminalTree.setId(generalDeviceDTO.getIndex());
                    terminalTree.setLevel(0);
                    // 处理子部门
                    deviceInfoParam.setDeptIndex(generalDeviceDTO.getIndex());
                    List<GeneralDeviceDTO> generalDeviceDTOsubList = generalDeviceService.getDeviceInfo(deviceInfoParam, Stream.of(0).collect(Collectors.toList()), Stream.of(1).collect(Collectors.toList()));
                    if (CollectionUtil.isNotEmpty(generalDeviceDTOsubList)) {
                        List<TerminalTree> terminalTreeList = new ArrayList<>();
                        for (int i = 0; i < generalDeviceDTOsubList.size(); i++) {
                            GeneralDeviceDTO deviceDTO = generalDeviceDTOsubList.get(i);
                            TerminalTree terminalSubTree = new TerminalTree();
                            terminalSubTree.setName(deviceDTO.getName());
                            terminalSubTree.setId(deviceDTO.getIndex());
                            terminalSubTree.setPid(generalDeviceDTO.getIndex());
                            terminalSubTree.setLevel(2);
                            terminalSubTree.setSort(i);
                            if(CollectionUtil.isNotEmpty(deviceDTO.getLineIndexes())){
                                // 处理该部门下的检测点显示
                                // 通过监测点索引查询监测点信息
                                List<TerminalTree> lineList = treeMapper.getLineList(deviceDTO.getLineIndexes());
                                terminalSubTree.setChildren(lineList);
                                terminalTreeList.add(terminalSubTree);
                            }
                        }
                        terminalTree.setChildren(terminalTreeList);
                    } else {
                        if(CollectionUtil.isNotEmpty(generalDeviceDTO.getLineIndexes())){
                            // 处理该部门下的检测点显示
                            // 通过监测点索引查询监测点信息
                            List<TerminalTree> lineList = treeMapper.getLineList(generalDeviceDTO.getLineIndexes());
                            terminalTree.setChildren(lineList);
                        }
                    }
                    taiZhang.add(terminalTree);
                }

            } else {
                // 获取用户
                UserReportParam userReportParam = new UserReportParam();
                List<UserLedgerVO> userReportPOList = userLedgerService.selectUserList(userReportParam);
                userReportPOList = userReportPOList.stream().filter(it -> StrUtil.isNotBlank(it.getStationId())).collect(Collectors.toList());
                Map<String, UserLedgerVO> userMap = userReportPOList.stream().collect(Collectors.toMap(UserLedgerVO::getId, Function.identity()));

                // 遍历集合
                for (GeneralDeviceDTO generalDeviceDTO : generalDeviceDTOList) {
                    // 创建实体类
                    TerminalTree terminalTree = new TerminalTree();

                    // 判断监测点索引集合状态
                    if (CollectionUtils.isEmpty(generalDeviceDTO.getLineIndexes())) {
                        continue;
                    }

                    // 通过供电公司索引查询省会
                    List<TerminalTree> proList = treeMapper.getProvinceList(generalDeviceDTO.getGdIndexes());
                    // 通过供电公司索引查询供电公司信息
                    List<TerminalTree> gdList = treeMapper.getGdList(generalDeviceDTO.getGdIndexes());
                    // 通过供电站索引查询供电站信息
                    List<TerminalTree> subList = treeMapper.getSubList(generalDeviceDTO.getSubIndexes());
                    // 通过监测点索引查询监测点信息
                    List<TerminalTree> lineList = treeMapper.getLineList(generalDeviceDTO.getLineIndexes());

                    List<TerminalTree> userLineList = lineList.stream().filter(it -> StrUtil.isNotBlank(it.getObjId())).collect(Collectors.toList());
                    List<TerminalTree> otherLineList = lineList.stream().filter(it -> StrUtil.isBlank(it.getObjId())).collect(Collectors.toList());

                    Map<String, List<TerminalTree>> temMap = new HashMap<>();
                    if (CollUtil.isNotEmpty(userLineList)) {
                        Map<String, List<TerminalTree>> objMap = userLineList.stream().collect(Collectors.groupingBy(TerminalTree::getObjId));
                        List<TerminalTree> temList = new ArrayList<>();
                        objMap.forEach((objId, monitorList) -> {
                            UserLedgerVO userLedgerVO = userMap.get(objId);
                            TerminalTree tree = new TerminalTree();
                            tree.setLevel(LineBaseEnum.USER_LEVEL.getCode());
                            tree.setPid(userLedgerVO.getStationId());
                            tree.setId(userLedgerVO.getId());
                            tree.setChildren(monitorList);
                            int devSize = (int) monitorList.stream().map(x -> {
                                // 获取父id字符串，通过 逗号 分割 成一个数组
                                String[] pid = x.getPids().split(StrUtil.COMMA);
                                return pid[LineBaseEnum.DEVICE_LEVEL.getCode()];
                            }).distinct().count();
                            tree.setName(userLedgerVO.getProjectName());
                            //特殊处理，用户层级下面的装置数量临时存到pids字段。
                            tree.setPids(String.valueOf(devSize));
                            temList.add(tree);
                        });
                        temMap = temList.stream().collect(Collectors.groupingBy(TerminalTree::getPid));
                    }
                    //处理变电站
                    dealChildrenData(subList, otherLineList, temMap, true);

                    //监测点前面加序号,后面不需要删除下面两行就行
                    //Integer[] arr = {1};
                    //subList.forEach(item->item.getChildren().forEach(it->it.setName((arr[0]++ +"_"+it.getName()))));
                    //处理供电公司



                    if (deviceInfoParam.getStatisticalType().getCode().equalsIgnoreCase(StatisticsEnum.POWER_NETWORK.getCode())) {
                        if("liaoning".equals(versionUsed)){
                            terminalTree.setChildren(subList);
                        }else {
                            dealChildrenData(gdList, subList, null, false);
                            terminalTree.setChildren(gdList);
                        }
                    } else {
                        dealChildrenData(gdList, subList, null, false);
                        //还需要额外处理省会
                        dealChildrenData(proList, gdList, null, false);
                        terminalTree.setChildren(proList);
                    }
                    terminalTree.setId(generalDeviceDTO.getIndex());
                    terminalTree.setName(generalDeviceDTO.getName());
                    terminalTree.setLevel(0);
                    taiZhang.add(terminalTree);
                }
            }
            return taiZhang;
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 处理变电站
     *
     * @param targetData
     * @param childrenData
     * @param isLine
     */
    private void dealChildrenData(List<TerminalTree> targetData, List<TerminalTree> childrenData, Map<String, List<TerminalTree>> userLineMap, boolean isLine) {
        // 创建一个map集合，用于封装对象
        Map<String, List<TerminalTree>> groupLine;
        if (isLine) {
            // 通过stream流分组
            groupLine = childrenData.stream().collect(Collectors.groupingBy(terminalTree -> {
                // 获取父id字符串，通过 逗号 分割 成一个数组
                String[] pid = terminalTree.getPids().split(StrUtil.COMMA);
                return pid[LineBaseEnum.SUB_LEVEL.getCode()];
            }));
        } else {
            groupLine = childrenData.stream().collect(Collectors.groupingBy(TerminalTree::getPid));
        }
        //变电站
        targetData.forEach(terminalTree -> {
            List<TerminalTree> terminalTrees = new ArrayList<>();
            if (groupLine.containsKey(terminalTree.getId())) {
                terminalTrees.addAll(groupLine.get(terminalTree.getId()).stream().sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList()));
            }
            if (isLine) {
                //变电站集合
                int size = (int) terminalTrees.stream().map(x -> {
                    // 获取父id字符串，通过 逗号 分割 成一个数组
                    String[] pid = x.getPids().split(StrUtil.COMMA);
                    return pid[LineBaseEnum.DEVICE_LEVEL.getCode()];
                }).distinct().count();

                int devSize = 0;
                if (userLineMap.containsKey(terminalTree.getId())) {
                    List<TerminalTree> userList = userLineMap.get(terminalTree.getId());
                    devSize = (int) userList.stream().mapToDouble(it -> Integer.parseInt(it.getPids())).sum();
                    terminalTrees.addAll(userList);
                }
                int sumDev = size + devSize;
                terminalTree.setName(terminalTree.getName() + "（" + sumDev + "台装置）");
                terminalTree.setChildren(terminalTrees);
            } else {
                terminalTree.setChildren(terminalTrees);
            }
        });
    }


    @Override
    public List<DeptLineTreeVO> getDeptBindDeptLineTree(String deptId, Integer deptType, String id, Integer type) {
        List<DeptLineTreeVO> deptLineTreeVOS = new ArrayList<>();
        /**
         * 非自定义树
         */
        if (deptType.equals(0)) {
            DeptLineTreeVO deptLineTreeVO = new DeptLineTreeVO();
            deptLineTreeVO.setNothingBindTree(getNothingDeptBindDeptLineTree(id, type));
            deptLineTreeVO.setOtherBindTree(getOtherDeptBindDeptLineTree(deptId, id, type));
            deptLineTreeVO.setMyselfBindTree(getMyselfDeptBindDeptLineTree(deptId, id, type));
            deptLineTreeVOS.add(deptLineTreeVO);
        } else {
            /**
             * 自定义树
             */
            DeptLineTreeVO deptLineTreeVO = new DeptLineTreeVO();
            deptLineTreeVO.setNothingBindTree(setNothingBindComDeptTree(id, type));
            deptLineTreeVO.setMyselfBindTree(getMyselfDeptBindDeptLineTree(deptId, id, type));
            deptLineTreeVOS.add(deptLineTreeVO);
        }
        return deptLineTreeVOS;
    }

    /**
     * 等级：0-项目名称；1- 工程名称；2-单位；3-部门；4-终端；5-母线；6-监测点
     * level为终端时
     * 返回的是 2-3-4
     * level为监测点时
     * 返回的是 2-3-(5+6)
     */
    @Override
    public List<TerminalSelectTreeVO> getTerminalSelectTree(Integer level) {
        List<TerminalSelectTreeVO> resultList = new ArrayList<>();
        DeviceInfoParam deviceInfoParam = new DeviceInfoParam();
        deviceInfoParam.setDeptIndex(RequestUtil.getDeptIndex());
        deviceInfoParam.setServerName(ServerEnum.HARMONIC.getName());
        List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceService.getDeviceInfo(deviceInfoParam, Stream.of(0, 1).collect(Collectors.toList()), Stream.of(1).collect(Collectors.toList()));

        for (GeneralDeviceDTO generalDeviceDTO : generalDeviceDTOList) {
            if (CollectionUtil.isEmpty(generalDeviceDTO.getLineIndexes())) {
                continue;
            }
            // 通过供电公司索引查询省会
            List<TerminalSelectTreeVO> children = new ArrayList<>();
            if (level == 6) {
                List<Line> busList = lineMapper.selectList(new LambdaQueryWrapper<Line>().in(Line::getId, generalDeviceDTO.getVoltageIndexes()));
                Map<String, Line> map = busList.stream().collect(Collectors.toMap(Line::getId, Function.identity()));
                List<Line> lineList = lineMapper.selectList(new LambdaQueryWrapper<Line>().in(Line::getId, generalDeviceDTO.getLineIndexes()));
                for (Line line : lineList) {
                    TerminalSelectTreeVO terminalSelectTreeVO = new TerminalSelectTreeVO();
                    terminalSelectTreeVO.setValue(line.getId());
                    terminalSelectTreeVO.setLabel(map.get(line.getPid()).getName() + "_" + line.getName());
                    children.add(terminalSelectTreeVO);
                }
            } else {
                List<Line> substationList = lineMapper.selectList(new LambdaQueryWrapper<Line>().in(Line::getId, generalDeviceDTO.getSubIndexes()));
                List<Line> devList = lineMapper.selectList(new LambdaQueryWrapper<Line>().in(Line::getId, generalDeviceDTO.getDeviceIndexes()));
                for (Line sub : substationList) {
                    TerminalSelectTreeVO terminalSelectTreeVO = new TerminalSelectTreeVO();
                    terminalSelectTreeVO.setValue(sub.getId());
                    terminalSelectTreeVO.setLabel(sub.getName());
                    //根据变电站获取其下面所有的装置
                    List<TerminalSelectTreeVO> devChildren = new ArrayList<>();
                    List<Line> subDev = devList.stream().filter(dev -> dev.getPids().contains(sub.getId())).collect(Collectors.toList());
                    for (Line line : subDev) {
                        TerminalSelectTreeVO terminalSelectTreeLineVO = new TerminalSelectTreeVO();
                        terminalSelectTreeLineVO.setValue(line.getId());
                        terminalSelectTreeLineVO.setLabel(line.getName());
                        devChildren.add(terminalSelectTreeLineVO);
                    }
                    terminalSelectTreeVO.setChildren(devChildren);
                    children.add(terminalSelectTreeVO);
                }
            }
            TerminalSelectTreeVO terminalSelectTreeVO = new TerminalSelectTreeVO();
            terminalSelectTreeVO.setValue(generalDeviceDTO.getIndex());
            terminalSelectTreeVO.setLabel(generalDeviceDTO.getName());
            terminalSelectTreeVO.setChildren(children);
            resultList.add(terminalSelectTreeVO);
        }
        return resultList;
    }

    @Override
    public List<TerminalTree> getJbTerminalTree() {
        /**
         * 1.先根据监测点电网侧电站，查询是否存在变电站信息
         *  1.1 如果存在，则根据根据电网标识(Power_Flag),来进行判断是电网侧还是非电网侧
         *  1.2 不存在，则根据监测点的线路号，进行判断是电网侧还是非电网侧并以当前监测点所对应的变电站为主层级
         * 2.变电站下不存在监测点信息进行筛查出来，然后进行匹配添加
         */
        List<TerminalTree> taiZhang = new ArrayList<>();
        List<TerminalTree> allList = lineMapper.getAllList();
        List<TerminalTree> projectList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.PROJECT_LEVEL.getCode())).sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());
        List<TerminalTree> provinceList = lineMapper.getProvinceList(null, 0);

        List<TerminalTree> collect1 = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.SUB_LEVEL.getCode()) ||
                item.getLevel().equals(LineBaseEnum.DEVICE_LEVEL.getCode()) ||
                item.getLevel().equals(LineBaseEnum.SUB_V_LEVEL.getCode())
        ).sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());


        List<TerminalTree> gdList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.GD_LEVEL.getCode())
//                && item.getName().equals("承德供电公司")
        ).sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());
        List<TerminalTree> subList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.SUB_LEVEL.getCode())
//                && item.getName().equals("110kV兴泉变电站")

        ).sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());
        List<TerminalTree> lineList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.LINE_LEVEL.getCode())).sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());

        //赋值电网侧信息
        List<String> lineIds = lineList.stream().map(TerminalTree::getId).collect(Collectors.toList());
        List<LineDetail> list = lineDetailMapper.selectList(new LambdaQueryWrapper<LineDetail>().in(CollUtil.isNotEmpty(lineIds), LineDetail::getId, lineIds));
        Map<String, LineDetail> powerFlagMap = list.stream().collect(Collectors.toMap(LineDetail::getId, Function.identity()));
        for (TerminalTree x : lineList) {
            if (powerFlagMap.containsKey(x.getId())) {
                x.setPowerFlag(powerFlagMap.get(x.getId()).getPowerFlag());
                x.setPowerSubstationName(powerFlagMap.get(x.getId()).getPowerSubstationName());
                x.setObjName(powerFlagMap.get(x.getId()).getObjName());
            } else {
                x.setPowerFlag(LineBaseEnum.POWER_FLAG.getCode());
            }

        }


        Map<String, List<TerminalTree>> lineObjNameMap = lineList.stream().filter(x -> StrUtil.isNotBlank(x.getPowerSubstationName())).collect(Collectors.groupingBy(TerminalTree::getPowerSubstationName));
        //组织变电站信息
        List<TerminalTree> subInfoList = new ArrayList<>();

        lineObjNameMap.forEach((key, value) -> {
            List<TerminalTree> terminalTrees = Collections.unmodifiableList(collect1);
            //获取变电信息
            List<TerminalTree> collect = subList.stream().filter(x -> x.getName().equals(key.replace("±", ""))).collect(Collectors.toList());
            //电网侧监测点
            List<TerminalTree> powerFlag = value.stream().filter(x -> x.getPowerFlag().equals(LineBaseEnum.POWER_FLAG.getCode())).collect(Collectors.toList());
            if (CollUtil.isEmpty(powerFlag)) {
                //解决变电站下没有监测点显示问题（变电站-》终端-》母线）
                powerFlag.addAll(collect);
            }
            List<TerminalTree> subChildren = new ArrayList<>();
            TerminalTree recursion = getRecursionChildren(powerFlag, terminalTrees);
            if (ObjectUtil.isNotNull(recursion)) {
                subChildren.add(recursion);
            }
            //非电网侧监测点
            List<TerminalTree> powerFlagNot = value.stream().filter(x -> x.getPowerFlag().equals(LineBaseEnum.POWER_FLAG_NOT.getCode())).collect(Collectors.toList());
            List<TerminalTree> notSubChildren = new ArrayList<>();
            if (CollUtil.isNotEmpty(powerFlagNot)) {
                Map<String, List<TerminalTree>> objNameMap = powerFlagNot.stream().collect(Collectors.groupingBy(TerminalTree::getObjName));
                objNameMap.forEach((objNameKey, objNameValue) -> {
                    TerminalTree recursionChildren = getRecursionChildren(objNameValue, terminalTrees);
                    if (ObjectUtil.isNotNull(recursionChildren)) {
                        recursionChildren.setName(objNameKey);
                        notSubChildren.add(recursionChildren);
                    }

                });
            }
            if (CollUtil.isNotEmpty(collect)) {
                List<TerminalTree> valueList = new ArrayList<>();
                TerminalTree sub = new TerminalTree();
                sub.setId(collect.get(0).getId());
                sub.setName(collect.get(0).getName());
                sub.setPid(collect.get(0).getPid());
                sub.setSort(0);
                sub.setChildren(valueList);

                TerminalTree powerTree = new TerminalTree();
                powerTree.setName("电网侧");
                powerTree.setId(collect.get(0).getId());
                powerTree.setChildren(subChildren);
                valueList.add(powerTree);


                TerminalTree notPowerTree = new TerminalTree();
                notPowerTree.setName("非电网侧");
                notPowerTree.setChildren(notSubChildren);
                valueList.add(notPowerTree);
                subInfoList.add(sub);
            } else {
                //电网侧变电站能否找到
                for (TerminalTree child : subChildren) {
                    List<TerminalTree> valueList = new ArrayList<>();
                    List<TerminalTree> exist = subInfoList.stream().filter(x -> x.getId().equals(child.getId())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(exist)) {
                        //电网侧
                        List<TerminalTree> children = new ArrayList<>();
                        children.addAll(exist.get(0).getChildren().get(0).getChildren());
                        children.add(child);
                        exist.get(0).getChildren().get(0).setChildren(children);
                    } else {
                        TerminalTree sub = new TerminalTree();
                        sub.setId(child.getId());
                        sub.setName(child.getName());
                        sub.setPid(child.getPid());
                        sub.setSort(0);
                        TerminalTree powerTree = new TerminalTree();
                        powerTree.setName("电网侧");
                        powerTree.setId(child.getId());
                        powerTree.setChildren(Arrays.asList(child));
                        valueList.add(powerTree);

                        TerminalTree notPowerTree = new TerminalTree();
                        notPowerTree.setName("非电网侧");
                        notPowerTree.setChildren(new ArrayList<>());
                        valueList.add(notPowerTree);

                        sub.setChildren(valueList);
                        subInfoList.add(sub);
                    }
                }
                for (TerminalTree child : notSubChildren) {
                    List<TerminalTree> valueList = new ArrayList<>();
                    List<TerminalTree> exist = subInfoList.stream().filter(x -> x.getId().equals(child.getId())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(exist)) {
                        //非电网侧
                        List<TerminalTree> children = new ArrayList<>();
                        children.addAll(exist.get(0).getChildren().get(1).getChildren());
                        children.add(child);
                        exist.get(0).getChildren().get(1).setChildren(children);
                    } else {
                        TerminalTree sub = new TerminalTree();
                        sub.setId(child.getId());
                        sub.setName(child.getName());
                        sub.setPid(child.getPid());
                        sub.setSort(0);
                        TerminalTree powerTree = new TerminalTree();
                        powerTree.setName("电网侧");
                        powerTree.setId(child.getId());
                        powerTree.setChildren(new ArrayList<>());
                        valueList.add(powerTree);

                        TerminalTree notPowerTree = new TerminalTree();
                        notPowerTree.setName("非电网侧");
                        notPowerTree.setChildren(Arrays.asList(child));
                        valueList.add(notPowerTree);

                        sub.setChildren(valueList);
                        subInfoList.add(sub);
                    }
                }

            }
        });
        //todo 变电站层级处理不存在下面信息的监测点信息(默认信息就是给他当成电网侧)
        List<TerminalTree> dw = new ArrayList<>();
        dw.addAll(subInfoList.stream().collect(Collectors.toList()));
        //暂时解决跨部门不显示电站问题（风光储）
        dw.addAll(subInfoList.stream().flatMap(x -> x.getChildren().get(0).getChildren().stream()).collect(Collectors.toList()));
        dw.addAll(subInfoList.stream().flatMap(x -> x.getChildren().get(1).getChildren().stream()).collect(Collectors.toList()));
        List<TerminalTree> collect = subList.stream().filter(x -> !dw.stream().map(TerminalTree::getId).collect(Collectors.toList()).contains(x.getId()) ||
                        x.getName().equals("220kV金阳变电站"))
                .distinct().collect(Collectors.toList());

        for (TerminalTree notSub : collect) {
            //只显示变电站下有装置的
            TerminalTree notSub1 = findParents(collect1, notSub);
            if (CollUtil.isNotEmpty(notSub1.getChildren())) {
                List<TerminalTree> valueList = new ArrayList<>();

                TerminalTree sub = new TerminalTree();
                sub.setId(notSub.getId());
                sub.setName(notSub.getName());
                sub.setPid(notSub.getPid());
                sub.setSort(0);
                TerminalTree powerTree = new TerminalTree();
                powerTree.setId(notSub.getId());
                powerTree.setName("电网侧");
                powerTree.setChildren(Arrays.asList(notSub1));
                valueList.add(powerTree);

                TerminalTree notPowerTree = new TerminalTree();
                notPowerTree.setName("非电网侧");
                notPowerTree.setChildren(new ArrayList<>());
                valueList.add(notPowerTree);

                sub.setChildren(valueList);
                subInfoList.add(sub);
                dw.add(sub);
            }
        }

        gdList.forEach(gd -> gd.setChildren(getChildren(gd, subInfoList)));
        provinceList.forEach(province -> province.setChildren(getChildren(province, gdList)));
        projectList.forEach(project -> project.setChildren(getChildren(project, provinceList)));

        if (CollectionUtil.isNotEmpty(allList)) {
            TerminalTree terminalTree = new TerminalTree();
            terminalTree.setId("9999999");
            terminalTree.setLevel(0);
            terminalTree.setName("台账管理");
            if (CollectionUtil.isNotEmpty(projectList)) {
                terminalTree.setChildren(projectList);
            }
            taiZhang.add(terminalTree);
        }
        return taiZhang;
    }

    @Override
    public List<TerminalTree> getJbNewTerminalTree() {
        List<TerminalTree> allList = lineMapper.getAllList();
        List<TerminalTree> projectList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.PROJECT_LEVEL.getCode())).sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());
        List<TerminalTree> provinceList = lineMapper.getProvinceList(null, 0);

        List<TerminalTree> gdList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.GD_LEVEL.getCode())).sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());
        List<TerminalTree> subList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.SUB_LEVEL.getCode())).sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());
        List<TerminalTree> devList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.DEVICE_LEVEL.getCode())).sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());
        List<TerminalTree> subvList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.SUB_V_LEVEL.getCode())).sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());

        List<TerminalTree> linepowerList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.LINE_LEVEL.getCode()) && item.getPowerFlag() != 1).sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());
        List<TerminalTree> lineNotPowerList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.LINE_LEVEL.getCode()) && item.getPowerFlag() == 1).sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());


        subvList.forEach(subv -> {
                    if (CollUtil.isEmpty(subv.getChildren())) {
                        subv.setChildren(getRecursionChildren(subv, linepowerList));
                    }
                }
        );

        subvList.forEach(subv -> {
                    if (CollUtil.isEmpty(subv.getChildren())) {
                        subv.setChildren(getRecursionChildren(subv, lineNotPowerList));
                    }
                }
        );
        subvList.stream().filter(x -> ObjUtil.isNull(x.getPowerFlag())).forEach(x -> x.setPowerFlag(0));
        devList.forEach(dev -> dev.setChildren(getRecursionChildren(dev, subvList)));
        devList.stream().filter(x -> ObjUtil.isNull(x.getPowerFlag())).forEach(x -> x.setPowerFlag(0));


        subList.forEach(sub -> sub.setChildren(getRecursionChildrenCs(sub, devList)));
        gdList.forEach(gd -> gd.setChildren(getChildren(gd, subList)));
        provinceList.forEach(province -> province.setChildren(getChildren(province, gdList)));
        projectList.forEach(project -> project.setChildren(getChildren(project, provinceList)));

        return projectList;

    }

    /**
     * 获取全部子节点
     *
     * @author cdf
     * @date 2021/7/19
     */
    public List<TerminalTree> getChildren(TerminalTree item, List<TerminalTree> all) {
        List<TerminalTree> collect = all.stream().filter(allItem -> allItem.getPid().equals(item.getId())).sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            long sortSize = collect.stream().filter(x -> ObjUtil.isNotNull(x.getSort())).filter(x -> x.getSort() == 0).count();
            if (collect.size() - sortSize / collect.size() > 50) {
                collect.sort(Comparator.comparing(x -> x.getName()));
            }
        }
        return collect;
    }

    public List<TerminalTree> getRecursionChildrenCs(TerminalTree item, List<TerminalTree> all) {
        List<TerminalTree> collect = all.stream().filter(allItem -> allItem.getPid().equals(item.getId())).sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());
        List<TerminalTree> list = new ArrayList<>();
        TerminalTree power = new TerminalTree();
        power.setName("电网侧");
        power.setSort(0);
        power.setChildren(collect.stream().filter(x -> 1 != x.getPowerFlag()).collect(Collectors.toList()));
        list.add(power);


        TerminalTree notPower = new TerminalTree();
        notPower.setName("非电网侧");
        notPower.setSort(1);
        notPower.setChildren(collect.stream().filter(x -> 1 == x.getPowerFlag()).collect(Collectors.toList()));
        list.add(notPower);
        return list;
    }

    public List<TerminalTree> getRecursionChildren(TerminalTree item, List<TerminalTree> all) {
        List<TerminalTree> list = all.stream().filter(allItem -> allItem.getPid().equals(item.getId())).sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(list)) {
            item.setPowerFlag(list.get(0).getPowerFlag());
        }
        return list;
    }

    /**
     * 变电站层级增加电网侧和非电网侧电站
     *
     * @param line 变电站对象
     * @param all  检测对象
     * @return
     */
    public TerminalTree getRecursionChildren(List<TerminalTree> line, List<TerminalTree> all) {
        List<TerminalTree> aa = new ArrayList<>();
        for (TerminalTree lineTree : line) {
            findParentsRecursive(lineTree, all, aa);
            aa.add(lineTree);
        }
        List<TerminalTree> distinctList = new ArrayList<>(aa.stream().distinct().collect(Collectors.toList()));
        long count = line.stream().filter(x -> !x.getLevel().equals(LineBaseEnum.LINE_LEVEL.getCode())).count();
        if (count > 0) {
            aa.addAll(all);
        }
        List<TerminalTree> lines = aa.stream().distinct().sorted(Comparator.comparing(TerminalTree::getSort)).collect(Collectors.toList());
        List<TerminalTree> collect = distinctList.stream().filter(x -> x.getLevel() == LineBaseEnum.SUB_LEVEL.getCode()).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            TerminalTree terminalTree = BeanUtil.copyProperties(collect.get(0), TerminalTree.class);
            return findParents(lines, terminalTree);
        }
        return null;
    }

    private static void findParentsRecursive(TerminalTree tree, List<TerminalTree> all, List<TerminalTree> newParents) {
        if (tree.getLevel() == LineBaseEnum.SUB_LEVEL.getCode()) {
            return;
        }
        List<TerminalTree> collect = all.stream().filter(allItem -> allItem.getId().equals(tree.getPid())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            newParents.addAll(collect);
            collect.forEach(treeMap -> {
                findParentsRecursive(treeMap, all, newParents);
            });
        }
    }

    private TerminalTree findParents(List<TerminalTree> all, TerminalTree subTree) {
        List<TerminalTree> collect = all.stream().filter(allItem -> allItem.getPid().equals(subTree.getId())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            collect.forEach(treeMap -> {
                subTree.setChildren(collect);
                findParents(all, treeMap);
            });
        }
        return subTree;
    }

    /**
     * 未绑定监测点树
     *
     * @param id
     * @param type
     * @return
     */
    public List<TerminalTree> getNothingDeptBindDeptLineTree(String id, Integer type) {

        List<TerminalTree> nothingBindTree = new ArrayList<>();
        List<TerminalTree> allList = lineMapper.getAllList();
        HttpResult<Area> area = areaFeignClient.areaPro(id, type);
        Area areaDetail = area.getData();
        String areaId = areaDetail.getId();

        if (CollectionUtil.isNotEmpty(allList)) {
            List<TerminalTree> projectList;
            List<TerminalTree> provinceList;
            if (!"0".equals(areaId)) {
                projectList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.PROJECT_LEVEL.getCode()) && lineMapper.selectProject(areaId).contains(item.getId())).collect(Collectors.toList());
                provinceList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.PROVINCE_LEVEL.getCode()) && item.getName().equals(areaId)).collect(Collectors.toList());
            } else {
                projectList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.PROJECT_LEVEL.getCode())).collect(Collectors.toList());
                provinceList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.PROVINCE_LEVEL.getCode())).collect(Collectors.toList());
            }
            for (TerminalTree terminalTree : provinceList) {
                terminalTree.setName(lineMapper.getProviceName(terminalTree.getName()));
            }
            List<TerminalTree> gdList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.GD_LEVEL.getCode())).collect(Collectors.toList());
            List<TerminalTree> subList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.SUB_LEVEL.getCode())).collect(Collectors.toList());
            List<TerminalTree> devList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.DEVICE_LEVEL.getCode())).collect(Collectors.toList());
            List<TerminalTree> subvList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.SUB_V_LEVEL.getCode())).collect(Collectors.toList());
            List<TerminalTree> lineList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.LINE_LEVEL.getCode())).collect(Collectors.toList());
            List<String> deptLineList = deptLineMapper.getAllBindLine();
            /**
             * 取出未绑定的监测点
             */
            List<TerminalTree> lineNoBindList = new ArrayList<>();
            for (int i = 0; i < lineList.size(); i++) {
                if (!deptLineList.contains(lineList.get(i).getId())) {
                    lineNoBindList.add(lineList.get(i));
                }
            }
            for (TerminalTree sub : subList) {
                List<TerminalTree> lineTemp = new ArrayList<>();
                List<TerminalTree> devTemp = devList.stream().filter(d -> d.getPid().equals(sub.getId())).collect(Collectors.toList());

                for (TerminalTree dev : devTemp) {
                    List<TerminalTree> subvTemp = subvList.stream().filter(d -> d.getPid().equals(dev.getId())).collect(Collectors.toList());

                    for (TerminalTree subv : subvTemp) {
                        List<TerminalTree> lineRes = lineNoBindList.stream().filter(d -> d.getPid().equals(subv.getId())).map(
                                (item) ->
                                {
                                    String name = subv.getName() + "_" + item.getName();
                                    item.setName(name);
                                    item.setPid(sub.getId());
                                    return item;
                                }).collect(Collectors.toList());
                        lineTemp.addAll(lineRes);

                    }
                }
                sub.setChildren(lineTemp);
            }

            gdList.stream().peek(gd -> {
                gd.setChildren(getChildren(gd, subList));
                gd.setLevel(2);
            }).collect(Collectors.toList());
            provinceList.stream().peek(province -> {
                province.setChildren(getChildren(province, gdList));
                province.setLevel(1);
            }).collect(Collectors.toList());
            nothingBindTree = projectList.stream().peek(project -> {
                project.setChildren(getChildren(project, provinceList));
                project.setLevel(0);
            }).collect(Collectors.toList());

        }
        return nothingBindTree;
    }

    /**
     * 未绑定监测点树(自定义)
     *
     * @param id
     * @param type
     * @return
     */
    public List<TerminalTree> setNothingBindComDeptTree(String id, Integer type) {
        List<TerminalTree> nothingBindTree = new ArrayList<>();
        List<TerminalTree> allList = lineMapper.getAllList();
        HttpResult<Area> area = areaFeignClient.areaPro(id, type);
        Area areaDetail = area.getData();
        String areaId = areaDetail.getId();

        if (CollectionUtil.isNotEmpty(allList)) {
            List<TerminalTree> projectList;
            List<TerminalTree> provinceList;
            if (!"0".equals(areaId)) {
                projectList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.PROJECT_LEVEL.getCode()) && lineMapper.selectProject(areaId).contains(item.getId())).collect(Collectors.toList());
                provinceList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.PROVINCE_LEVEL.getCode()) && item.getName().equals(areaId)).collect(Collectors.toList());
            } else {
                projectList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.PROJECT_LEVEL.getCode())).collect(Collectors.toList());
                provinceList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.PROVINCE_LEVEL.getCode())).collect(Collectors.toList());
            }
            for (TerminalTree terminalTree : provinceList) {
                terminalTree.setName(lineMapper.getProviceName(terminalTree.getName()));
            }
            List<TerminalTree> gdList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.GD_LEVEL.getCode())).collect(Collectors.toList());
            List<TerminalTree> subList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.SUB_LEVEL.getCode())).collect(Collectors.toList());
            List<TerminalTree> devList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.DEVICE_LEVEL.getCode())).collect(Collectors.toList());
            List<TerminalTree> subvList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.SUB_V_LEVEL.getCode())).collect(Collectors.toList());
            List<TerminalTree> lineList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.LINE_LEVEL.getCode())).collect(Collectors.toList());
            for (TerminalTree sub : subList) {
                List<TerminalTree> lineTemp = new ArrayList<>();
                List<TerminalTree> devTemp = devList.stream().filter(d -> d.getPid().equals(sub.getId())).collect(Collectors.toList());

                for (TerminalTree dev : devTemp) {
                    List<TerminalTree> subvTemp = subvList.stream().filter(d -> d.getPid().equals(dev.getId())).collect(Collectors.toList());

                    for (TerminalTree subv : subvTemp) {
                        List<TerminalTree> lineRes = lineList.stream().filter(d -> d.getPid().equals(subv.getId())).map(
                                (item) ->
                                {
                                    String name = subv.getName() + "_" + item.getName();
                                    item.setPid(sub.getId());
                                    item.setName(name);
                                    return item;
                                }).collect(Collectors.toList());
                        lineTemp.addAll(lineRes);

                    }
                }
                sub.setChildren(lineTemp);
            }

            gdList.stream().peek(gd -> {
                gd.setChildren(getChildren(gd, subList));
                gd.setLevel(2);
            }).collect(Collectors.toList());
            provinceList.stream().peek(province -> {
                province.setChildren(getChildren(province, gdList));
                province.setLevel(1);
            }).collect(Collectors.toList());
            nothingBindTree = projectList.stream().peek(project -> {
                project.setChildren(getChildren(project, provinceList));
                project.setLevel(0);
            }).collect(Collectors.toList());

        }
        return nothingBindTree;
    }

    /**
     * 其他绑定绑定监测点树
     *
     * @param id
     * @param type
     * @return
     */
    public List<TerminalTree> getOtherDeptBindDeptLineTree(String deptId, String id, Integer type) {
        //其他绑定监测点树
        List<TerminalTree> otherBindTree = new ArrayList<>();
        List<TerminalTree> allList = lineMapper.getAllList();
        HttpResult<Area> area = areaFeignClient.areaPro(id, type);
        Area areaDetail = area.getData();
        String areaId = areaDetail.getId();

        if (CollectionUtil.isNotEmpty(allList)) {
            List<TerminalTree> projectList;
            List<TerminalTree> provinceList;
            if (!"0".equals(areaId)) {
                projectList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.PROJECT_LEVEL.getCode()) && lineMapper.selectProject(areaId).contains(item.getId())).collect(Collectors.toList());
                provinceList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.PROVINCE_LEVEL.getCode()) && item.getName().equals(areaId)).collect(Collectors.toList());
            } else {
                projectList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.PROJECT_LEVEL.getCode())).collect(Collectors.toList());
                provinceList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.PROVINCE_LEVEL.getCode())).collect(Collectors.toList());
            }
            for (TerminalTree terminalTree : provinceList) {
                terminalTree.setName(lineMapper.getProviceName(terminalTree.getName()));
            }
            List<TerminalTree> gdList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.GD_LEVEL.getCode())).collect(Collectors.toList());
            List<TerminalTree> subList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.SUB_LEVEL.getCode())).collect(Collectors.toList());
            List<TerminalTree> devList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.DEVICE_LEVEL.getCode())).collect(Collectors.toList());
            List<TerminalTree> subvList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.SUB_V_LEVEL.getCode())).collect(Collectors.toList());
            List<TerminalTree> lineList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.LINE_LEVEL.getCode())).collect(Collectors.toList());
            List<String> deptLineList = deptLineMapper.getOtherBindLine(deptId);

            List<TerminalTree> lineOther = new ArrayList<>();
            for (int i = 0; i < lineList.size(); i++) {
                if (deptLineList.contains(lineList.get(i).getId())) {
                    lineOther.add(lineList.get(i));
                }
            }
            for (TerminalTree sub : subList) {
                List<TerminalTree> lineTemp = new ArrayList<>();
                List<TerminalTree> devTemp = devList.stream().filter(d -> d.getPid().equals(sub.getId())).collect(Collectors.toList());

                for (TerminalTree dev : devTemp) {
                    List<TerminalTree> subvTemp = subvList.stream().filter(d -> d.getPid().equals(dev.getId())).collect(Collectors.toList());

                    for (TerminalTree subv : subvTemp) {
                        List<TerminalTree> lineRes = lineOther.stream().filter(d -> d.getPid().equals(subv.getId())).map(
                                (item) ->
                                {
                                    String name = subv.getName() + "_" + item.getName();
                                    item.setName(name);
                                    item.setPid(sub.getId());
                                    return item;
                                }).collect(Collectors.toList());
                        lineTemp.addAll(lineRes);

                    }
                }
                sub.setChildren(lineTemp);

            }

            gdList.stream().peek(gd -> {
                gd.setChildren(getChildren(gd, subList));
                gd.setLevel(2);
            }).collect(Collectors.toList());
            provinceList.stream().peek(province -> {
                province.setChildren(getChildren(province, gdList));
                province.setLevel(1);
            }).collect(Collectors.toList());
            otherBindTree = projectList.stream().peek(project -> {
                project.setChildren(getChildren(project, provinceList));
                project.setLevel(0);
            }).collect(Collectors.toList());
        }
        return otherBindTree;
    }

    /**
     * 本身绑定绑定监测点树
     *
     * @param id
     * @param type
     * @return
     */
    public List<TerminalTree> getMyselfDeptBindDeptLineTree(String deptId, String id, Integer type) {
        //本身绑定监测点树
        List<TerminalTree> myselfBindTree = new ArrayList<>();
        List<TerminalTree> allList = lineMapper.getAllList();
        HttpResult<Area> area = areaFeignClient.areaPro(id, type);
        Area areaDetail = area.getData();
        String areaId = areaDetail.getId();

        if (CollectionUtil.isNotEmpty(allList)) {
            List<TerminalTree> projectList;
            List<TerminalTree> provinceList;
            if (!"0".equals(areaId)) {
                projectList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.PROJECT_LEVEL.getCode()) && lineMapper.selectProject(areaId).contains(item.getId())).collect(Collectors.toList());
                provinceList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.PROVINCE_LEVEL.getCode()) && item.getName().equals(areaId)).collect(Collectors.toList());
            } else {
                projectList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.PROJECT_LEVEL.getCode())).collect(Collectors.toList());
                provinceList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.PROVINCE_LEVEL.getCode())).collect(Collectors.toList());
            }
            for (TerminalTree terminalTree : provinceList) {
                terminalTree.setName(lineMapper.getProviceName(terminalTree.getName()));
            }
            List<TerminalTree> gdList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.GD_LEVEL.getCode())).collect(Collectors.toList());
            List<TerminalTree> subList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.SUB_LEVEL.getCode())).collect(Collectors.toList());
            List<TerminalTree> devList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.DEVICE_LEVEL.getCode())).collect(Collectors.toList());
            List<TerminalTree> subvList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.SUB_V_LEVEL.getCode())).collect(Collectors.toList());
            List<TerminalTree> lineList = allList.stream().filter(item -> item.getLevel().equals(LineBaseEnum.LINE_LEVEL.getCode())).collect(Collectors.toList());
            List<String> deptLineList = deptLineMapper.getMyselfBindLine(deptId);

            List<TerminalTree> lineMyself = new ArrayList<>();
            for (int i = 0; i < lineList.size(); i++) {
                if (deptLineList.contains(lineList.get(i).getId())) {
                    lineMyself.add(lineList.get(i));
                }
            }


            for (TerminalTree sub : subList) {
                List<TerminalTree> lineTemp = new ArrayList<>();
                List<TerminalTree> devTemp = devList.stream().filter(d -> d.getPid().equals(sub.getId())).collect(Collectors.toList());

                for (TerminalTree dev : devTemp) {
                    List<TerminalTree> subvTemp = subvList.stream().filter(d -> d.getPid().equals(dev.getId())).collect(Collectors.toList());

                    for (TerminalTree subv : subvTemp) {
                        List<TerminalTree> lineRes = lineMyself.stream().filter(d -> d.getPid().equals(subv.getId())).map(
                                (item) ->
                                {
                                    String name = subv.getName() + "_" + item.getName();
                                    item.setName(name);
                                    item.setPid(sub.getId());
                                    return item;
                                }).collect(Collectors.toList());
                        lineTemp.addAll(lineRes);

                    }
                }
                sub.setChildren(lineTemp);

            }

            gdList.stream().peek(gd -> {
                gd.setChildren(getChildren(gd, subList));
                gd.setLevel(2);
            }).collect(Collectors.toList());
            provinceList.stream().peek(province -> {
                province.setChildren(getChildren(province, gdList));
                province.setLevel(1);
            }).collect(Collectors.toList());
            myselfBindTree = projectList.stream().peek(project -> {
                project.setChildren(getChildren(project, provinceList));
                project.setLevel(0);
            }).collect(Collectors.toList());
        }
        return myselfBindTree;
    }


}
