package com.bocloud.ims.service.topology;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.utils.ListTool;
import com.bocloud.ims.entity.resource.Alarm;
import com.bocloud.ims.entity.topology.*;
import com.bocloud.ims.interfaces.topology.InstanceRelationService;
import com.bocloud.ims.repository.topology.*;
import com.bocloud.ims.service.internal.CspAlarmService;
import com.bocloud.ims.service.utils.Operation;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

import static java.util.stream.Collectors.groupingBy;

/**
 * InstanceRelation Service层
 *
 * @author lyy
 * @Version 1.0
 * @since 2017年9月15日
 */
@Service("instanceRelationService")
public class InstanceRelationServiceImpl implements InstanceRelationService {
    private static final Logger logger = LoggerFactory.getLogger(InstanceRelationServiceImpl.class);
    @Autowired
    private InstanceRelationRepository instanceRelationRepository;
    @Autowired
    private InstanceRepository instanceRepository;
    @Autowired
    private ModuleRelationRepository moduleRelationRepository;
    @Autowired
    private ModuleRepository moduleRepository;
    @Autowired
    private RelationRepository relationRepository;
    @Autowired
    private CiIconRepository iconRepository;
    @Autowired
    private RelationCategoryRepository relationCategoryRepository;
    @Autowired
    private InstanceValueRepository instanceValueRepository;
    @Autowired
    private PropertyRepository propertyRepository;
    @Autowired
    private InstanceLocationRepository instanceLocationRepository;
    @Autowired
    private CspAlarmService cspAlarmService;

    @Override
    public BocloudResult list(Long id, Long userId, Long categoryId) {
        List<ModuleRelation> moduleRelationList = null;
        try {
            // 通过实例id获取到关联到的模型关系
            Instance instance = instanceRepository.query(id);
            moduleRelationList = moduleRelationRepository.queryByModuleIdEnable(instance.getModuleId(), categoryId);
            // 拼接模型关系的结果集
            for (ModuleRelation moduleRelation : moduleRelationList) {
                moduleRelation.setSourceName(moduleRepository.query(moduleRelation.getSourceId()).getName());
                moduleRelation.setTargetName(moduleRepository.query(moduleRelation.getTargetId()).getName());
                moduleRelation.setRelationName(relationRepository.query(moduleRelation.getRelationId()).getName());
                List<InstanceRelation> instanceRelations = instanceRelationRepository.queryByInstanceIdAndModuleRelationId(id,
                        moduleRelation.getId());
                List<Instance> intanceList = Lists.newArrayList();
                if (!ListTool.isEmpty(instanceRelations)) {
                    for (InstanceRelation instanceRelation : instanceRelations) {
                        if (id.equals(instanceRelation.getTargetId())) {
                            Instance instanceNode = instanceRepository.query(instanceRelation.getSourceId());
                            InstanceValue instanceValue = instanceValueRepository.queryTitleByInstanceId(instanceNode.getId());
                            if (instanceValue != null && !"".equals(instanceValue.getPropertyValue())) {
                                instanceNode.setBname(instanceValue.getPropertyValue());
                            }
                            intanceList.add(instanceNode);
                        } else {
                            Instance instanceNode = instanceRepository.query(instanceRelation.getTargetId());
                            InstanceValue instanceValue = instanceValueRepository.queryTitleByInstanceId(instanceNode.getId());
                            if (instanceValue != null && !"".equals(instanceValue.getPropertyValue())) {
                                instanceNode.setBname(instanceValue.getPropertyValue());
                            }
                            intanceList.add(instanceNode);
                        }
                    }
                }
                moduleRelation.setInstances(intanceList);
            }
        } catch (Exception e) {
            logger.error("query instanceRelation error:", e);
            return new BocloudResult(false, "查询失败");
        }
        return new BocloudResult(true, moduleRelationList, "查询成功");
    }

    @Override
    public BocloudResult create(Long id, List<Map<String, Long>> links, Long userId, Long categoryId) {
        try {
            // 前端传入的数据
            List<InstanceRelation> newInstanceRelationList = Lists.newArrayList();
            List<InstanceRelation> oldInstanceRelationList = null;
            if (categoryId != null) {
                // 数据库已存在的数据
                oldInstanceRelationList = instanceRelationRepository.queryByInstanceIdAndCategoryId(id, categoryId);
            } else {
                oldInstanceRelationList = instanceRelationRepository.queryByInstanceId(id);
            }
            Instance instance = instanceRepository.query(id);
            if (instance == null) {
                return new BocloudResult(false, "数据不存在，配置失败");
            }
            for (Map<String, Long> map : links) {
                // 获取前端传入的模型关系id
                Long relationId = Long.parseLong(((Object) map.get("relationId")).toString());
                // 获取前端传入的实例节点id
                Long nodeId = Long.parseLong(((Object) map.get("nodeId")).toString());
                ModuleRelation moduleRelation = moduleRelationRepository.queryById(relationId);
                Instance nodeInstance = instanceRepository.query(nodeId);
                InstanceRelation instanceRelation = null;
                // 判断实例节点的方向
                if (moduleRelation.isSource(nodeInstance.getModuleId())) {
                    // 通过前端传入的实例id去查询数据,获取到实例关系id，获取不到关系id设置为null
                    instanceRelation = instanceRelationRepository.queryBySourceIdAndTargetId(nodeId, id,
                            moduleRelation.getId());
                    if (null == instanceRelation) {
                        BocloudResult result = validate(moduleRelation, instance, nodeInstance);
                        if (result.isFailed()) {
                            return result;
                        }
                        // 重组实例关系
                        instanceRelation = new InstanceRelation(nodeId, moduleRelation.getRelationId(), id,
                                nodeInstance.getModuleId(), instance.getModuleId(), moduleRelation.getId(), new Date(),
                                userId, false, moduleRelation.getCategoryId(), true);
                    }
                } else {
                    instanceRelation = instanceRelationRepository.queryBySourceIdAndTargetId(id, nodeId,
                            moduleRelation.getId());
                    if (null == instanceRelation) {
                        BocloudResult result = validate(moduleRelation, instance, nodeInstance);
                        if (result.isFailed()) {
                            return result;
                        }
                        // 重组实例关系
                        instanceRelation = new InstanceRelation(id, moduleRelation.getRelationId(), nodeId,
                                instance.getModuleId(), nodeInstance.getModuleId(), moduleRelation.getId(), new Date(),
                                userId, false, moduleRelation.getCategoryId(), true);
                    }
                }
                newInstanceRelationList.add(instanceRelation);
            }
            // 处理已存在的数据
            HashMap<Long, InstanceRelation> oldInstanceRelationMap = Maps.newHashMap();
            for (InstanceRelation instanceRelation : oldInstanceRelationList) {
                oldInstanceRelationMap.put(instanceRelation.getId(), instanceRelation);
            }
            // 前端传入的实例关系若没有id则直接走新增，若有id则跳过
            for (InstanceRelation instanceRelation : newInstanceRelationList) {
                if (null == instanceRelation.getId()) {
                    instanceRelationRepository.save(instanceRelation);
                } else {
                    oldInstanceRelationMap.remove(instanceRelation.getId());
                }
            }
            // 迭代删除未发生变化的实例关系
            for (Long key : oldInstanceRelationMap.keySet()) {
                instanceRelationRepository.delete(key);
            }
        } catch (Exception e) {
            logger.error("create instanceRelation error:", e);
            return new BocloudResult(false, "创建失败");
        }
        return new BocloudResult(true, "创建成功");
    }

