package com.bocloud.ims.service.builder;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.compute.ServerDriver;
import com.bocloud.cmp.driver.storage.VolumeDriver;
import com.bocloud.cmp.entity.enums.ResourceCategory;
import com.bocloud.cmp.model.IpModel;
import com.bocloud.cmp.model.NetcardOperation;
import com.bocloud.cmp.model.NetworkCardModel;
import com.bocloud.cmp.model.ServerModel;
import com.bocloud.cmp.model.VolumeModel;
import com.bocloud.cmp.model.fusionsphere.NicSpecificationModel;
import com.bocloud.common.enums.ResourceCatalog;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.RequestContext;
import com.bocloud.common.utils.IDFactory;
import com.bocloud.common.utils.ListTool;
import com.bocloud.ims.entity.resource.*;
import com.bocloud.ims.repository.resource.*;
import com.bocloud.ims.service.resource.fusionsphere.utils.FusionSphereResourceUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Company: 博云 www.bocloud.com
 * @ClassName: FusionSphereServerBuilder
 * @Description:
 * @author: zhenpingLi/李振平
 * @date: 2021/10/27 13:45
 */
@Slf4j
public class FusionSphereServerBuilder implements ServerBuilder {

    private ServerModel model;

    private RequestContext context;
    private DataStoreRepository dataStoreRepository;
    private VdcRepository vdcRepository;
    private ServerRepository serverRepository;
    private NetworkCardRepository networkCardRepository;
    private PortGroupRepository portGroupRepository;
    private CloudServerRepository cloudServerRepository;
    private VolumeRepository volumeRepository;
    private SecurityGroupRepository securityGroupRepository;
    private ServerSgroupRepository serverSgroupRepository;
    private ResourceRepository resourceRepository;
    private ResourceEventRepository resourceEventRepository;
    private ServerDriver serverDriver;
    private VolumeDriver volumeDriver;
    private CloudVendor vendor;
    private ClusterRepository clusterRepository;
    private IpRepository ipRepository;
    private IpPoolRepository ipPoolRepository;
    private FusionSphereResourceUtils resourceUtils;

    public FusionSphereServerBuilder() {
    }

    public FusionSphereServerBuilder(RequestContext context, DataStoreRepository dataStoreRepository, VdcRepository vdcRepository, ServerRepository serverRepository, NetworkCardRepository networkCardRepository, PortGroupRepository portGroupRepository,
                                     CloudServerRepository cloudServerRepository, VolumeRepository volumeRepository, SecurityGroupRepository securityGroupRepository, ServerSgroupRepository serverSgroupRepository,
                                     ResourceRepository resourceRepository, ResourceEventRepository resourceEventRepository, ServerDriver serverDriver, VolumeDriver volumeDriver, ClusterRepository clusterRepository,
                                     CloudVendor vendor, IpRepository ipRepository, IpPoolRepository ipPoolRepository, FusionSphereResourceUtils resourceUtils) {
        this.context = context;
        this.dataStoreRepository = dataStoreRepository;
        this.vdcRepository = vdcRepository;
        this.serverRepository = serverRepository;
        this.networkCardRepository = networkCardRepository;
        this.portGroupRepository = portGroupRepository;
        this.cloudServerRepository = cloudServerRepository;
        this.volumeRepository = volumeRepository;
        this.securityGroupRepository = securityGroupRepository;
        this.serverSgroupRepository = serverSgroupRepository;
        this.resourceRepository = resourceRepository;
        this.resourceEventRepository = resourceEventRepository;
        this.serverDriver = serverDriver;
        this.volumeDriver = volumeDriver;
        this.clusterRepository = clusterRepository;
        this.vendor = vendor;
        this.ipRepository = ipRepository;
        this.ipPoolRepository = ipPoolRepository;
        this.resourceUtils = resourceUtils;
    }

