package com.bocloud.ims.service.topology;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.GridBean;
import com.bocloud.common.model.Param;
import com.bocloud.common.utils.GridHelper;
import com.bocloud.common.utils.ListTool;
import com.bocloud.ims.entity.topology.*;
import com.bocloud.ims.interfaces.topology.InstanceRelationService;
import com.bocloud.ims.interfaces.topology.InstanceService;
import com.bocloud.ims.repository.topology.*;
import com.bocloud.ims.service.utils.*;
import com.bocloud.service.lock.BocloudACLock;
import com.bocloud.service.lock.LockFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.io.InputStream;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.*;

/**
 * instance Service层
 *
 * @author lyy
 * @Version 1.0
 * @since 2017年9月15日
 */
@Service("instanceService")
public class InstanceServiceImpl implements InstanceService, InitializingBean {
    private static final Logger logger = LoggerFactory.getLogger(InstanceServiceImpl.class);
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private InstanceRepository instanceRepository;
    @Autowired
    private PropertyRepository propertyRepository;
    @Autowired
    private PropertyItemRepository propertyItemRepository;
    @Autowired
    private InstanceValueRepository instanceValueRepository;
    @Autowired
    private PropertyGroupRepository propertyGroupRepository;
    @Autowired
    private RegularExpressionRepository regularExpressionRepository;
    @Autowired
    private AmqpTemplate amqpTemplate;
    //    @Autowired
//    FileRepository fileRepository;
    // excel文件的输入流对象
    protected InputStream excel;
    @Autowired
    protected ModuleRepository moduleRepository;
    @Autowired
    private ModuleRelationRepository moduleRelationRepository;
    @Autowired
    private RelationRepository relationRepository;
    @Autowired
    private RelationCategoryRepository relationCategoryRepository;
    @Autowired
    private InstanceRelationRepository instanceRelationRepository;
    @Autowired
    private InstanceRelationService instanceRelationService;
    @Autowired
    private InstanceGridRepository instanceGridRepository;
    //    @Autowired
//    private SynConfigRepository synConfigRepository;
    @Autowired
    private SynMappingRepository synMappingRepository;
    //    @Autowired
//    private SocUserService socUserService;
//    @Autowired
//    private OperatingHistoryRepository operatingHistoryRepository;
    @Autowired
    private ResourceEventPublisher resourceEventPublisher;