    @Override
    public BocloudResult validate(ModuleRelation moduleRelation, Instance master, Instance target) throws Exception {
        // 判断实例节点的方向
        if (moduleRelation.isSource(target.getModuleId())) {
            if (moduleRelation.getTargetType().equals("1")) {
                List<InstanceRelation> list = instanceRelationRepository.queryByInstanceIdAndModuleRelationId(target.getId(),
                        moduleRelation.getId());
                for (InstanceRelation instanceRelationTemp : list) {
                    // 非手动的后面会有删掉的操作，所以不会出问题
                    if (instanceRelationTemp.getTargetId().equals(master.getId())
                            && instanceRelationTemp.getManual() == true) {
                        Instance instanceS = instanceRepository.query(instanceRelationTemp.getSourceId());
                        Instance instanceT = instanceRepository.query(instanceRelationTemp.getTargetId());
                        String masterName = master.getBname();
                        InstanceValue instanceValueS = instanceValueRepository.queryTitleByInstanceId(instanceS.getId());
                        if (instanceValueS != null) {
                            instanceS.setBname(instanceValueS.getPropertyValue());
                        }
                        InstanceValue instanceValueT = instanceValueRepository.queryTitleByInstanceId(instanceT.getId());
                        if (instanceValueT != null) {
                            instanceT.setBname(instanceValueT.getPropertyValue());
                        }
                        InstanceValue instanceValueOne = instanceValueRepository.queryTitleByInstanceId(master.getId());
                        if (instanceValueOne != null) {
                            masterName = instanceValueOne.getPropertyValue();
                        }
                        return new BocloudResult(false, "配置[" + instanceS.getBname() + "]已与配置[" + instanceT.getBname()
                                + "]关联，不能再与当前实例[" + masterName + "]关联.");
                    }
                }
            }
            if (moduleRelation.getSourceType().equals("1")) {
                List<InstanceRelation> list = instanceRelationRepository.queryByInstanceIdAndModuleRelationId(master.getId(),
                        moduleRelation.getId());
                for (InstanceRelation instanceRelationTemp : list) {
                    // 手动维护的 同步不进行修改，这里校验失败
                    if (instanceRelationTemp.getSourceId().equals(target.getId())
                            && instanceRelationTemp.getManual() == true) {
                        Instance instanceS = instanceRepository.query(instanceRelationTemp.getTargetId());
                        Instance instanceT = instanceRepository.query(instanceRelationTemp.getSourceId());
                        String twoName = target.getBname();
                        InstanceValue instanceValueS = instanceValueRepository.queryTitleByInstanceId(instanceS.getId());
                        if (instanceValueS != null) {
                            instanceS.setBname(instanceValueS.getPropertyValue());
                        }
                        InstanceValue instanceValueT = instanceValueRepository.queryTitleByInstanceId(instanceT.getId());
                        if (instanceValueT != null) {
                            instanceT.setBname(instanceValueT.getPropertyValue());
                        }
                        InstanceValue instanceValueOne = instanceValueRepository.queryTitleByInstanceId(target.getId());
                        if (instanceValueOne != null) {
                            twoName = instanceValueOne.getPropertyValue();
                        }
                        return new BocloudResult(false, "配置[" + instanceS.getBname() + "]已与配置[" + instanceT.getBname()
                                + "]关联，不能再与实例[" + twoName + "]关联.");
                    }
                }
            }
        } else {
            if (moduleRelation.getSourceType().equals("1")) {
                List<InstanceRelation> list = instanceRelationRepository.queryByInstanceIdAndModuleRelationId(target.getId(),
                        moduleRelation.getId());
                for (InstanceRelation instanceRelationTemp : list) {
                    if (instanceRelationTemp.getSourceId().equals(master.getId())
                            && instanceRelationTemp.getManual() == true) {
                        Instance instanceS = instanceRepository.query(instanceRelationTemp.getTargetId());
                        Instance instanceT = instanceRepository.query(instanceRelationTemp.getSourceId());
                        String masterName = master.getBname();
                        InstanceValue instanceValueS = instanceValueRepository.queryTitleByInstanceId(instanceS.getId());
                        if (instanceValueS != null) {
                            instanceS.setBname(instanceValueS.getPropertyValue());
                        }
                        InstanceValue instanceValueT = instanceValueRepository.queryTitleByInstanceId(instanceT.getId());
                        if (instanceValueT != null) {
                            instanceT.setBname(instanceValueT.getPropertyValue());
                        }
                        InstanceValue instanceValueOne = instanceValueRepository.queryTitleByInstanceId(master.getId());
                        if (instanceValueOne != null) {
                            masterName = instanceValueOne.getPropertyValue();
                        }
                        return new BocloudResult(false, "配置[" + instanceS.getBname() + "]已与配置[" + instanceT.getBname()
                                + "]关联，不能再与当前实例[" + masterName + "]关联.");
                    }
                }
            }
            if (moduleRelation.getTargetType().equals("1")) {
                List<InstanceRelation> list = instanceRelationRepository.queryByInstanceIdAndModuleRelationId(target.getId(),
                        moduleRelation.getId());
                for (InstanceRelation instanceRelationTemp : list) {
                    if (instanceRelationTemp.getSourceId().equals(master.getId())
                            && instanceRelationTemp.getManual() == true) {
                        Instance instanceS = instanceRepository.query(instanceRelationTemp.getTargetId());
                        Instance instanceT = instanceRepository.query(instanceRelationTemp.getSourceId());
                        String OneName = master.getBname();
                        InstanceValue instanceValueS = instanceValueRepository.queryTitleByInstanceId(instanceS.getId());
                        if (instanceValueS != null) {
                            instanceS.setBname(instanceValueS.getPropertyValue());
                        }
                        InstanceValue instanceValueT = instanceValueRepository.queryTitleByInstanceId(instanceT.getId());
                        if (instanceValueT != null) {
                            instanceT.setBname(instanceValueT.getPropertyValue());
                        }
                        InstanceValue instanceValueOne = instanceValueRepository.queryTitleByInstanceId(master.getId());
                        if (instanceValueOne != null) {
                            OneName = instanceValueOne.getPropertyValue();
                        }
                        return new BocloudResult(false, "配置[" + instanceS.getBname() + "]已与配置[" + instanceT.getBname()
                                + "]关联，不能再与当前实例[" + OneName + "]关联.");
                    }
                }
            }
        }
        return new BocloudResult(true, "校验没问题");
    }