    @Override
    public BocloudResult<ServerModel> prepare(JSONObject object) throws Exception {
        model = new ServerModel();
        //IP地址
        List<NetcardOperation> operations =
                Optional.ofNullable(JSONObject.parseArray(object.getString("operations"), NetcardOperation.class))
                        .orElse(new ArrayList<>());
        model.setOperations(operations);
        Map<String, IpModel> ipMap = Maps.newHashMap();
        for (NetcardOperation operation : operations) {
            if (null != operation.getIp()) {
                ipMap.put(operation.getIp().getIp(), operation.getIp());
            }
        }
        try {
            model.setCreateMode(object.getString("createMode"));
            model.setCustomization(false);
            model.setIsTemplate(object.getBoolean("isTemplate"));
            switch (model.getCreateMode()) {
                case "Default":
                    log.info("builder执行默认构建VM......");
                    //操作系统和版本号
                    model.setOsCategory(object.getString("osCategory"));
                    model.setOsVersion(object.getString("osVersion"));
                    break;
                case "Template":
                    log.info("builder执行模板克隆构建虚VM......");
                    CloudServer template = cloudServerRepository.query(object.getLong("templateId"));
                    model.setUri(template.getUri());
                    model.setBusinessTemplateId(template.getId());
                    model.setPassword(object.getString("password"));
                    model.setVmHostName(object.getString("vmHostName"));
                    model.setCustomization(object.getBoolean("customization"));
                    model.setOsCategory(template.getOsCategory());
                    model.setOsVersion(template.getOsVersion());
                    break;
                case "FromServer":
                    log.info("builder执行云主机克隆构建VM......");
                    CloudServer cloudServer = cloudServerRepository.query(object.getLong("serverId"));
                    model.setUri(cloudServer.getUri());
                    model.setOsCategory(cloudServer.getOsCategory());
                    model.setOsVersion(cloudServer.getOsVersion());
                    break;
                default:
                    break;
            }
            model.setName(object.getString("name"));
            model.setRemark(object.getString("remark"));

            //站点
            Long vdcId = object.getLong("vdcId");
            Vdc vdc = vdcRepository.query(vdcId);
            model.setVdcUri(vdc.getUri());
            model.setVdcUuid(vdc.getVdcVal());

            String resourceLocation = object.getString("resourceLocation");
            if (resourceLocation.equalsIgnoreCase("cluster")) {//创建在集群下
                Long clusterId = object.getLong("clusterId");
                Cluster cluster = clusterRepository.query(clusterId);
                model.setVmlocation(cluster.getClusterVal());
            } else {//创建在主机下
                Long hostId = object.getLong("hostId");
                Server host = serverRepository.query(hostId);
                model.setVmlocation(host.getUuid());
                model.setIsBindingHost(object.getBoolean("isBindingHost"));
            }
            //vmConfig
            model.setCpu(object.getInteger("cpu"));
            model.setMemory(object.getBigDecimal("memory"));
            model.setDiskDevices(object.getJSONArray("diskDevices").toJavaList(VolumeModel.class));
            model.setNetworkCards(object.getJSONArray("networkCards").toJavaList(NetworkCardModel.class));

            // 云主机标签
            if (!StringUtils.isEmpty(object.getString("labelIds"))) {
                model.setLabelIds(JSONArray.parseArray(object.getString("labelIds"), Long.class));
            }
            //ip配置
            List<NicSpecificationModel> nicSpecificationModels = new ArrayList<>();
            for (NetcardOperation operation : operations) {
                IpModel ip = operation.getIp();
                NicSpecificationModel nicSpecification = new NicSpecificationModel();
                nicSpecification.setSequenceNum(operation.getSequenceNum());
                nicSpecification.setIpVersion(4);
                nicSpecification.setIp(ip.getIp());
                nicSpecification.setNetmask(ip.getMask());
                nicSpecification.setGateway(ip.getGateway());
                nicSpecification.setSetdns(ip.getDns());
                nicSpecificationModels.add(nicSpecification);
            }
            model.setNicSpecificationModels(nicSpecificationModels);
            return new BocloudResult<>(true, model, "success");
        } catch (Exception e) {
            for (Map.Entry<String, IpModel> entry : ipMap.entrySet()) {
                IpModel ip = entry.getValue();
                ipRepository.makeFreeById(ip.getId());
            }
            return new BocloudResult<>(false, "fail");
        }
    }