    /**
     * 消息处理队列
     */
    private ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("import-pool-%d").build();
    private ExecutorService threadQueue = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(1024), threadFactory, new ThreadPoolExecutor.AbortPolicy());
    /**
     * 关系处理队列
     */
    private DelayQueue<RelationDelay> relationDelayQueue = new DelayQueue<RelationDelay>();

    /**
     * 配置列表
     */
    @Override
    public BocloudResult list(int page, int rows, List<Param> params, Map<String, String> sorter, Boolean simple,
                              Long userId, Boolean showTitle) {
        GridBean gridBean = null;
        try {
            if (null == params) {
                params = new ArrayList<Param>();
            }
            if (null == sorter) {
                sorter = Maps.newHashMap();
            }
            // 表头选中状态加载
            List<Property> propertiesAll = propertyRepository
                    .queryByPropertyStatusId(Long.parseLong(instanceRepository.getField(params, "moduleId")), userId);
            int total;
            if (instanceRepository.getField(params, "bname") != null) {
                total = this.instanceRepository.count(params);
            } else {
                total = this.instanceRepository.countSimple(Long.parseLong(instanceRepository.getField(params, "moduleId")));
            }
            List<Map<String, Object>> list = this.instanceRepository.list(page, rows, params, sorter, propertiesAll, simple,
                    showTitle);
            for (Map<String, Object> map : list) {
                InstanceValue instanceValue = instanceValueRepository
                        .queryByInstanceIdAndPropertyCode(Long.parseLong(map.get("id").toString()), "name");
                map.put("name", instanceValue.getPropertyValue());
            }
            InstanceHelper instanceHelper = new InstanceHelper(propertyItemRepository, instanceRepository, instanceGridRepository,
                    instanceValueRepository);
            instanceHelper.converInstanceValue(propertiesAll, list);
            gridBean = GridHelper.getBean(page, rows, total, list);
            Map<String, Object> data = Maps.newHashMap();
            if (showTitle) {
                Property title = propertyRepository.queryForTitle(Long.parseLong(instanceRepository.getField(params, "moduleId")));
                if (title != null) {
                    data.put("name", title.getName());
                }
            } else {
                Property bname = propertyRepository.queryByCode("name",
                        Long.parseLong(instanceRepository.getField(params, "moduleId")));
                if (bname != null) {
                    data.put("name", bname.getName());
                }
            }
            data.put("page", gridBean.getPage());
            data.put("rows", gridBean.getRows());
            data.put("total", gridBean.getTotal());
            data.put("pages", gridBean.getPages());
            data.put("columns", JSONObject.toJSON(propertiesAll));
            return new BocloudResult(true, data, "查询成功");
        } catch (Exception e) {
            logger.error("Query notice instance list fail:", e);
            return new BocloudResult(false, "查询失败");
        }
    }

    /**
     * 新增配置
     */
    @Override
    public BocloudResult create(Instance instance, Long userId) {
        String path = Instance.class.getSimpleName() + "_" + instance.getId();
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            instance.setGmtCreate(new Date());
            instance.setCreatorId(userId);
            instance.setDeleted(false);
            if (instance.getUuid() == null) {
                instance.setUuid(UUID.randomUUID().toString());
            }
            this.instanceRepository.save(instance);
/*            if (null == instance) {
                logger.warn("Create instance  fail!");
                return new BocloudResult(false, instance, "保存失败");
            }*/
            ValidateHelper validateHelper = new ValidateHelper(instanceRepository, propertyRepository, propertyItemRepository,
                    regularExpressionRepository);
            // 属性校验
            String validateMessage = validateHelper.validateInstance(instance);
            if (StringUtils.isNotEmpty(validateMessage)) {
                instanceRepository.delete(instance.getId());
                return new BocloudResult(false, "校验不通过：\n" + validateMessage);
            }
            // 属性保存
            saveInstanceValue(instance);
            instanceRepository.update(instance);
            instanceRelationService.autoDiscovery(instance, userId);
        } catch (Exception e) {
            logger.error("Create notice instance error:", e);
            try {
                if (null != instance) {
                    instanceRepository.deletePhysical(instance.getId());
                }
            } catch (Exception e1) {
                logger.error("删除失败", e);
            }
            return new BocloudResult(false, "添加失败");
        }
        return new BocloudResult(true, instance, "添加成功");
    }

    /**
     * 保存数据的属性
     *
     * @param instance
     * @throws Exception
     */
    private void saveInstanceValue(Instance instance) throws Exception {
        List<InstanceValue> instanceValues = instanceValueRepository.getByInstanceId(instance.getId());
        List<InstanceGrid> instanceGrids = instanceGridRepository.queryByInstanceId(instance.getId());
        Map<String, InstanceValue> oldValues = Maps.newHashMap();
        Map<Long, InstanceGrid> oldGrids = Maps.newHashMap();
        for (InstanceValue instanceValue : instanceValues) {
            if (oldValues.containsKey(instanceValue.getPropertyCode())) {
                instanceValueRepository.delete(instanceValue.getId());
            } else {
                oldValues.put(instanceValue.getPropertyCode(), instanceValue);
            }
        }
        for (InstanceGrid instanceGrid : instanceGrids) {
            oldGrids.put(instanceGrid.getId(), instanceGrid);
        }
        List<InstanceValue> createValueList = new ArrayList<>();
        List<InstanceValue> modifyValueList = new ArrayList<>();
        List<InstanceGrid> createGridList = new ArrayList<>();
        List<InstanceGrid> modifyGridList = new ArrayList<>();
        List<InstanceValue> properties = instance.getProperties();
        for (InstanceValue instanceValue : properties) {
            // 对表格的处理
            if (instanceValue.getProperty().isTable()) {
                List<InstanceGrid> grids = instanceValue.getGrid();
                if (ListTool.isEmpty(grids)) {
                    continue;
                }
                for (InstanceGrid instanceGrid : grids) {
                    instanceGrid.setInstanceId(instance.getId());
                    instanceGrid.setPropertyCode(instanceValue.getProperty().getCode());
                    instanceGrid.setPropertyId(instanceValue.getProperty().getId());
                    if (instanceGrid.getId() == null) {
                        createGridList.add(instanceGrid);
                    } else if (instanceGrid.getId() != null && oldGrids.containsKey(instanceGrid.getId())) {
                        modifyGridList.add(instanceGrid);
                        oldGrids.remove(instanceGrid.getId());
                    } else {
                        instanceGrid.setId(null);
                        createGridList.add(instanceGrid);
                    }
                }
                continue;
            }
            // bname显示到主表
            if ("bname".equals(instanceValue.getPropertyCode())) {
                instance.setBname(instanceValue.getPropertyValue());
            }
            if (oldValues.containsKey(instanceValue.getPropertyCode())) {
                instanceValue.setId(oldValues.get(instanceValue.getPropertyCode()).getId());
                instanceValue.setInstanceId(instance.getId());
                modifyValueList.add(instanceValue);
                oldValues.remove(instanceValue.getPropertyCode());
                continue;
            }
            instanceValue.setInstanceId(instance.getId());
            createValueList.add(instanceValue);
        }

        if (modifyValueList.size() > 0) {
            instanceValueRepository.batchUpdate(modifyValueList, modifyValueList.size());
        }
        if (createValueList.size() > 0) {
            instanceValueRepository.batchSave(createValueList, createValueList.size());
        }
        if (createGridList.size() > 0) {
            instanceGridRepository.batchSave(createGridList, createGridList.size());
        }
        if (modifyGridList.size() > 0) {
            instanceGridRepository.batchUpdate(modifyGridList, modifyGridList.size());
        }
        for (Entry<String, InstanceValue> entry : oldValues.entrySet()) {
            instanceValueRepository.delete(entry.getValue().getId());
        }
        for (Long id : oldGrids.keySet()) {
            instanceGridRepository.delete(id);
        }
    }

    @Override
    public BocloudResult modify(Instance instance, Long userId) {
        String path = Instance.class.getSimpleName() + "_" + instance.getId();
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            Instance object = this.instanceRepository.query(instance.getId());
            if (null == object) {
                logger.warn("Instance does not exist!");
                return new BocloudResult(false, "数据不存在");
            }
            ValidateHelper validateHelper = new ValidateHelper(instanceRepository, propertyRepository, propertyItemRepository,
                    regularExpressionRepository);
            // 属性校验
            String validateMessage = validateHelper.validateInstance(instance);
            if (!"".equals(validateMessage)) {
                return new BocloudResult(false, "校验不通过：\n" + validateMessage);
            }
            // 属性保存
            saveInstanceValue(instance);
            object.setBname(instance.getBname());
            object.setGmtModify(new Date());
            object.setMenderId(userId);
            object.setProperties(instance.getProperties());
            this.instanceRepository.update(object);
            instanceRelationService.autoDiscovery(object, userId);
            return new BocloudResult(true, object, "修改成功");
        } catch (Exception e) {
            logger.error("Modify notice instance fail:", e);
            return new BocloudResult(false, "修改失败");
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see com.bocloud.cmdb.service.instance.InstanceService#remove(java.lang.Long)
     */
    @Override
    public BocloudResult remove(Long id, Long userId) {
        String path = Instance.class.getSimpleName() + "_" + id;
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            Instance instance = instanceRepository.query(id);
            if (instance == null) {
                return new BocloudResult(false, "数据不存在");
            }
            String message = removeValidate(instance);
            if (!"".equals(message)) {
                return new BocloudResult(false, message);
            }
            // 删除实例关系
            this.instanceRelationRepository.deleteByInstanceId(id);
            // 删除实例数据
            this.instanceRepository.delete(id);
            return new BocloudResult(true, "删除成功");
        } catch (Exception e) {
            logger.error("Remove notice instance fail:", e);
            return new BocloudResult(false, "删除失败");
        }
    }

    /**
     * 删除前的校验
     *
     * @param instance
     * @return
     */
    private String removeValidate(Instance instance) {
        StringBuffer message = new StringBuffer();
        try {
            // 是否有引用
            Module module = moduleRepository.query(instance.getModuleId());
            List<Property> properties = propertyRepository.queryQuoteByModuleId(module.getId());
            if (!properties.isEmpty()) {
                List<Long> propertyIds = Lists.newArrayList();
                for (Property property : properties) {
                    propertyIds.add(property.getId());
                }
                List<Instance> instances = instanceRepository.queryQuoteByInstanceId(propertyIds, instance.getId());
                if (!instances.isEmpty()) {
                    message.append("存在[" + instances.size() + "]条数据引用该实例，请先解除关联再删除.");
                }
            }
        } catch (Exception e) {
            logger.error("查询失败", e);
        }
        return message.toString();
    }

    @Override
    public BocloudResult detail(Long id) {
        try {
            // 查询实例信息
            Instance instance = instanceRepository.query(id);
            if (instance == null) {
                return new BocloudResult(false, "数据不存在");
            }
            // 根据当前实例信息中的模型id查询模型属性中的所有分组
            List<PropertyGroup> ciPropertyGroupLists = propertyGroupRepository.queryByModuleId(instance.getModuleId());
            // 查询出模型所有的属性
            List<Property> ciPropertyLists = propertyRepository.queryPropertysAndValue(id, instance.getModuleId());
            InstanceHelper instanceHelper = new InstanceHelper(propertyItemRepository, instanceRepository, instanceGridRepository,
                    instanceValueRepository);
            instanceHelper.converDetailValue(id, ciPropertyLists);
            HashMap<Object, Object> maps = Maps.newHashMap();
            maps.put("moduleId", id);
            maps.put("groups", ciPropertyGroupLists);
            maps.put("properties", ciPropertyLists);
            return new BocloudResult(true, maps, "查询成功");
        } catch (Exception e) {
            logger.error("Query instance detail error:", e);
            return new BocloudResult(false, "查询失败");
        }
    }


    @Override
    public void receive(InstanceMq instancemq) {
        if (StringUtils.isEmpty(instancemq.getUuid())) {
            logger.error("资源数据接收，未附带uuid，不予处理。");
            return;
        }
        if (null == instancemq.getData() || instancemq.getData().isEmpty()) {
            logger.error("资源数据接收，批次 [{}] 没有数据！", instancemq.getUuid());
            return;
        }
        final Long userId;
        try {
//            SynConfig synConfig = synConfigRepository.queryByServiceName(instance4mq.getServiceName());
//            if (synConfig == null) {
//                logger.error("cmdb接收，批次 [{}] 服务名称不存在！", instance4mq.getUuid());
//                return;
//            }
            userId = instancemq.getManagerId();
        } catch (Exception e) {
            logger.error("资源数据接收，查询失败！", e);
            return;
        }
        receiveHandler(instancemq, userId);
    }

    private void receiveHandler(InstanceMq instance4mq, Long userId) {
        logger.info("现在处理：" + JSONObject.toJSONString(instance4mq));
        Map<String, Module> moduleCache = Maps.newHashMap();
        Map<String, Map<String, String>> mappingCache = Maps.newHashMap();
        Map<String, Property> propertyCache = Maps.newHashMap();
        Map<String, InstanceRelation> oldMap = Maps.newHashMap();
        Set<String> insertRelationSet = Sets.newHashSet();
        String uuid = instance4mq.getUuid();
        // 遍历一条条的数据
        for (Instance instance : instance4mq.getData()) {
            if (StringUtils.isEmpty(instance.getModuleCode())) {
                logger.error("资源数据接收，批次[{}] ModuleCode 为空！", uuid);
                return;
            }
            // 验证模型编码
            Module module = moduleCache.get(instance.getModuleCode());
            if (null == module) {
                try {
                    module = moduleRepository.queryByCode(instance.getModuleCode());
                } catch (Exception e) {
                    logger.error("资源数据接收，查询失败2", e);
                    continue;
                }
                moduleCache.put(instance.getModuleCode(), module);
            }
            if (null == module) {
                logger.error("资源数据接收，模型[" + instance.getModuleCode() + "]不存在");
                continue;
            }
            instance.setModuleId(module.getId());
            if (null == instance.getUuid()) {
                logger.error("资源数据接收，实例uuid不能为空");
                continue;
            }
            if (Operation.DELETE.getOperate().equals(instance.getOperation())) {
                try {
                    Instance deadInstance = instanceRepository.queryByUuid(instance.getUuid());
                    if (null == deadInstance) {
                        continue;
                    }
                    Long deadInstanceId = deadInstance.getId();
                    BocloudResult bsmResult = remove(deadInstanceId, userId);
                    if (bsmResult.isFailed()) {
                        logger.error("资源数据接收，实例[{}] 删除失败！失败原因：[{}]", instance.getUuid(), bsmResult.getMessage());
                    } else {
                        logger.info("资源数据接收，实例[{}]删除成功！", instance.getUuid());
                    }
                } catch (Exception e) {
                    logger.error("删除实例失败!", e);
                }
                continue;
            } else if (Operation.MODIFY.getOperate().equals(instance.getOperation())) {
                // 可以传部分属性 其他的不变
                if (ListTool.isEmpty(instance.getProperties())) {
                    continue;
                }
                try {
                    Instance old = instanceRepository.query(instance.getId());
                    if (old == null) {
                        continue;
                    }
                    List<InstanceValue> oldInstanceValues = instanceValueRepository.getByInstanceId(instance.getId());
                    List<InstanceValue> newInstanceValues = instance.getProperties();
                    for (InstanceValue oldInstanceValue : oldInstanceValues) {
                        for (InstanceValue newInstanceValue : newInstanceValues) {
                            if (newInstanceValue.getPropertyCode()
                                    .equalsIgnoreCase(oldInstanceValue.getPropertyCode())) {
                                oldInstanceValue.setPropertyValue(newInstanceValue.getPropertyValue());
                            }
                        }
                    }
                    instance.setProperties(oldInstanceValues);
                    this.modify(instance, userId);
                } catch (Exception e) {
                    logger.error("Modify instance [{}] Exception ", instance.getBname(), e);
                }
                continue;
            }

            // 获取映射关系
            Map<String, String> mappingMap = mappingCache.get(instance.getModuleCode());
            if (mappingMap == null) {
                try {
                    List<SynMapping> list = synMappingRepository.query(instance4mq.getServiceName(), instance.getModuleCode());
                    mappingMap = Maps.newHashMap();
                    for (SynMapping synMapping : list) {
                        mappingMap.put(synMapping.getTargetCode(), synMapping.getPropertyCode());
                    }
                    mappingCache.put(instance.getModuleCode(), mappingMap);
                } catch (Exception e) {
                    logger.error("资源数据接收，查询失败", e);
                }
            }
            List<InstanceValue> instanceValues = instance.getProperties();
            if (ListTool.allNull(instanceValues)) {
                logger.error("资源数据接收，实例[" + instance4mq.getUuid() + "]属性为空");
                continue;
            }
            // 处理属性 并得到bname
            String bname = receiveInstanceValueHandler(propertyCache, instance, mappingMap, instanceValues);
            if (StringUtils.isEmpty(bname)) {
                logger.error("资源数据接收，实例[{}]名称为空!", instance.getUuid());
                continue;
            }
            // 查找名称 是否存在
            Instance instanceTemp;
            try {
                instanceTemp = instanceRepository.queryByBname(module.getId(), bname);
                if (instanceTemp == null) {
                    BocloudResult result = create(instance, userId);
                    if (result.isSuccess()) {
                        logger.info("资源数据接收，实例[" + instance.getUuid() + "]新建成功");
                        instanceRelationService.syncRelation4Mq(instance.getRelations(), instance, module.getId(),
                                userId, relationDelayQueue, oldMap, insertRelationSet);
                    } else {
                        logger.info("资源数据接收，实例[" + instance.getUuid() + "]新建失败，" + result.getMessage());
                    }
                } else {
                    instance.setId(instanceTemp.getId());
                    BocloudResult result = modify(instance, userId);
                    if (result.isSuccess()) {
                        logger.info("资源数据接收，实例[" + instance.getUuid() + "]修改成功");
                        instanceRelationService.syncRelation4Mq(instance.getRelations(), instance, module.getId(),
                                userId, relationDelayQueue, oldMap, insertRelationSet);
                    } else {
                        logger.info("资源数据接收，实例[" + instance.getUuid() + "]修改失败，" + result.getMessage());
                    }
                }
            } catch (Exception e) {
                logger.error("资源数据接收，查询失败5", e);
            }
        }
        if (!oldMap.isEmpty()) {
            List<Long> ids = Lists.newArrayList();
            for (String key : oldMap.keySet()) {
                // 新增的不要出现误删除了
                if (insertRelationSet.contains(key)) {
                    continue;
                }
                InstanceRelation instanceRelation = oldMap.get(key);
                // 只删除自动挂接的
                if (instanceRelation.getManual() == false) {
                    logger.info("废弃之前的关系:" + JSONObject.toJSONString(instanceRelation));
                    ids.add(instanceRelation.getId());
                } else {
                    logger.info("手工关系不删除:" + JSONObject.toJSONString(instanceRelation));
                }
            }
            if (!ids.isEmpty()) {
                try {
                    instanceRelationRepository.batchDelete(ids);
                } catch (Exception e) {
                    logger.error("删除关系失败" + e);
                }
            }
        }
        logger.error("批次[" + instance4mq.getUuid() + "]处理完毕,延迟处理关系：" + relationDelayQueue.size());
    }

    /**
     * 对属性的处理
     *
     * @param propertyCache
     * @param instance
     * @param mappingMap
     * @param instanceValues
     * @return
     */
    private String receiveInstanceValueHandler(Map<String, Property> propertyCache, Instance instance,
                                               Map<String, String> mappingMap, List<InstanceValue> instanceValues) {
        String bname = "";
        // 处理一个个的属性
        for (InstanceValue instanceValue : instanceValues) {
            // 如果属性不存在的话 就跳过
            if (!mappingMap.containsKey(instanceValue.getPropertyCode())) {
                continue;
            }
            // 得到cmdb中的属性编码
            String propertyCode = mappingMap.get(instanceValue.getPropertyCode());
            Property property = propertyCache.get(instance.getModuleCode() + "&&" + propertyCode);
            if (property == null) {
                try {
                    property = propertyRepository.queryByCode(propertyCode, instance.getModuleId());
                    if (property != null && (property.isHaveItem())) {
                        property.setItem(propertyItemRepository.queryByPropertyId(property.getId()));
                    }
                } catch (Exception e) {
                    logger.error("资源数据接收，查询失败4", e);
                }
            }
            if (property == null) {
                continue;
            }
            if (property.isTable()) {
                List<List<Map<String, String>>> rows = instanceValue.getTable();
                if (rows == null) {
                    continue;
                }
                // 一行数据
                for (List<Map<String, String>> list : rows) {
                    InstanceGrid instanceGrid = new InstanceGrid(property.getId(), property.getCode());
                    // 一行中的列
                    for (Map<String, String> map : list) {
                        // 查找对应的属性
                        for (PropertyItem pitem : property.getItem()) {
                            if (pitem.getName().equals(map.get("name"))) {
                                BeanUtils.setProperties(instanceGrid, map.get("value"), pitem.getValue());
                            }
                        }
                    }
                    if (instanceValue.getGrid() == null) {
                        instanceValue.setGrid(Lists.newArrayList());
                    }
                    instanceValue.getGrid().add(instanceGrid);
                }
            } else {
                if ("bname".equals(property.getCode())) {
                    bname = instanceValue.getPropertyValue();
                }
            }
            instanceValue.setPropertyId(property.getId());
            instanceValue.setPropertyCode(property.getCode());
        }
        return bname;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // 起个线程去处理关系
        Runnable runnable = new RelationThread(relationDelayQueue, instanceRepository, instanceRelationRepository,
                instanceRelationService);
        Thread thread = new Thread(runnable);
        thread.start();
        logger.info("启动实例关系延迟处理线程...");

    }

}