    @Override
    public BocloudResult topology(Long nodeId, String uuid, Long categoryId, Long managerId, Boolean oneLevel, String x, String y, Boolean isGenerate) {
        try {
            if (null == nodeId) {
                Instance instance = instanceRepository.queryByUuid(uuid);
                if (instance == null) {
                    return new BocloudResult(false, "数据不存在");
                }
                nodeId = instance.getId();
            }
            return topology(nodeId, categoryId, managerId, oneLevel, x, y, isGenerate);
        } catch (Exception e) {
            logger.error("查询错误");
        }
        return new BocloudResult(false, "查询错误");
    }

    @Override
    public BocloudResult tree(Long id, Long categoryId, Long managerId) {
        try {
            // 初始化缓存start
            Map<Long, Instance> instanceCache = instanceRepository.queryAll();
            Map<Long, InstanceValue> instanceValueCache = instanceValueRepository.queryTitle4InstanceAll();
            Map<Long, Module> moduleCache = moduleRepository.queryAll4Cache();
            Map<String, List<InstanceRelation>> instanceRelationCache = instanceRelationRepository.queryAll4Cache();
            Map<Long, CiIcon> iconCache = Maps.newHashMap();
            // 初始化缓存end
            //获取当前实例信息
            Instance instance = instanceCache.get(id);
            if (instance == null) {
                return new BocloudResult(false, "查询失败，数据不存在");
            }
            CiIcon icon = iconCache.get(instance.getModuleId());
            if (null == icon) {
                try {
                    icon = iconRepository.queryByModuleId(instance.getModuleId());
                } catch (Exception e) {
                    logger.error("查询图标错误");
                }
            }
            if (icon != null) {
                iconCache.put(icon.getId(), icon);
                instance.setIconId(icon.getId());
            }
            Module module = moduleRepository.query(instance.getModuleId());
            // 根据实例id查询实例的内容（当前实例为title）
            InstanceValue instanceValue = instanceValueRepository.queryTitleByInstanceId(instance.getId());
            if (instanceValue != null) {
                instance.setBname(instanceValue.getPropertyValue());
            }
            // 生成拓扑关系
            //自身节点关键信息
            Map<String, Object> selfMap = Maps.newHashMap();
            selfMap.put("id", instance.getId());
            selfMap.put("bname", instance.getBname());
            selfMap.put("uuid", instance.getUuid());
            selfMap.put("moduleId", instance.getModuleId());
            if (icon != null) {
                selfMap.put("iconId", icon.getId());
            }
//            List<String> alarmGuids = Lists.newArrayList();
//            alarmGuids.add(instance.getUuid());
//            Map<String, List<Alarm>> alarmMap = cspAlarmService.topologyAlarm(alarmGuids);
//            // 获取自身告警
//            if (module.getSyncAlarm()) {
//                List<Alarm> alarms = alarmMap.get(instance.getUuid());
//                if (alarms != null && !alarms.isEmpty()) {
//                    instance.setHaveAlarm(true);
//                    selfMap.put("haveAlarm", true);
//                } else {
//                    instance.setHaveAlarm(false);
//                    selfMap.put("haveAlarm", false);
//                }
//            } else {
//                instance.setHaveAlarm(false);
//            }
            //获取拓扑图的根节点
            Long rootNode = rootNode(id, 1, categoryId, moduleCache, iconCache, instanceCache, instanceValueCache,
                    instanceRelationCache);
            if (null != rootNode) {
                // 查出与当前节点有关系的数据
                List<InstanceRelation> instanceRelationList = instanceRelationCache.get(rootNode + "$$" + categoryId);
                if (instanceRelationList == null) {
                    instanceRelationList = instanceRelationRepository.queryByInstanceIdAndCategoryId(id, categoryId);
                }
                if (!ListTool.isEmpty(instanceRelationList)) {
                    List<Map<String, Object>> children = Lists.newArrayList();
                    List<Map<String, Object>> maps = buildRelation(instanceRelationList, children, rootNode, 1, categoryId, moduleCache, iconCache, instanceCache, instanceValueCache,
                            instanceRelationCache);
                    selfMap.put("children", maps);
                }
            }
            return new BocloudResult(true, selfMap, "查询成功");
        } catch (Exception e) {
            logger.error("query instanceRelation error:", e);
            return new BocloudResult(false, "查询失败");
        }
    }

    private Long rootNode(Long id, int hierarchy, Long categoryId, Map<Long, Module> moduleCache, Map<Long, CiIcon> iconCache, Map<Long, Instance> instanceCache, Map<Long, InstanceValue> instanceValueCache, Map<String, List<InstanceRelation>> instanceRelationCache) {
        try {
            // 查出与当前节点有关系的数据
            List<InstanceRelation> instanceRelationList = instanceRelationCache.get(id + "$$" + categoryId);
            if (instanceRelationList == null) {
                instanceRelationList = instanceRelationRepository.queryByInstanceIdAndCategoryId(id, categoryId);
            }
            if (ListTool.isEmpty(instanceRelationList)) {
                return null;
            }
            for (InstanceRelation instanceRelation : instanceRelationList) {
                //向上查找节点
                Long instanceId;
                if (instanceRelation.getTargetId().equals(id)) {
                    instanceId = instanceRelation.getSourceId();
                } else {
                    continue;
                }
                if (hierarchy == 4) {
                    return instanceId;
                } else {
                    // 继续钻取关系
                    rootNode(instanceId, hierarchy + 1, categoryId, moduleCache, iconCache,
                            instanceCache, instanceValueCache, instanceRelationCache);
                }
            }
            return id;
        } catch (Exception e) {
            logger.error("query instanceRelation error:", e);
            return null;
        }
    }