    @Override
    public BocloudResult<CloudServer> builder(CloudServer oldServer) throws Exception {

        List<NetcardOperation> operations = model.getOperations();
        Map<String, Ip> ipMap = Maps.newHashMap();
        List<String> ipList = new ArrayList<>();
        for (NetcardOperation operation : operations) {
            if (null != operation.getIp()) {
                ipMap.put(operation.getIp().getIp(),
                        JSONObject.parseObject(JSONObject.toJSONString(operation.getIp()), Ip.class));
                ipList.add(operation.getIp().getIp());
            }
        }
        List<Ip> recycleIps = new ArrayList<>(ipMap.values());

        // 创建云主机
        BocloudResult result = serverDriver.create(vendor.getUuid(), oldServer.getRegionId(), model);
        // 操作记录
        Long userId = context.getTarget();
        String handler = "云主机创建";
        ResourceEvent event = null;
        if (result.isSuccess()) {
            event = new ResourceEvent(oldServer.getId(), handler, "成功", userId, new Date(), "VM", vendor.getId(), context.getCatalog());
            ServerModel newServerModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), ServerModel.class);
            oldServer.setName(newServerModel.getName());
            oldServer.setInstanceId(newServerModel.getInstanceId());
            oldServer.setStatus(newServerModel.getStatus());
            oldServer.setPrivateIps(newServerModel.getPrivateIps());
            oldServer.setOsName(newServerModel.getOsName());
            oldServer.setOsCategory(newServerModel.getOsCategory());
            oldServer.setOsVersion(newServerModel.getOsVersion());
            oldServer.setSystemDiskCategory(newServerModel.getSystemDiskCategory());
            oldServer.setSystemDiskSize(newServerModel.getSystemDiskSize());
            oldServer.setDataDiskSize(newServerModel.getDataDisk());
            oldServer.setDisk(newServerModel.getDisk());
            oldServer.setCpu(newServerModel.getCpu());
            oldServer.setMemory(newServerModel.getMemory());
            oldServer.setRecycle(false);
            oldServer.setArch(newServerModel.getArch());
            oldServer.setUri(newServerModel.getUri());
            oldServer.setCdRomStatus(newServerModel.getCdRomStatus());
            //重新设置集群、主机id
            if (!StringUtils.isEmpty(newServerModel.getHostUuid())) {
                Long hostId = serverRepository.queryIdByUuid(newServerModel.getHostUuid());
                oldServer.setHostId(hostId);
            }
            if (!StringUtils.isEmpty(newServerModel.getClusterUuid())) {
                Cluster cluster = clusterRepository.queryByClusterVal(newServerModel.getClusterUuid(), oldServer.getVdcId());
                oldServer.setClusterId(cluster.getId());
            }
            if (model.getCreateMode().equalsIgnoreCase("Template")) {
                oldServer.setTemplateId(model.getBusinessTemplateId());
            }
            cloudServerRepository.update(oldServer);
            //先设置网卡
            this.saveNetworkCard(oldServer, newServerModel, userId);
            //在等待ip操作
            new Thread(() -> {
                try {
                    switch (model.getCreateMode()) {
                        case "Default":
                            log.info("执行默认创建获取IP......");
                            log.info("休眠5分钟......");
                            Thread.sleep(5 * 60 * 1000L);
                            break;
                        case "Template":
                            log.info("执行模板获取IP......");
                            if (model.getCustomization()) {
                                log.info("轮询等待IP中......");
                                this.waitIpTask(oldServer, ipList, ipMap, userId);
                            } else {
                                log.info("休眠5分钟......");
                                Thread.sleep(5 * 60 * 1000L);
                            }
                            break;
                        case "FromServer":
                            log.info("执行克隆获取IP......");
                            log.info("休眠5分钟......");
                            Thread.sleep(5 * 60 * 1000L);
                            break;
                        default:
                            break;
                    }
                    BocloudResult detailResult = serverDriver.detail(oldServer.getUri(), vendor.getUuid(), null);
                    ServerModel detailServerModel = JSONObject.parseObject(JSONObject.toJSONString(detailResult.getData()), ServerModel.class);
                    oldServer.setPrivateIps(detailServerModel.getPrivateIps());
                    cloudServerRepository.update(oldServer);
                    //设置fc自动分配的ip，不影响模板轮询等待ip
                    this.automaticAllocationIp(oldServer);
                    updateNetworkCard(oldServer, detailServerModel);
                    log.info("IP变更完成......");
                } catch (Exception e) {
                    log.error("IP变更失败", e);
                }
            }).start();
            // 磁盘信息
            this.saveVolume(oldServer, newServerModel, userId);
            // 保存资源
            this.saveResource(oldServer, userId);
            oldServer.setDiskDevices(volumeRepository.listByServerId(oldServer.getId()));
        } else {
            for (Ip ip : recycleIps) {
                ipRepository.makeFreeById(ip.getId());
            }
            event = new ResourceEvent(oldServer.getId(), handler, "失败", userId, new Date(), "VM", vendor.getId(), context.getCatalog());
            cloudServerRepository.remove(oldServer.getId(), context.getTarget());
        }
        resourceEventRepository.save(event);
        return result.isSuccess() ? new BocloudResult<>(true, oldServer, "success")
                : new BocloudResult<>(false, oldServer, result.getMessage());
    }

    private void saveNetworkCard(CloudServer oldServer, ServerModel serverModel, Long userId) throws Exception {
        List<NetworkCardModel> networkCards = serverModel.getNetworkCards();
        if (!CollectionUtils.isEmpty(networkCards)) {
            for (NetworkCardModel cardModel : networkCards) {
                NetworkCard card = new NetworkCard();
                card.setName(cardModel.getName());
                card.setNetworkcardUuid(cardModel.getNetworkcardUuid());
                card.setUri(cardModel.getUri());
                card.setMac(cardModel.getMac());
                card.setIpAddress(cardModel.getIpAddress());
                card.setType(cardModel.getType());
                card.setNumber(cardModel.getSequenceNum());
                card.setVringbuf(cardModel.getVringbuf());
                card.setQueues(cardModel.getQueues());
                card.setEnableSecurityGroup(cardModel.getEnableSecurityGroup());
                card.setVendorId(oldServer.getVendorId());
                card.setServerId(oldServer.getId());
                card.setCreatorId(userId);
                card.setGmtCreate(new Date());
                PortGroup portGroup = portGroupRepository.queryByUuid(cardModel.getPortGroupUuid(), oldServer.getVendorId());
                if (null != portGroup) {
                    card.setPortGroupId(portGroup.getId());
                }
                SecurityGroup securityGroup = securityGroupRepository.getByGroupId(cardModel.getSecurityGroupUuid(), oldServer.getVendorId());
                if (null != securityGroup) {
                    card.setSecurityGroupId(securityGroup.getId());
                    networkCardRepository.save(card);
                    //加入云主机和安全组绑定关系
                    ServerSgroup serverSgroup = new ServerSgroup(oldServer.getId(), securityGroup.getId(), card.getId());
                    serverSgroupRepository.save(serverSgroup);
                } else {
                    networkCardRepository.save(card);
                }

            }
        }
    }

    private void updateNetworkCard(CloudServer oldServer, ServerModel serverModel) {
        List<NetworkCardModel> networkCards = serverModel.getNetworkCards();
        if (!CollectionUtils.isEmpty(serverModel.getNetworkCards())) {
            Map<String, String> cardmodels = networkCards.stream().collect(Collectors.toMap(cardModel -> cardModel.getNetworkcardUuid(), cardModel -> cardModel.getIpAddress()));
            List<NetworkCard> cards = networkCardRepository.listByServerId(oldServer.getId());
            for (NetworkCard card : cards) {
                String ipAddress = cardmodels.get(card.getNetworkcardUuid());
                if (null != ipAddress) {
                    card.setIpAddress(ipAddress);
                    networkCardRepository.update(card);
                }
            }
        }
    }


    private void saveVolume(CloudServer oldServer, ServerModel serverModel, Long userId) throws Exception {
        List<VolumeModel> volumeModels = serverModel.getDiskDevices();
        if (!CollectionUtils.isEmpty(volumeModels)) {
            for (VolumeModel volumeModel : volumeModels) {
                Volume volume = new Volume();
                volume.setServerId(oldServer.getId());
                volume.setVendorId(oldServer.getVendorId());
                volume.setVendorType(oldServer.getVendorType());
                volume.setName(volumeModel.getName());
                volume.setUri(volumeModel.getUri());
                volume.setVolumeUuid(volumeModel.getVolumeUuid());
                volume.setSize(volumeModel.getSize());
                volume.setBootVolume(volumeModel.getBootVolume());
                volume.setPciType(volumeModel.getPciType());
                volume.setSequenceNum(volumeModel.getSequenceNum());
                volume.setIoMode(volumeModel.getIoMode());
                volume.setAccessMode(volumeModel.getAccessMode());
                volume.setStatus("IN_USE");
                volume.setType(volumeModel.getType());
                volume.setVolumeType(volumeModel.getVolumeType());
                volume.setCreatorId(userId);
                volume.setGmtCreate(new Date());
                DataStore dataStore = dataStoreRepository.getByValue(oldServer.getVdcId(), volumeModel.getDataStoreUuid());
                if (null != dataStore) {
                    volume.setDataStoreId(dataStore.getId());
                }
                volume.setTenantId(oldServer.getTenantId() == null ? 0L : oldServer.getTenantId());
                if (null != oldServer.getProjectId() && oldServer.getProjectId() > 0) {
                    volume.setProjectId(oldServer.getProjectId());
                }
                BocloudResult result = volumeDriver.detail(volumeModel.getUri(), vendor.getUuid(), null);
                if (result.isFailed()) {
                    log.error("云主机创建成功后，磁盘查询详情失败,磁盘uri：{}", volumeModel.getUri());
                } else {
                    VolumeModel newVolumeModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), VolumeModel.class);
                    volume.setAllocatedSize(newVolumeModel.getAllocatedSize());
                    volume.setThinlyProvisioned(newVolumeModel.getThinlyProvisioned());
                    volume.setIndepDisk(newVolumeModel.getIndepDisk());
                    volume.setPersistentDisk(newVolumeModel.getPersistentDisk());
                }
                volumeRepository.save(volume);
                resourceUtils.modifyDataStore(volume.getDataStoreId(),volume.getSize(),"add");
            }
        }
    }

    private void saveResource(CloudServer oldServer, Long userId) {
        List<String> ips = Optional.ofNullable(oldServer.getPrivateIps()).map(privateIps -> JSONArray.parseArray(privateIps, String.class)).orElse(new ArrayList<>());
        Resource resource = resourceRepository.query(ResourceCategory.Computer.name(), ResourceCatalog.LOGICAL.name(),
                oldServer.getId());
        if (null == resource) {
            resource = new Resource(ResourceCategory.Computer.name(), ResourceCatalog.LOGICAL.name(),
                    oldServer.getId(), JSONObject.toJSONString(ips), oldServer.getOsCategory(), vendor.getId());
            resource.setRegionId(oldServer.getRegionId());
            resource.preSave(oldServer.getName(), oldServer.getStatus(), userId, context.getTenant(),
                    context.getProject());
            resource.setInventory(JSONObject.toJSONString(oldServer));
            resourceRepository.save(resource);
        } else {
            resource.setInventory(JSONObject.toJSONString(oldServer));
            resource.setStatus(oldServer.getStatus());
            resource.setMenderId(userId);
            resource.setCreatorId(userId);
            resource.setGmtModify(new Date());
            resource.setGmtCreate(new Date());
            resource.setPrivateIps(JSONObject.toJSONString(ips));
            resource.setRegionId(oldServer.getRegionId());
            resourceRepository.update(resource);
        }
    }

    private void waitIpTask(CloudServer oldServer, List<String> ipList, Map<String, Ip> ipMap,
                            Long userId) {
        try {
            BocloudResult vmIpResult = new BocloudResult(false, "查询失败");
            for (String address : ipList) {
                vmIpResult = serverDriver.getVmIps(oldServer.getUri(), address, vendor.getUuid());
            }
            if (vmIpResult.isSuccess()) {
                ServerModel model = JSONObject.parseObject(JSONObject.toJSONString(vmIpResult.getData()), ServerModel.class);
                oldServer.setPrivateIps(model.getPrivateIps());
                oldServer.setToolsInstalled(true);
                oldServer.setToolsRunning(true);
                if (!StringUtils.isEmpty(model.getPrivateIps())) {
                    List<String> vmIps = JSONObject.parseArray(model.getPrivateIps(), String.class);
                    for (String vmIp : vmIps) {
                        if (vmIp.equals("0.0.0.0")) {
                            continue;
                        }
                        if (ipMap.containsKey(vmIp)) {
                            Ip ip = ipMap.get(vmIp);
                            ip.setCatalog("VM");
                            ip.setTarget(oldServer.getId());
                            ip.setVendorId(oldServer.getVendorId());
                            ip.setStatus(Ip.IpStatus.used);
                            ipRepository.update(ip);
                            ipMap.remove(vmIp);
                        } else {
                            List<IpPool> pools = ipPoolRepository.listByIpVersion(null);
                            Ip ip = ipRepository.checkExist(vmIp, null, vendor.getId());
                            if (null == ip) {
                                ip = new Ip(vmIp, null, null, null, vendor.getId(), IDFactory.instance().uuid(),
                                        null, Ip.IpStatus.used);
                                ip.setCatalog("VM");
                                ip.setTarget(oldServer.getId());
                                ipRepository.save(ip);
                            } else {
                                ip.setTarget(oldServer.getId());
                                ip.setStatus(Ip.IpStatus.used);
                                ip.setCatalog("VM");
                                ip.setVendorId(vendor.getId());
                                ipRepository.update(ip);
                            }
                        }
                    }
                    // 回收IP
                    for (Map.Entry<String, Ip> entry : ipMap.entrySet()) {
                        ipRepository.makeFreeById(entry.getValue().getId());
                    }
                }
                // 保存资源
                List<String> ips = Lists.newArrayList();
                if (!StringUtils.isEmpty(model.getPrivateIps())) {
                    List<String> vmIps = JSONObject.parseArray(model.getPrivateIps(), String.class);
                    for (String vmIp : vmIps) {
                        if (StringUtils.isEmpty(vmIp)) {
                            continue;
                        }
                        ips.add(vmIp);
                    }
                }
                if (!ListTool.isEmpty(ips)) {
                    oldServer.setManagerIp(ips.get(0));
                }
                cloudServerRepository.update(oldServer);
                Resource resource = resourceRepository.query(ResourceCategory.Computer.name(),
                        ResourceCatalog.LOGICAL.name(), oldServer.getId());
                if (null == resource) {
                    resource = new Resource(ResourceCategory.Computer.name(), ResourceCatalog.LOGICAL.name(),
                            oldServer.getId(), JSONObject.toJSONString(ips), oldServer.getOsCategory(),
                            vendor.getId());
                    resource.preSave(oldServer.getName(), oldServer.getStatus(), userId, context.getTenant());
                    resource.setInventory(JSONObject.toJSONString(oldServer));
                    resourceRepository.save(resource);
                } else {
                    resource.setInventory(JSONObject.toJSONString(oldServer));
                    resource.setStatus(oldServer.getStatus());
                    resource.setMenderId(userId);
                    resource.setCreatorId(userId);
                    resource.setGmtModify(new Date());
                    resource.setGmtCreate(new Date());
                    resource.setPrivateIps(JSONObject.toJSONString(ips));
                    resourceRepository.update(resource);
                }
            } else {
                // 回收IP
                for (Map.Entry<String, Ip> entry : ipMap.entrySet()) {
                    ipRepository.makeFreeById(entry.getValue().getId());
                }
            }
        } catch (Exception e) {
            log.error("Get error message:", e);
        }
    }

    private void automaticAllocationIp(CloudServer entity) {
        Map<String, Ip> ipMap = Optional
                .ofNullable(ipRepository.listByVendor(vendor.getId()))
                .map(ips -> ips.stream()
                        .collect(Collectors.toMap(ip -> ip.getIp(),
                                ip -> ip)))
                .orElse(Maps.newHashMap());

        if (!StringUtils.isEmpty(entity.getPrivateIps())) {
            List<String> vmIps = JSONObject.parseArray(entity.getPrivateIps(), String.class);
            for (String vmIp : vmIps) {
                if (vmIp.equals("0.0.0.0")) {
                    continue;
                }
                if (ipMap.containsKey(vmIp)) {
                    Ip ip = ipMap.get(vmIp);
                    ip.setCatalog("VM");
                    ip.setTarget(entity.getId());
                    ip.setVendorId(entity.getVendorId());
                    ip.setStatus(Ip.IpStatus.used);
                    ipRepository.update(ip);
                } else {
                    Ip ip = ipRepository.checkExist(vmIp, null, entity.getVendorId());
                    if (null == ip) {
                        ip = new Ip(vmIp, null, null, null, entity.getVendorId(), IDFactory.instance().uuid(),
                                null, Ip.IpStatus.used);
                        ip.setCatalog("VM");
                        ip.setTarget(entity.getId());
                        ipRepository.save(ip);
                    } else {
                        ip.setTarget(entity.getId());
                        ip.setStatus(Ip.IpStatus.used);
                        ip.setCatalog("VM");
                        ip.setVendorId(entity.getVendorId());
                        ipRepository.update(ip);
                    }
                }
            }
        }
    }

}