    private List<Map<String, Object>> buildRelation(List<InstanceRelation> instanceRelationList, List<Map<String, Object>> children, Long id, int i, Long categoryId, Map<Long, Module> moduleCache,
                                                    Map<Long, CiIcon> iconCache, Map<Long, Instance> instanceCache, Map<Long, InstanceValue> instanceValueCache,
                                                    Map<String, List<InstanceRelation>> instanceRelationCache) {
        try {
            for (InstanceRelation instanceRelation : instanceRelationList) {
                Long instanceId;
                // 判断哪个节点是与当前节点发生关系的节点
                if (instanceRelation.getSourceId().equals(id)) {
                    instanceId = instanceRelation.getTargetId();
                } else {
                    continue;
                }
                Map<Long, Map<String, Object>> nodes = Maps.newHashMap();
                Map<String, Object> nodeMap = null;
                if (!nodes.containsKey(instanceId)) {
                    // 查出节点，放到nodes里
                    Instance node = instanceCache.get(instanceId);
                    if (node == null) {
                        node = instanceRepository.query(instanceId);
                        instanceCache.put(instanceId, node);
                    }
                    if (node == null) {
                        continue;
                    }
                    Module module = moduleCache.get(node.getModuleId());
                    if (null == module) {
                        try {
                            module = moduleRepository.query(node.getModuleId());
                        } catch (Exception e) {
                            continue;
                        }
                        moduleCache.put(node.getModuleId(), module);
                    }
                    if (null == module) {
                        continue;
                    }
                    CiIcon icon = iconCache.get(module.getIconId());
                    if (null == icon) {
                        try {
                            icon = iconRepository.queryByModuleId(node.getModuleId());
                        } catch (Exception e) {
                            continue;
                        }
                        iconCache.put(module.getIconId(), icon);
                    }
                    nodeMap = Maps.newHashMap();
                    nodeMap.put("id", node.getId());
                    nodeMap.put("bname", node.getBname());
                    nodeMap.put("uuid", node.getUuid());
                    nodeMap.put("moduleId", module.getId());
                    if (icon != null) {
                        nodeMap.put("iconId", icon.getId());
                    } else {
                        continue;
                    }
                    /**
                     * 有标题属性的话 用标题属性
                     */
                    InstanceValue instanceValue = instanceValueCache.get(node.getId());
                    if (instanceValue != null) {
                        nodeMap.put("bname", instanceValue.getPropertyValue());
                    }
                    // 只钻5层（从当前根节点算起）
                    if (i == 4) {
                        // 统计与当前关系节点下节点的所有关系数量
                        int count = instanceRelationRepository.countQueryByInstanceIdAndCategoryId(instanceId, categoryId);
                        if (count > 1) {
                            // 下一层有几个孩子，除去根节点以外的关系数（otherRelationNum作为前端控制节点是否可以继续往下钻取的标识）
                            nodeMap.put("otherRelationNum", count - 1);
                        }
                    } else {
                        // 继续钻取关系
                        // 查出与当前节点有关系的数据
                        List<InstanceRelation> instanceRelations = instanceRelationCache.get(instanceId + "$$" + categoryId);
                        if (instanceRelationList == null) {
                            instanceRelationList = instanceRelationRepository.queryByInstanceIdAndCategoryId(instanceId, categoryId);
                        }
                        if (!ListTool.isEmpty(instanceRelationList)) {
                            List<Map<String, Object>> childrenData = Lists.newArrayList();
                            List<Map<String, Object>> maps = buildRelation(instanceRelations, childrenData, instanceId, i + 1, categoryId, moduleCache, iconCache,
                                    instanceCache, instanceValueCache, instanceRelationCache);
                            nodeMap.put("children", maps);
                        }
                    }
                    children.add(nodeMap);
                }
            }
            return children;
        } catch (Exception e) {
            logger.error("create instanceRelation error:", e);
            return null;
        }
    }

    @Override
    public BocloudResult topology(Long id, Long categoryId, Long managerId, Boolean oneLevel, String x, String y, Boolean isGenerate) {
        try {
            // 初始化缓存start
            Map<Long, Instance> instanceCache = instanceRepository.queryAll();
            Map<Long, InstanceValue> instanceValueCache = instanceValueRepository.queryTitle4InstanceAll();
            Map<Long, Module> moduleCache = moduleRepository.queryAll4Cache();
            Map<String, List<InstanceRelation>> instanceRelationCache = instanceRelationRepository.queryAll4Cache();
            Map<Long, CiIcon> iconCache = Maps.newHashMap();
            // 初始化缓存end
            Instance instance = instanceCache.get(id);
            if (instance == null) {
                return new BocloudResult(false, "查询失败，数据不存在");
            }
            Map<Long, Map<String, Object>> nodes = Maps.newHashMap();
            Map<String, Map<String, Object>> links = Maps.newHashMap();

            CiIcon icon = iconCache.get(instance.getModuleId());
            if (null == icon) {
                try {
                    icon = iconRepository.queryByModuleId(instance.getModuleId());
                } catch (Exception e) {
                    logger.error("查询图标错误");
                }
                iconCache.put(icon.getId(), icon);
            }
            if (icon != null) {
                instance.setIconId(icon.getId());
            }
            Module module = moduleRepository.query(instance.getModuleId());
            // 根据实例id查询实例的内容（当前实例为title）
            InstanceValue instanceValue = instanceValueRepository.queryTitleByInstanceId(instance.getId());
            if (instanceValue != null) {
                instance.setBname(instanceValue.getPropertyValue());
            }

            // 生成拓扑关系
            if (oneLevel) {
                buildOneLevelRelation(nodes, links, id, categoryId, moduleCache, iconCache, instanceCache, instanceValueCache,
                        instanceRelationCache, x, y, isGenerate, managerId);
            } else {
                buildRelation(nodes, links, id, 1, categoryId, moduleCache, iconCache, instanceCache, instanceValueCache,
                        instanceRelationCache);
            }
            List<String> alarmGuids = Lists.newArrayList();
            // 同步告警
            if (!nodes.isEmpty()) {
                Collection<Map<String, Object>> values = nodes.values();
                for (Map<String, Object> map : values) {
                    Module module2 = moduleCache.get(map.get("moduleId"));
                    // 同步告警
                    if (module2.getSyncAlarm()) {
                        alarmGuids.add(map.get("uuid").toString());
                    }
                }
            }
            Map<String, List<Alarm>> alarmMap = Maps.newHashMap();
            if (!alarmGuids.isEmpty()) {
                // 查询所有关系节点的警告
                alarmMap = cspAlarmService.topologyAlarm(alarmGuids);

            }
            //查询拓扑坐标
            List<InstanceLocation> instanceLocations = instanceLocationRepository.query(id, categoryId, managerId);
            HashMap<Long, InstanceLocation> nodesLocation = Maps.newHashMap();
            for (InstanceLocation instanceLocation : instanceLocations) {
                nodesLocation.put(instanceLocation.getNodeId(), instanceLocation);
            }
            Boolean layout = false;
            if (!instanceLocations.isEmpty()) {
                layout = true;
            }
            Map<String, Object> result = Maps.newHashMap();
            result.put("id", instance.getId());
            result.put("bname", instance.getBname());
            result.put("layout", layout);
            Map<String, Object> selfMap = Maps.newHashMap();
            if (!oneLevel) {
                //自身节点关键信息
                selfMap.put("id", instance.getId());
                selfMap.put("bname", instance.getBname());
                selfMap.put("uuid", instance.getUuid());
                selfMap.put("moduleId", instance.getModuleId());
                selfMap.put("iconId", icon.getId());
                if (layout) {
                    selfMap.put("x", nodesLocation.get(instance.getId()).getX());
                    selfMap.put("y", nodesLocation.get(instance.getId()).getY());
                }
                //判断当前节点下是否存在下级节点
                List<InstanceRelation> nodeRelations = instanceRelationCache.get(instance.getId() + "$$" + categoryId);
                if (nodeRelations == null) {
                    nodeRelations = instanceRelationRepository.queryByInstanceIdAndCategoryId(instance.getId(), categoryId);
                }
                Boolean leafNode = true;
                for (InstanceRelation nodeRelation : nodeRelations) {
                    if (instance.getId().equals(nodeRelation.getSourceId())) {
                        leafNode = false;
                    }
                }
                selfMap.put("leafNode", leafNode);
            }
            // 获取自身告警
            if (!oneLevel) {
                if (module.getSyncAlarm()) {
                    List<Alarm> alarms = alarmMap.get(instance.getUuid());
                    if (alarms != null && !alarms.isEmpty()) {
                        instance.setHaveAlarm(true);
                        selfMap.put("haveAlarm", true);
                        selfMap.put("alarmLevel", Operation.grade(alarms.get(0).getLevel()));
                    } else {
                        instance.setHaveAlarm(false);
                        selfMap.put("haveAlarm", false);
                    }
                } else {
                    instance.setHaveAlarm(false);
                }
            }
            // 获取其他节点告警
            if (!nodes.isEmpty()) {
                nodes.remove(id);
                List<Map<String, Object>> list = Lists.newArrayList();
                Collection<Map<String, Object>> values = nodes.values();
                for (Map<String, Object> map : values) {
                    if (alarmMap != null) {
                        List<Alarm> alarms = alarmMap.get(map.get("uuid"));
                        if (alarms != null && !alarms.isEmpty()) {
                            map.put("haveAlarm", true);
                            map.put("alarmLevel", Operation.grade(alarms.get(0).getLevel()));
                        } else {
                            map.put("haveAlarm", false);
                        }
                    } else {
                        map.put("haveAlarm", false);
                    }
                    //加入节点的坐标点
                    if (layout) {
                        InstanceLocation instanceLocation = nodesLocation.get(map.get("id"));
                        if (null != instanceLocation) {
                            map.put("x", instanceLocation.getX());
                            map.put("y", instanceLocation.getY());
                        }
                    }
                    list.add(map);
                }
                if (!oneLevel) {
                    //将自身节点加入到nodes数组中
                    list.add(selfMap);
                }
                result.put("nodes", list);
            } else {
                List<Map<String, Object>> list = Lists.newArrayList();
                if (!oneLevel) {
                    list.add(selfMap);
                }
                result.put("nodes", list);
            }
            if (!links.isEmpty()) {
                List<Map<String, Object>> list = Lists.newArrayList();
                Collection<Map<String, Object>> values = links.values();
                for (Map<String, Object> map : values) {
                    list.add(map);
                }
                result.put("links", list);
            } else {
                result.put("links", Lists.newArrayList());
            }

            Map<String, String> relationIconMap = Maps.newHashMap();
            for (Long iconId : iconCache.keySet()) {
                relationIconMap.put(String.valueOf(iconId), iconCache.get(iconId).getIcon());
            }
            result.put("relationIconMap", relationIconMap);
            return new BocloudResult(true, result, "查询成功");
        } catch (Exception e) {
            logger.error("query instance Relation fail:", e);
            return new BocloudResult(false, "查询失败");
        }

    }

    private void buildOneLevelRelation(Map<Long, Map<String, Object>> nodes, Map<String, Map<String, Object>> links,
                                       Long id, Long categoryId, Map<Long, Module> moduleCache, Map<Long, CiIcon> iconCache,
                                       Map<Long, Instance> instanceCache, Map<Long, InstanceValue> instanceValueCache,
                                       Map<String, List<InstanceRelation>> instanceRelationCache, String x, String y, Boolean isGenerate,
                                       Long managerId) {
        try {
            // 查出与当前节点有关系的数据
            List<InstanceRelation> instanceRelationList = instanceRelationCache.get(id + "$$" + categoryId);
            if (instanceRelationList == null) {
                instanceRelationList = instanceRelationRepository.queryByInstanceIdAndCategoryId(id, categoryId);
            }
            if (ListTool.isEmpty(instanceRelationList)) {
                return;
            }
            //获取下级关系的所有节点
            Map<Long, InstanceLocation> locationCache = Maps.newHashMap();
            Map<Long, List<InstanceRelation>> lowerNodes = instanceRelationList.stream().filter(instanceRelation -> instanceRelation.getSourceId().equals(id))
                    .collect(groupingBy(InstanceRelation::getTargetId));
            Set<Long> ids = lowerNodes.keySet();
            List<InstanceLocation> locations = instanceLocationRepository.query(ids, categoryId, managerId);
            for (InstanceLocation location : locations) {
                locationCache.put(location.getNodeId(), location);
            }
            int num = 1;
            Double multiple = 0.5;
            for (InstanceRelation instanceRelation : instanceRelationList) {
                Long instanceId;
                if (instanceRelation.getSourceId().equals(id)) {
                    instanceId = instanceRelation.getTargetId();
                } else {
                    continue;
                }
                Map<String, Object> nodeMap;
                if (!nodes.containsKey(instanceId)) {
                    // 查出节点，放到nodes里
                    Instance node = instanceCache.get(instanceId);
                    if (node == null) {
                        node = instanceRepository.query(instanceId);
                        instanceCache.put(instanceId, node);
                    }
                    if (node == null) {
                        continue;
                    }
                    Module module = moduleCache.get(node.getModuleId());
                    if (null == module) {
                        try {
                            module = moduleRepository.query(node.getModuleId());
                        } catch (Exception e) {
                            continue;
                        }
                        moduleCache.put(node.getModuleId(), module);
                    }
                    if (null == module) {
                        continue;
                    }
                    CiIcon icon = iconCache.get(module.getIconId());
                    if (null == icon) {
                        try {
                            icon = iconRepository.queryByModuleId(node.getModuleId());
                        } catch (Exception e) {
                            continue;
                        }
                        iconCache.put(module.getIconId(), icon);
                    }
                    nodeMap = Maps.newHashMap();
                    nodeMap.put("id", node.getId());
                    nodeMap.put("bname", node.getBname());
                    nodeMap.put("uuid", node.getUuid());
                    nodeMap.put("moduleId", module.getId());
                    if (icon != null) {
                        nodeMap.put("iconId", icon.getId());
                    } else {
                        continue;
                    }
                    /**
                     * 有标题属性的话 用标题属性
                     */
                    InstanceValue instanceValue = instanceValueCache.get(node.getId());
                    if (instanceValue != null) {
                        nodeMap.put("bname", instanceValue.getPropertyValue());
                    }
                    //判断当前节点下是否存在下级节点
                    List<InstanceRelation> nodeRelations = instanceRelationCache.get(node.getId() + "$$" + categoryId);
                    if (nodeRelations == null) {
                        nodeRelations = instanceRelationRepository.queryByInstanceIdAndCategoryId(node.getId(), categoryId);
                    }
                    Boolean leafNode = true;
                    for (InstanceRelation nodeRelation : nodeRelations) {
                        if (node.getId().equals(nodeRelation.getSourceId())) {
                            leafNode = false;
                        }
                    }
                    nodeMap.put("leafNode", leafNode);
                    //生成坐标
                    if (isGenerate) {
                        if (locationCache.containsKey(instanceId)) {
                            InstanceLocation instanceLocation = locationCache.get(instanceId);
                            nodeMap.put("x", instanceLocation.getX());
                            nodeMap.put("y", instanceLocation.getY());
                        } else {
                            int xLocation = Integer.valueOf(x).intValue();
                            int yLocation = Integer.valueOf(y).intValue();
                            if (1 == num) {
                                nodeMap.put("x", x);
                                nodeMap.put("y", yLocation + 170);
                            } else {
                                multiple += 0.5;
                                int i = ((Double) Math.floor(multiple)).intValue();
                                if (0 == num % 2) {
                                    nodeMap.put("x", xLocation + (75 * i));
                                    nodeMap.put("y", yLocation + 170);
                                } else {
                                    nodeMap.put("x", xLocation - (75 * i));
                                    nodeMap.put("y", yLocation + 170);
                                }
                            }
                        }
                        num++;
                    }
                    nodes.put(node.getId(), nodeMap);
                } else {
                    continue;
                }
                // 将当前关系放到关系links里
                String key = instanceRelation.getSourceId() + "-" + instanceRelation.getTargetId();
                if (!links.containsKey(key)) {
                    Relation relationCategory = relationRepository.query(instanceRelation.getRelation());
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("source", instanceRelation.getSourceId());
                    map.put("target", instanceRelation.getTargetId());
                    map.put("relation", relationCategory.getName());
                    links.put(key, map);
                } else {
                    continue;
                }
            }
        } catch (Exception e) {
            logger.error("异常：" + e);
        }
    }

    @Override
    public BocloudResult location(InstanceLocation instanceLocation) {
        try {
            List<InstanceLocation> instanceLocations = instanceLocation.getLocations().stream().map(location -> {
                JSONObject object = JSONObject.parseObject(String.valueOf(location));
                InstanceLocation nodeLocation = new InstanceLocation();
                nodeLocation.setInstanceId(instanceLocation.getInstanceId());
                nodeLocation.setCategoryId(instanceLocation.getCategoryId());
                nodeLocation.setManagerId(instanceLocation.getManagerId());
                nodeLocation.setNodeId(object.getLong("nodeId"));
                nodeLocation.setX(object.getLong("x"));
                nodeLocation.setY(object.getLong("y"));
                return nodeLocation;
            }).collect(Collectors.toList());
            List<InstanceLocation> instanceLocationList = instanceLocationRepository.query(instanceLocation.getInstanceId(),
                    instanceLocation.getCategoryId(), instanceLocation.getManagerId());
            if (!instanceLocationList.isEmpty()) {
                instanceLocationRepository.delete(instanceLocation.getInstanceId(), instanceLocation.getCategoryId(), instanceLocation.getManagerId());
            }
            instanceLocationRepository.batchSave(instanceLocations, instanceLocations.size());
            return new BocloudResult(true, "保存成功");
        } catch (Exception e) {
            logger.error("instance location set is error:", e);
            return new BocloudResult(false, "保存失败");
        }
    }

    /**
     * 拼接拓扑图
     *
     * @param nodes
     * @param links
     * @param id
     * @param hierarchy
     * @param categoryId
     * @param moduleCache
     * @param iconCache
     * @param instanceCache
     * @param instanceValueCache
     * @param instanceRelationCache
     */
    private void buildRelation(Map<Long, Map<String, Object>> nodes, Map<String, Map<String, Object>> links, Long id,
                               int hierarchy, Long categoryId, Map<Long, Module> moduleCache, Map<Long, CiIcon> iconCache,
                               Map<Long, Instance> instanceCache, Map<Long, InstanceValue> instanceValueCache,
                               Map<String, List<InstanceRelation>> instanceRelationCache) {
        try {
            // 查出与当前节点有关系的数据
            List<InstanceRelation> instanceRelationList = instanceRelationCache.get(id + "$$" + categoryId);
            if (instanceRelationList == null) {
                instanceRelationList = instanceRelationRepository.queryByInstanceIdAndCategoryId(id, categoryId);
            }
            if (ListTool.isEmpty(instanceRelationList)) {
                return;
            }
            for (InstanceRelation instanceRelation : instanceRelationList) {
                Long instanceId = 0L;
                // 判断哪个节点是与当前节点发生关系的节点
                if (instanceRelation.getSourceId().equals(id)) {
                    instanceId = instanceRelation.getTargetId();
                } else {
                    instanceId = instanceRelation.getSourceId();
                }
                Map<String, Object> nodeMap = null;
                int leafNodeNumber = 0;
                if (!nodes.containsKey(instanceId)) {
                    // 查出节点，放到nodes里
                    Instance node = instanceCache.get(instanceId);
                    if (node == null) {
                        node = instanceRepository.query(instanceId);
                        instanceCache.put(instanceId, node);
                    }
                    if (node == null) {
                        continue;
                    }
                    Module module = moduleCache.get(node.getModuleId());
                    if (null == module) {
                        try {
                            module = moduleRepository.query(node.getModuleId());
                        } catch (Exception e) {
                            continue;
                        }
                        moduleCache.put(node.getModuleId(), module);
                    }
                    if (null == module) {
                        continue;
                    }

                    CiIcon icon = iconCache.get(module.getIconId());
                    if (null == icon) {
                        try {
                            icon = iconRepository.queryByModuleId(node.getModuleId());
                        } catch (Exception e) {
                            continue;
                        }
                        iconCache.put(module.getIconId(), icon);
                    }
                    nodeMap = Maps.newHashMap();
                    nodeMap.put("id", node.getId());
                    nodeMap.put("bname", node.getBname());
                    nodeMap.put("uuid", node.getUuid());
                    nodeMap.put("moduleId", module.getId());
                    if (icon != null) {
                        nodeMap.put("iconId", icon.getId());
                    } else {
                        continue;
                    }
                    /**
                     * 有标题属性的话 用标题属性
                     */
                    InstanceValue instanceValue = instanceValueCache.get(node.getId());
                    if (instanceValue != null) {
                        nodeMap.put("bname", instanceValue.getPropertyValue());
                    }
                    //判断当前节点下是否存在下级节点
                    List<InstanceRelation> nodeRelations = instanceRelationCache.get(node.getId() + "$$" + categoryId);
                    if (nodeRelations == null) {
                        nodeRelations = instanceRelationRepository.queryByInstanceIdAndCategoryId(node.getId(), categoryId);
                    }
                    Boolean leafNode = true;
                    for (InstanceRelation nodeRelation : nodeRelations) {
                        if (node.getId().equals(nodeRelation.getSourceId())) {
                            leafNodeNumber++;
                            leafNode = false;
                        }
                    }
                    nodeMap.put("leafNode", leafNode);
                    nodes.put(node.getId(), nodeMap);
                } else {
                    nodeMap = nodes.get(instanceId);
                }
                // 将当前关系放到关系links里
                String key = instanceRelation.getSourceId() + "-" + instanceRelation.getTargetId();
                if (!links.containsKey(key)) {
                    Relation relationCategory = relationRepository.query(instanceRelation.getRelation());
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("source", instanceRelation.getSourceId());
                    map.put("target", instanceRelation.getTargetId());
                    map.put("relation", relationCategory.getName());
                    links.put(key, map);
                } else {
                    continue;
                }
                // 只钻5层（从当前根节点算起）
                if (hierarchy == 4) {
                    // 统计与当前关系节点下节点的所有关系数量
                    int count = instanceRelationRepository.countQueryByInstanceIdAndCategoryId(instanceId, categoryId);
                    if (count > 1) {
                        // 下一层有几个孩子，除去根节点以外的关系数（otherRelationNum作为前端控制节点是否可以继续往下钻取的标识）
                        nodeMap.put("otherRelationNum", count - 1);
                    }
                } else {
                    // 继续钻取关系
                    if (leafNodeNumber < 12) {
                        buildRelation(nodes, links, instanceId, hierarchy + 1, categoryId, moduleCache, iconCache,
                                instanceCache, instanceValueCache, instanceRelationCache);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("query instanceRelationList fail:", e);
        }
    }

    /**
     * 关系的自动发现
     *
     * @param instance
     * @param userId
     */
    @Override
    public void autoDiscovery(Instance instance, Long userId) {
        try {
            // 查出 引用的属性 并且启用了自动发现的
            List<Property> properties = propertyRepository.queryByQuoteForDiscovery(instance.getModuleId());
            for (Property property : properties) {
                // 查出所有维度
                List<RelationCategory> relationCategories = relationCategoryRepository.list();
                for (RelationCategory relationCategory : relationCategories) {
                    // 查询出符合的模型关系
                    ModuleRelation moduleRelation = moduleRelationRepository.queryBySidAndTid(property.getModuleId(),
                            property.getLinkModuleId(), relationCategory.getId());
                    if (moduleRelation != null) {
                        // 判断 如果与引用的模型 对应的是关系的1:1 或N:1 满足自动挂接关系的要求
                        if (!((moduleRelation.getSourceId().equals(property.getLinkModuleId())
                                && "1".equals(moduleRelation.getSourceType()))
                                || (moduleRelation.getTargetId().equals(property.getLinkModuleId())
                                && "1".equals(moduleRelation.getTargetType())))) {
                            continue;
                        }
                        List<InstanceValue> instanceValues = instance.getProperties();
                        for (InstanceValue instanceValue : instanceValues) {
                            // 找到对应的 属性
                            if (instanceValue.getPropertyCode().equals(property.getCode())) {
                                // 查询出 当前模型关系 对应的 实例关系
                                List<InstanceRelation> instanceRelations = instanceRelationRepository
                                        .queryByInstanceIdAndModuleRelationId(instance.getId(), moduleRelation.getId());
                                // 如果本次属性为空 则清空已有的关系 理论上最多只有一条数据 为了保险起见 就循环吧
                                if ("".equals(instanceValue.getPropertyValue())
                                        && instanceRelations.size() > 0) {
                                    for (InstanceRelation instanceRelation : instanceRelations) {
                                        instanceRelationRepository.deleteByRelationId(instanceRelation.getId());
                                    }
                                } else if (!"".equals(instanceValue.getPropertyValue())) {
                                    boolean isSame = false;
                                    // 原来的关系 和本此应该生成的关系 一致 就不必做其他操作了 最多也就一条
                                    for (InstanceRelation instanceRelation : instanceRelations) {
                                        if ((instanceRelation.getTargetId().equals(instance.getId()) && instanceRelation
                                                .getSourceId() == Long.parseLong(instanceValue.getPropertyValue()))
                                                || ((instanceRelation.getTargetId() == Long
                                                .parseLong(instanceValue.getPropertyValue()))
                                                && instanceRelation.getSourceId().equals(instance.getId()))) {
                                            isSame = true;
                                        } else {
                                            if (instanceRelation.getManual() == false) {
                                                instanceRelationRepository.delete(instanceRelation.getId());
                                            }
                                        }
                                    }
                                    if (isSame) {
                                        // 关系不必再 自动挂接
                                        continue;
                                    }
                                    Instance target = instanceRepository
                                            .query(Long.parseLong(instanceValue.getPropertyValue()));
                                    BocloudResult result = validate(moduleRelation, instance, target);
                                    if (result.isFailed()) {
                                        continue;
                                    }
                                    // 新增关系
                                    // 当前数据 是源头的话
                                    if (moduleRelation.getSourceId().equals(instance.getModuleId())) {
                                        InstanceRelation instanceRelationNew = new InstanceRelation(instance.getId(),
                                                moduleRelation.getRelationId(),
                                                Long.parseLong(instanceValue.getPropertyValue()),
                                                property.getModuleId(), property.getLinkModuleId(),
                                                moduleRelation.getId(), new Date(), userId, false,
                                                relationCategory.getId(), false);
                                        instanceRelationRepository.save(instanceRelationNew);
                                    } else {
                                        InstanceRelation instanceRelationNew = new InstanceRelation(
                                                Long.parseLong(instanceValue.getPropertyValue()),
                                                moduleRelation.getRelationId(), instance.getId(),
                                                property.getLinkModuleId(), property.getModuleId(),
                                                moduleRelation.getId(), new Date(), userId, false,
                                                relationCategory.getId(), false);
                                        instanceRelationRepository.save(instanceRelationNew);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("自动发现出错", e);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public BocloudResult save(List<Object> list, Long userId, Long instanceId) {
        for (Object object : list) {
            Long categoryId = Long.parseLong(((Map<String, Object>) object).get("categoryId").toString());
            List<Map<String, Long>> links = (List<Map<String, Long>>) ((Map<String, Object>) object).get("linkIds");
            BocloudResult result = create(instanceId, links, userId, categoryId);
            if (result.isFailed()) {
                return result;
            }
        }
        return new BocloudResult(true, "保存成功");
    }

    /**
     * 保存关系
     *
     * @param relations
     * @param instance
     * @param moduleId
     * @param userId
     * @param relationDelayQueue
     * @param oldMap
     * @param insertRelationSet
     */
    @Override
    public void syncRelation4Mq(List<InstanceRelationMq> relations, Instance instance, Long moduleId, Long userId,
                                DelayQueue<RelationDelay> relationDelayQueue, Map<String, InstanceRelation> oldMap,
                                Set<String> insertRelationSet) {
        try {
            List<InstanceRelation> oldRelations = instanceRelationRepository.queryByInstanceId(instance.getId());
            for (InstanceRelation relation : oldRelations) {
                String key = null;
                if (relation.getSourceId() > relation.getTargetId()) {
                    key = relation.getCategoryId() + "&&" + relation.getTargetId() + "&&" + relation.getSourceId()
                            + "&&" + relation.getModuleRelationId();
                } else {
                    key = relation.getCategoryId() + "&&" + relation.getSourceId() + "&&" + relation.getTargetId()
                            + "&&" + relation.getModuleRelationId();
                }
                if (!oldMap.containsKey(key)) {
                    oldMap.put(key, relation);
                }
            }
            if (ListTool.isEmpty(relations)) {
                return;
            }
            // 循环每一种关系
            for (InstanceRelationMq relation : relations) {
                Long categoryId = relation.getCategoryId();
                RelationCategory relationCategory = relationCategoryRepository.query(categoryId);
                if (relationCategory == null) {
                    continue;
                }
                Module targetModule = moduleRepository.queryByCode(relation.getTargetModule());
                // 如果模型不存在 跳过
                if (targetModule == null) {
                    continue;
                }
                // 获取每一个目标 做相关校验
                List<String> guids = relation.getGuids();
                if (ListTool.isEmpty(guids)) {
                    continue;
                }
                ModuleRelation moduleRelation = moduleRelationRepository.queryBySidAndTid(moduleId, targetModule.getId(),
                        categoryId);
                if (moduleRelation == null) {
                    continue;
                }
                for (String guid : guids) {
                    if (StringUtils.isEmpty(guid) || "null".equalsIgnoreCase(guid)) {
                        continue;
                    }
                    Instance target = instanceRepository.queryByBname(targetModule.getId(), guid);
                    if (target == null) {
                        // 目标不存在 有可能是还没创建
                        if (moduleRelation.isSource(targetModule.getId())) {
                            InstanceRelation relationNew = new InstanceRelation(null, moduleRelation.getRelationId(),
                                    instance.getId(), targetModule.getId(), moduleId, moduleRelation.getId(),
                                    new Date(), userId, false, categoryId, false);
                            relationNew.setGuidTemp(guid);
                            RelationDelay delay = new RelationDelay(relationNew, "source", instance, moduleRelation);
                            relationDelayQueue.put(delay);
                        } else {
                            InstanceRelation relationNew = new InstanceRelation(instance.getId(),
                                    moduleRelation.getRelationId(), null, moduleId, targetModule.getId(),
                                    moduleRelation.getId(), new Date(), userId, false, categoryId, false);
                            relationNew.setGuidTemp(guid);
                            RelationDelay delay = new RelationDelay(relationNew, "target", instance, moduleRelation);
                            relationDelayQueue.put(delay);
                        }
                    } else {
                        String key = null;
                        if (instance.getId() > target.getId()) {
                            key = categoryId + "&&" + target.getId() + "&&" + instance.getId() + "&&"
                                    + moduleRelation.getId();
                        } else {
                            key = categoryId + "&&" + instance.getId() + "&&" + target.getId() + "&&"
                                    + moduleRelation.getId();
                        }
                        if (oldMap.containsKey(key)) {
                            logger.info("关系已存在，不做处理:" + JSONObject.toJSONString(oldMap.get(key)));
                            // 以前存在就不在做其他操作了
                            oldMap.remove(key);
                            if (!insertRelationSet.contains(key)) {
                                // 防止传过来的顺序不对 导致多删除了不该删的
                                insertRelationSet.add(key);
                            }
                        } else {
                            if (!insertRelationSet.contains(key)) {
                                insertRelationSet.add(key);
                            }
                            BocloudResult result = new BocloudResult();
                            InstanceRelation relationNew = null;
                            if (moduleRelation.isSource(targetModule.getId())) {
                                relationNew = new InstanceRelation(target.getId(), moduleRelation.getRelationId(),
                                        instance.getId(), targetModule.getId(), moduleId, moduleRelation.getId(),
                                        new Date(), userId, false, categoryId, false);
                                result = validate(moduleRelation, instance, target);
                            } else {
                                relationNew = new InstanceRelation(instance.getId(), moduleRelation.getRelationId(),
                                        target.getId(), moduleId, targetModule.getId(), moduleRelation.getId(),
                                        new Date(), userId, false, categoryId, false);
                                result = validate(moduleRelation, target, instance);
                            }
                            if (result.isFailed()) {
                                logger.error(result.getMessage());
                                RelationDelay delay = new RelationDelay(relationNew, "later", instance, moduleRelation);
                                relationDelayQueue.put(delay);
                                continue;
                            }
                            instanceRelationRepository.save(relationNew);
                            logger.info("关系增加成功:" + JSONObject.toJSONString(relationNew));
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("处理关系失败", e);
        }
    }

}
