package com.bocloud.ims.service.transporter.vendor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.entity.enums.BocloudStatus;
import com.bocloud.cmp.entity.enums.ModuleCode;
import com.bocloud.cmp.entity.enums.ResourceCategory;
import com.bocloud.cmp.model.ElasticIpModel;
import com.bocloud.cmp.model.EnterpriseProjectModel;
import com.bocloud.cmp.model.FlavorModel;
import com.bocloud.cmp.model.HealthMonitorModel;
import com.bocloud.cmp.model.HuaweiSyncModel;
import com.bocloud.cmp.model.ImageModel;
import com.bocloud.cmp.model.KeypairModel;
import com.bocloud.cmp.model.LbListenerModel;
import com.bocloud.cmp.model.LbListenerPolicyModel;
import com.bocloud.cmp.model.LbListenerRuleModel;
import com.bocloud.cmp.model.LbMemberModel;
import com.bocloud.cmp.model.LbModel;
import com.bocloud.cmp.model.LbPoolModel;
import com.bocloud.cmp.model.NatGatewayDnatRuleModel;
import com.bocloud.cmp.model.NatGatewayModel;
import com.bocloud.cmp.model.NatGatewaySnatRuleModel;
import com.bocloud.cmp.model.PortFixedIpModel;
import com.bocloud.cmp.model.PortModel;
import com.bocloud.cmp.model.RegionModel;
import com.bocloud.cmp.model.RouteModel;
import com.bocloud.cmp.model.RouteTableModel;
import com.bocloud.cmp.model.SecurityGroupModel;
import com.bocloud.cmp.model.SecurityGroupRuleModel;
import com.bocloud.cmp.model.ServerModel;
import com.bocloud.cmp.model.ServerVolumeModel;
import com.bocloud.cmp.model.SnapshotModel;
import com.bocloud.cmp.model.SubnetModel;
import com.bocloud.cmp.model.VolumeModel;
import com.bocloud.cmp.model.VolumeTypeModel;
import com.bocloud.cmp.model.VpcModel;
import com.bocloud.cmp.model.ZoneModel;
import com.bocloud.common.enums.OSCategory;
import com.bocloud.common.enums.ResourceCatalog;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.utils.IDFactory;
import com.bocloud.common.utils.ListTool;
import com.bocloud.ims.entity.VolumeType;
import com.bocloud.ims.entity.resource.CloudServer;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.ElasticIp;
import com.bocloud.ims.entity.resource.Flavor;
import com.bocloud.ims.entity.resource.HealthMonitor;
import com.bocloud.ims.entity.resource.Image;
import com.bocloud.ims.entity.resource.Keypair;
import com.bocloud.ims.entity.resource.LbListener;
import com.bocloud.ims.entity.resource.LbListenerPolicy;
import com.bocloud.ims.entity.resource.LbListenerRule;
import com.bocloud.ims.entity.resource.LbMember;
import com.bocloud.ims.entity.resource.LbPool;
import com.bocloud.ims.entity.resource.LoadBalancer;
import com.bocloud.ims.entity.resource.NatGateway;
import com.bocloud.ims.entity.resource.NatGatewayDnatRule;
import com.bocloud.ims.entity.resource.NatGatewaySnatRule;
import com.bocloud.ims.entity.resource.NatGatewaySnatRuleRelation;
import com.bocloud.ims.entity.resource.OSTenant;
import com.bocloud.ims.entity.resource.Port;
import com.bocloud.ims.entity.resource.PortFixedIp;
import com.bocloud.ims.entity.resource.Region;
import com.bocloud.ims.entity.resource.Resource;
import com.bocloud.ims.entity.resource.Route;
import com.bocloud.ims.entity.resource.RouteTable;
import com.bocloud.ims.entity.resource.SecurityGroup;
import com.bocloud.ims.entity.resource.SecurityGroupRule;
import com.bocloud.ims.entity.resource.ServerSgroup;
import com.bocloud.ims.entity.resource.Snapshot;
import com.bocloud.ims.entity.resource.Subnet;
import com.bocloud.ims.entity.resource.Volume;
import com.bocloud.ims.entity.resource.VolumeTypeZone;
import com.bocloud.ims.entity.resource.Vpc;
import com.bocloud.ims.entity.resource.Zone;
import com.bocloud.ims.repository.NatGatewaySnatRuleRelationRepository;
import com.bocloud.ims.repository.resource.CloudServerRepository;
import com.bocloud.ims.repository.resource.ElasticIpRepository;
import com.bocloud.ims.repository.resource.FlavorRepository;
import com.bocloud.ims.repository.resource.HealthMonitorRepository;
import com.bocloud.ims.repository.resource.ImageRepository;
import com.bocloud.ims.repository.resource.KeypairRepository;
import com.bocloud.ims.repository.resource.LbListenerPolicyRepository;
import com.bocloud.ims.repository.resource.LbListenerRepository;
import com.bocloud.ims.repository.resource.LbListenerRuleRepository;
import com.bocloud.ims.repository.resource.LbMemberRepository;
import com.bocloud.ims.repository.resource.LbPoolRepository;
import com.bocloud.ims.repository.resource.LoadBalancerRepository;
import com.bocloud.ims.repository.resource.NatGatewayDnatRuleRepository;
import com.bocloud.ims.repository.resource.NatGatewayRepository;
import com.bocloud.ims.repository.resource.NatGatewaySnatRuleRepository;
import com.bocloud.ims.repository.resource.OSTenantRepository;
import com.bocloud.ims.repository.resource.PortFixedIpRepository;
import com.bocloud.ims.repository.resource.PortRepository;
import com.bocloud.ims.repository.resource.RegionRepository;
import com.bocloud.ims.repository.resource.ResourceRepository;
import com.bocloud.ims.repository.resource.RouteRepository;
import com.bocloud.ims.repository.resource.RouteTableRepository;
import com.bocloud.ims.repository.resource.SecurityGroupRepository;
import com.bocloud.ims.repository.resource.SecurityGroupRuleRepository;
import com.bocloud.ims.repository.resource.ServerSgroupRepository;
import com.bocloud.ims.repository.resource.SnapshotRepository;
import com.bocloud.ims.repository.resource.SubnetRepository;
import com.bocloud.ims.repository.resource.TagRepository;
import com.bocloud.ims.repository.resource.VolumeRepository;
import com.bocloud.ims.repository.resource.VolumeTypeRepository;
import com.bocloud.ims.repository.resource.VolumeTypeZoneRepository;
import com.bocloud.ims.repository.resource.VpcRepository;
import com.bocloud.ims.repository.resource.ZoneRepository;
import com.bocloud.ims.service.model.cmdb.CmdbInfo;
import com.bocloud.ims.service.model.cmdb.CmdbRelation;
import com.bocloud.ims.service.transportor.Transportor;
import com.bocloud.ims.service.utils.CmdbInfoConvertor;
import com.bocloud.ims.service.utils.ListUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;


/**
 * hcso平台同步类
 * @author ymh
 * @date 2022/02/25
 */
@Component("hcsoTransportor")
public class HcsoTransportor implements Transportor {

	private static Logger logger = LoggerFactory.getLogger(HcsoTransportor.class);

	@Autowired private SnapshotRepository snapshotRepository;
	@Autowired private ImageRepository imageRepository;
	@Autowired private FlavorRepository flavorRepository;
	@Autowired private CloudServerRepository cloudServerRepository;
	@Autowired private SubnetRepository subnetRepository;
	@Autowired private RegionRepository regionRepository;
	@Autowired private VolumeRepository volumeRepository;
	@Autowired private VolumeTypeRepository volumeTypeRepository;
	@Autowired private VolumeTypeZoneRepository volumeTypeZoneRepository;
	@Autowired private ResourceRepository resourceRepository;
	@Autowired private SecurityGroupRepository securityGroupRepository;
	@Autowired private SecurityGroupRuleRepository securityGroupRuleRepository;
	@Autowired private ServerSgroupRepository serverSgroupRepository;
	@Autowired private KeypairRepository keypairRepository;
	@Autowired private PortRepository portRepository;
	@Autowired private PortFixedIpRepository portFixedIpRepository;
	@Autowired private ElasticIpRepository elasticIpRepository;
	@Autowired private ZoneRepository zoneRepository;
	@Autowired private VpcRepository vpcRepository;
	@Autowired private NatGatewayRepository natGatewayRepository;
	@Autowired private NatGatewayDnatRuleRepository dnatRuleRepository;
	@Autowired private NatGatewaySnatRuleRepository snatRuleRepository;
	@Autowired private NatGatewaySnatRuleRelationRepository ruleRelationRepository;

	@Autowired private LoadBalancerRepository loadBalancerRepository;

	@Autowired private LbListenerRepository lbListenerRepository;

	@Autowired private LbPoolRepository lbPoolRepository;
	@Autowired private LbMemberRepository lbMemberRepository;
	@Autowired private HealthMonitorRepository healthMonitorRepository;

	@Autowired private LbListenerPolicyRepository lbListenerPolicyRepository;

	@Autowired private LbListenerRuleRepository lbListenerRuleRepository;

	@Autowired private TagRepository tagRepository;

	@Autowired private OSTenantRepository osTenantRepository;

	@Autowired private RouteTableRepository routeTableRepository;
	@Autowired private RouteRepository routeRepository;

	@Override
	public BocloudResult sync(CloudVendor vendor, Object data, Region region, Long userId, List<CmdbInfo> infos) {
		try {
			if (null != data) {
				if (cloudServerRepository.hasBuilding(vendor.getId())) {
					return new BocloudResult(false, "该平台下有云主机正在创建，请稍后进行同步操作");
				}
				Long vendorId = vendor.getId();
				String content = JSONObject.toJSONString(data);
				HuaweiSyncModel model = JSONObject.parseObject(content, HuaweiSyncModel.class);
				// 同步可用区域
				logger.info("Starting sync region......");
				this.syncRegions(model.getRegions(), vendor, userId, region.getRegionId());
				List<Zone> zoneList = zoneRepository.listByRegionId(region.getRegionId(), vendorId);
				Map<String, Long> zoneMap = new HashMap<>(8);
				for (Zone zone : zoneList) {
					zoneMap.put(zone.getZoneId(), zone.getId());
				}
				logger.info("End sync region......");

				// 同步vpc
				logger.info("Starting sync vpc......");
				this.syncVpc(model.getVpcModels(), vendor.getId(), userId, region.getRegionId());
				Map<String, Long> vpcMap = new HashMap<>(8);
				List<Vpc> vpcList = vpcRepository.list(vendorId, region.getRegionId());
				for (Vpc vpc : vpcList) {
					vpcMap.put(vpc.getVpcId(), vpc.getId());
				}
				Map<String, Long> subnetMap = new HashMap<>(8);
				Map<String, Subnet> neutronSubnetMap = new HashMap<>(8);
				List<Subnet> subnetList = subnetRepository.listByRegion(vendorId, region.getRegionId());
				for (Subnet subnet : subnetList) {
					subnetMap.put(subnet.getSubnetUuid(), subnet.getId());
					neutronSubnetMap.put(subnet.getNeutronSubnetUuid(), subnet);
				}
				logger.info("End sync vpc......");
				// 同步端口
				logger.info("Starting sync port......");
				this.syncPort(model.getPortModels(), region.getRegionId(), vendorId, userId);
				Map<String, Long> portMap = new HashMap<>(8);
				List<Port> ports = portRepository.listByVid(vendorId, region.getRegionId());
				for (Port port : ports) {
					portMap.put(port.getPortUuid(), port.getId());
				}
				logger.info("End sync port...");
				// 同步弹性IP
				logger.info("Starting sync elastic ip......");
				this.syncElasticIp(model.getElasticIpModels(), region.getRegionId(), vendorId, userId);
				Map<String, Long> elasticIpMap = new HashMap<>(8);
				List<ElasticIp> floatingIps = elasticIpRepository.listByVid(vendorId, region.getRegionId());
				for (ElasticIp elasticIp : floatingIps) {
					elasticIpMap.put(elasticIp.getElasticIpUuid(), elasticIp.getId());
				}
				logger.info("End sync elastic ip...");

//				logger.info("Starting sync bandwidth......");
//				this.syncBandwidth(model.getBandwidthModels(), region.getRegionId(), vendorId, userId);
//				logger.info("End sync bandwidth...");
				// 同步安全组
				logger.info("Starting sync security group......");
				this.syncSecurityGroup(model.getGroupModels(), vpcMap, vendorId, userId, region.getRegionId());
				Map<String, Long> securityGroupMap = new HashMap<>(8);
				List<SecurityGroup> securityGroups = securityGroupRepository.listByVendorId(vendorId, region.getRegionId());
				for (SecurityGroup securityGroup : securityGroups) {
					securityGroupMap.put(securityGroup.getGroupUuid(), securityGroup.getId());
				}
				logger.info("End sync security group......");
				// 同步云主机
				logger.info("Starting sync server......");
				Map<String, CloudServer> serverMap = new HashMap<>(8);
				this.syncServer(model.getServerModels(), vendor, userId, region, vendor.getType(), serverMap, infos);
				Map<String, CloudServer> sMap = new HashMap<>(8);
				List<CloudServer> serverByVid = cloudServerRepository.listByVid(vendor.getId(), region.getRegionId());
				for (CloudServer cloudServer : serverByVid) {
					sMap.put(cloudServer.getInstanceId(), cloudServer);
				}
				logger.info("End sync server......");
				// 同步镜像
				Map<String, Image> imageMap = Maps.newHashMap();
				logger.info("Starting sync image......");
				this.syncImage(model.getImageModels(), vendorId, region.getRegionId(), userId, vendor.getType(),
					imageMap);
				logger.info("End sync image......");
				// 同步云硬盘类型
				logger.info("Starting sync volume type......");
				this.syncVolumeType(model.getVolumeTypeModels(), vendorId, region.getRegionId(), userId, zoneMap);
				logger.info("End sync volume type......");
				// 同步云硬盘
				logger.info("Starting sync volume......");
				this.syncVolume(model.getVolumeModels(), vendorId, region.getRegionId(), userId, sMap);
				logger.info("End sync volume......");
				// 获取云硬盘信息
				Map<String, Volume> volumeMap = Maps.newHashMap();
				List<Volume> volumes = volumeRepository.listByVendorId(vendorId);
				for (Volume volume : volumes) {
					volumeMap.put(volume.getVolumeUuid(), volume);
				}
				// 同步快照
				logger.info("Starting sync snapshot......");
				this.syncSnapshot(model.getSnapshotModels(), vendorId, userId, region.getRegionId(), volumeMap);
				logger.info("End sync snapshot......");
				// 同步规格
				logger.info("Starting sync flavor......");
				this.syncFlavor(model.getFlavorModels(), vendorId, userId, region.getRegionId());
				logger.info("End sync flavor......");
				// 同步密钥
				logger.info("Starting sync keypair......");
				this.syncKeypair(model.getKeypairModels(), region.getRegionId(), vendorId, userId);
				logger.info("End sync keypair...");

				// 同步nat网关
				logger.info("Starting sync nat gateway......");
				this.syncNatGateway(model.getNatGatewayModels(), region.getRegionId(), vendorId, userId, vpcMap,
					subnetMap);
				Map<String, Long> natGatewayMap = new HashMap<>(8);
				List<NatGateway> natGateways = natGatewayRepository.listByVendorId(vendorId, region.getRegionId());
				for (NatGateway natGateway : natGateways) {
					natGatewayMap.put(natGateway.getUuid(), natGateway.getId());
				}
				logger.info("End sync nat gateway......");

				// 同步nat网关dnat规则
				logger.info("Starting sync nat gateway dnat......");
				this.syncNatGatewayDnatRule(model.getDnatRuleModels(), region.getRegionId(), vendorId, userId,
					natGatewayMap, elasticIpMap, portMap);
				logger.info("End sync nat gateway dnat......");

				// 同步nat网关snat规则
				logger.info("Starting sync nat gateway snat......");
				this.syncNatGatewaySnatRule(model.getSnatRuleModels(), region.getRegionId(), vendorId, userId,
					natGatewayMap, elasticIpMap, subnetMap);
				logger.info("End sync nat gateway snat......");

				// 同步负载均衡
				logger.info("Starting sync lb......");
				this.syncLoadBalancer(model.getLbModels(), vpcMap, neutronSubnetMap, vendor.getId(), userId, region.getRegionId(), subnetMap, elasticIpMap);
				List<LoadBalancer> balancers = loadBalancerRepository.listByVid(vendor.getId(), region.getRegionId());
				Map<String, Long> balancerMap = Maps.newHashMap();
				for (LoadBalancer balancer : balancers) {
					balancerMap.put(balancer.getLbUuid(), balancer.getId());
				}
				logger.info("End sync lb......");

				// 同步侦听器
				logger.info("Starting sync listener......");
				this.syncLbListener(model.getLbListenerModels(), balancerMap, vendor.getId(), userId, region.getRegionId());
				List<LbListener> lbListeners = lbListenerRepository.listByVid(vendor.getId(), region.getRegionId());
				Map<String, Long> listenerMap = Maps.newHashMap();

				for (LbListener listener : lbListeners) {
					listenerMap.put(listener.getListenerUuid(), listener.getId());
				}
				logger.info("End sync lb listener......");

				// 后端云服务器组
				logger.info("Starting sync lb pool......");
				this.syncLbPool(model.getLbPoolModels(), listenerMap, balancerMap, vendor.getId(), userId, region.getRegionId());
				List<LbPool> targetGroups = lbPoolRepository.listByVid(vendor.getId(), region.getRegionId());
				Map<String, Long> tgMap = Maps.newHashMap();

				Map<String, LbPool> lbPoolMap = Maps.newHashMap();
				for (LbPool group : targetGroups) {
					tgMap.put(group.getPoolUuid(), group.getId());
					lbPoolMap.put(group.getPoolUuid(), group);
				}
				logger.info("End sync lb pool......");
				// 后端云服务器
				logger.info("Starting sync lb member......");
				this.syncLbMember(model.getLbMemberModels(), lbPoolMap, neutronSubnetMap, vendor.getId(), userId, region.getRegionId());
				logger.info("End sync lb member......");

				// 健康检查
				logger.info("Starting sync Health Monitor......");
				this.syncHealthMonitor(model.getHealthMonitorModels(), lbPoolMap, vendor.getId(), userId, region.getRegionId());
				logger.info("End sync Health Monitor......");

				// 转发策略
				logger.info("Starting sync Listener Policy......");
				this.syncL7policy(model.getLbL7PolicyModels(), tgMap, listenerMap, vendor.getId(), userId, region.getRegionId());
				logger.info("End sync Listener Policy......");

				List<LbListenerPolicy> lbL7PolicyList = lbListenerPolicyRepository.listByVid(vendor.getId(), region.getRegionId());
				Map<String, Long> l7PolicyMap = Maps.newHashMap();

				for (LbListenerPolicy group : lbL7PolicyList) {
					l7PolicyMap.put(group.getPolicyUuid(), group.getId());
				}
				// 转发规则
				logger.info("Starting sync Listener Rule......");
				this.syncL7rule(model.getLbL7RuleModels(), l7PolicyMap, vendor.getId(), userId, region.getRegionId());
				logger.info("End sync Listener Rule......");

//				// 转发规则
//				logger.info("Starting sync ceratificate......");
//				this.syncCeratificate(model.getCertificateModels(), vendor.getId(), userId, region.getRegionId());
//				logger.info("End sync ceratificate......");
//
//				// ip地址组
//				logger.info("Starting sync ipGroup......");
//				this.syncIpGroup(model.getIpGroupModels(), vendor.getId(), userId, region.getRegionId());
//				logger.info("End sync ipGroup......");

//				// 同步华为存储库
//				logger.info("statr sync Vaults...");
//				this.syncBackupVaults(model.getVaultsModels(), vendor.getId(), userId, region.getRegionId(), volumeMap,
//					sMap);
//				List<BackupVaults> vaultslist = backupVaultsRepository.list(vendor.getId(), region.getRegionId());
//				Map<String, BackupVaults> vaultsMap = Maps.newHashMap();
//
//				for (BackupVaults vaults : vaultslist) {
//					vaultsMap.put(vaults.getVaultsUuid(), vaults);
//				}
//				logger.info("statr sync Vaults... END");
//
//				// 同步华为备份策略
//				logger.info("statr sync backup policy...");
//				this.syncBackupPolicys(model.getBackupPolicyModels(), vendor.getId(), userId, region.getRegionId());
//				logger.info("statr sync backup policy... END");
//
//				// 同步华为存储resource
//				logger.info("statr sync Backup...");
//				this.syncBackupResources(model.getBackupModels(), vendor.getId(), userId, region.getRegionId(),
//					vaultsMap);
//				logger.info("statr sync Backup... END");

//				// 同步华为备份策略
//				logger.info("statr sync backup log...");
//				this.syncBackupLogs(model.getLogModels(), vendor.getId(), userId, region.getRegionId());
//				logger.info("statr sync backup log... END");
//
//				// 同步华为存储resource
//				logger.info("statr sync bucket...");
//				this.syncBuckets(model.getBucketModels(), vendor.getId(), userId, region.getRegionId());
//				logger.info("statr sync bucket... END");

				// 同步企业项目
				logger.info("statr sync EnterpriseProject...");
				this.syncEnterpriseProject(model.getEnterpriseProjectModels(), vendor.getId(), userId, region.getRegionId());
				Map<String, Long> projectMap = new HashMap<>(8);
				List<OSTenant> projects = osTenantRepository.listByVid(vendorId);
				for (OSTenant osTenant : projects) {
					projectMap.put(osTenant.getTenantUuid(), osTenant.getId());
				}
				logger.info("statr sync EnterpriseProject... END");

//				// 同步云数据库
//				logger.info("statr sync CloudRds...");
//				this.syncCloudRds(model.getDbInstanceModels(), vpcMap, subnetMap, securityGroupMap, projectMap, region.getRegionId(), vendor.getId(), userId);
//				Map<String, CloudRds> rdsMap = new HashMap<>(8);
//				List<CloudRds> cloudRds = cloudRdsRepository.listByVid(vendorId, region.getRegionId());
//				for (CloudRds rds : cloudRds) {
//					rdsMap.put(rds.getUuid(), rds);
//				}
//				logger.info("statr sync CloudRds... END");
//
//				// 同步云数据库备份
//				logger.info("statr sync CloudRds backup...");
//				this.syncRdsBackup(model.getDbBackupModels(), rdsMap, region.getRegionId(), vendor.getId(), userId);
//				logger.info("statr sync CloudRds backup... END");
//
//				// 同步云数据库模板
//				logger.info("statr sync CloudRdsConfiguration...");
//				this.syncCloudRdsConfiguration(model.getDbConfigurationModels(), region.getRegionId(), vendor.getId(),
//					userId);
//				logger.info("statr sync CloudRdsConfiguration... END");
//
//				// 同步云数据库规格
//				logger.info("statr sync CloudRdsFlavor...");
//				this.syncCloudRdsFlavor(model.getDbFlavorModels(), region.getRegionId(), vendor.getId(), userId);
//				logger.info("statr sync CloudRdsFlavor... END");
//
//				// 同步云数据库磁盘
//				logger.info("statr sync CloudRdsStorage...");
//				this.syncCloudRdsStorage(model.getDbStorageModels(), region.getRegionId(), vendor.getId(), userId);
//				logger.info("statr sync CloudRdsStorage... END");
//
//				// 同步云数据库版本
//				logger.info("statr sync CloudRdsVersion...");
//				this.syncCloudRdsVersion(model.getDbVersionModels(), region.getRegionId(), vendor.getId(), userId);
//				logger.info("statr sync CloudRdsVersion... END");
//
//				// 获取租户配额存入redis缓存
//				logger.info("statr sync HUAWEI QuoteInfo...");
//				BocloudResult quoteInfo = cloudVendorService.getQuoteInfo(vendorId);
//				if (quoteInfo.isSuccess() && null != quoteInfo.getData()) {
//					redisTemplate.opsForValue().set("HUAWEI-QuoteInfo-" + vendorId, JSONObject.toJSONString(quoteInfo.getData()));
//				}
//				logger.info("statr sync HUAWEI QuoteInfo... END");
//
//				// 同步华为预定义标签
//				logger.info("statr sync predefine tags ...");
//				this.syncPredefineTags(model.getTagModels(), region.getRegionId(), vendor.getId(), userId);
//				logger.info("statr sync predefine tags ... END");
//
//				// 同步对等连接
//				logger.info("statr sync vpcpeering ...");
//				this.syncVpcPeerings(model.getVpcPeeringModels(), region.getRegionId(), vendor.getId(), userId);
//				logger.info("statr sync vpcpeering ... END");
//
//				// 同步路由条目
//				logger.info("statr sync routeTable ...");
//				this.syncRouteTables(model.getRouteTableModels(), vendorId, userId, vpcMap, region.getRegionId());
//				logger.info("statr sync routeTable ... END");
//
//				// 同步云服务器组
//				logger.info("statr sync cloudservergroup ...");
//				this.syncCloudServerGroups(model.getCloudServerGroupModels(), region.getRegionId(), vendor.getId(),
//					userId);
//				logger.info("statr sync cloudservergroup ... END");
//
//				// 同步云ACL
//				logger.info("statr sync firewall ...");
//				this.syncFirewall(model.getFirewallModels(), region.getRegionId(), vendor.getId(), userId);
//				logger.info("statr sync firewall ... END");
//				List<Firewall> allFirewalls = firewallRepository.listByVid(vendorId, region.getRegionId());
//				Map<String, Firewall> firewallMap = Maps.newHashMap();
//				for (Firewall firewall : allFirewalls) {
//					firewallMap.put(firewall.getIngressFirewallPolicy(), firewall);
//					firewallMap.put(firewall.getEgressFirewallPolicy(), firewall);
//				}
//				// 同步云ACL 规则
//				logger.info("statr sync firewall rule ...");
//				this.syncFirewallRule(model.getFirewallRuleModels(), region.getRegionId(), vendor, userId);
//				logger.info("statr sync firewall rule ... END");
//				List<FirewallRule> firewallRules = firewallRuleRepository.listByVid(vendorId);
//				Map<String, FirewallRule> firewallRuleMap = firewallRules.stream()
//						.collect(Collectors.toMap(FirewallRule::getRuleUuid, Function.identity(), (key1, key2) -> key2));
//				// 同步云ACL 策略
//				logger.info("statr sync firewall policy ...");
//				this.syncFirewallPolicy(model.getFirewallPolicyModels(), region.getRegionId(), vendor, userId, firewallRuleMap, firewallMap);
//				logger.info("statr sync firewall policy ... END");
//				
//				
//				
//				
//				//同步HCSO 容器镜像服务
//	            logger.info("Starting sync 容器镜像服务......");
//	            syncContainerImage(model.getContainerImages(), vendor, userId);
//	            logger.info("End sync hcso 容器镜像服务......");
//
//	            //同步HCSO 集群管理数据
//	            logger.info("Starting sync hcso 集群管理......");
//	            this.syncCluster(model.getHcsoClusterModels(), vendor, userId);
//	            logger.info("End sync hcso 集群管理......");
//
//	            //同步HCSO 节点管理数据
//	            logger.info("Starting sync hcso 节点管理......");
//	            this.syncClusterNode(model.getClusterNodeModels(), vendor, userId, sMap);
//	            logger.info("End sync hcso 节点管理......");
//
//	            logger.info("Starting sync hcso 节点池管理......");
//	            this.syncClusterNodePool(model.getClusterNodepoolsModels(), vendor, userId);
//	            logger.info("End sync hcso 节点池管理......");
//
//	            logger.info("Starting sync hcso cce网络管理service......");
//	            this.syncClusterServices(model.getClusterServices(), vendor, userId);
//	            logger.info("End sync hcso cce网络管理service......");
//
//	            logger.info("Starting sync hcso cce网络管理service......");
//	            this.syncClusterIngress(model.getClusterIngress(), vendor, userId);
//	            logger.info("End sync hcso cce网络管理service......");
//
//	            logger.info("Starting sync hcso cce网络管理service......");
//	            this.syncClusterNetworkpolicy(model.getClusterNetworkpolicy(), vendor, userId);
//	            logger.info("End sync hcso cce网络管理service......");
//
//	            logger.info("Starting sync hcso cce命名空间......");
//	            this.syncClusterNameSpace(model.getNamespaces(), vendor, userId);
//	            logger.info("End sync hcso cce命名空间......");
//
//	            logger.info("Starting sync hcso 云容器镜像组织......");
//	            this.syncSwrNamepace(model.getSwrNamespaceModels(), vendor, userId);
//	            logger.info("End sync hcso 云容器镜像组织......");
//
//	            logger.info("Starting sync hcso IAM用户......");
//	            this.syncHcsoUser(model.getHcsoUserModels(), vendor, userId);
//	            logger.info("End sync hcso IAM用户......");
//	            
//	            //同步HCSO  弹性伸缩
//	            logger.info("Starting sync hcso 弹性伸缩......");
//	            this.syncScalingGroups(model.getScalingGroupModels(), vendor, userId);
//	            logger.info("End sync hcso 弹性伸缩......");
//
//	            //同步HCSO  伸缩策略
//	            logger.info("Starting sync hcso 伸缩策略......");
//	            this.syncScalingPolicies(model.getScalingPoliciesModels(), vendor, userId);
//	            logger.info("End sync hcso 伸缩策略......");
//
//	            //同步HCSO  伸缩策略
//	            logger.info("Starting sync hcso 伸缩配置......");
//	            this.syncScalingConfiguration(model.getScalingConfigurationModels(), vendor, userId);
//	            logger.info("End sync hcso 伸缩配置......");

	            
			}
			return new BocloudResult(true, "云平台【" + vendor.getName() + "】平台数据同步成功");
		} catch (Exception e) {
			logger.error("Sync HuaweiTransportor error:{}", e);
			return new BocloudResult(false, "云平台【" + vendor.getName() + "】平台数据同步失败:" + e.getMessage());
		}
	}
	
	//syncScalingGroups
//    private void syncScalingGroups(List<ScalingGroupModel> scalingGroupModels, CloudVendor vendor, Long userId) throws Exception {
//        if (scalingGroupModels == null) {
//            return;
//        }
//
//        if (scalingGroupModels.isEmpty()) {
//            hcsoScalingGroupRepository.removeByVid(vendor.getId(), userId);
//            return;
//        }
//
//        // 获取平台 所有as信息
//        List<ScalingGroup> scalingGroups = hcsoScalingGroupRepository.listByVendorId(vendor.getId());
//        Map<String, ScalingGroup> scalingGroupMap = Maps.newHashMap();
//        for (ScalingGroup scalingGroup : scalingGroups) {
//            scalingGroupMap.put(scalingGroup.getScaling_group_id(), scalingGroup);
//        }
//
//        for (ScalingGroupModel scalingGroupModel : scalingGroupModels) {
//            ScalingGroup scalingGroup = null;
//            if (scalingGroupMap.containsKey(scalingGroupModel.getScaling_group_id())) {//update
//                scalingGroup = scalingGroupMap.get(scalingGroupModel.getScaling_group_id());
//                BeanUtils.copyProperties(scalingGroupModel, scalingGroup);
//                hcsoScalingGroupRepository.update(scalingGroup);
//                scalingGroupMap.remove(scalingGroupModel.getScaling_group_id());
//                continue;
//            }
//            //新增
//            scalingGroup = new ScalingGroup();
//            BeanUtils.copyProperties(scalingGroupModel, scalingGroup);
//            scalingGroup.setVendorId(vendor.getId());
//            hcsoScalingGroupRepository.save(scalingGroup);
//            scalingGroupMap.remove(scalingGroupModel.getScaling_group_id());
//        }
//
//        //删除
//        //删除
//        for (Map.Entry<String, ScalingGroup> entry : scalingGroupMap.entrySet()) {
//            ScalingGroup scalingGroup = entry.getValue();
//            hcsoScalingGroupRepository.remove(ScalingGroup.class, scalingGroup.getId());
//        }
//
//    }
//
//    private void syncScalingPolicies(List<ScalingPoliciesModel> scalingPoliciesModels, CloudVendor vendor, Long userId) throws Exception {
//        if (scalingPoliciesModels == null) {
//            return;
//        }
//
//        if (scalingPoliciesModels.isEmpty()) {
//            hcsoScalingPoliciesRepository.removeByVid(vendor.getId(), userId);
//            return;
//        }
//
//        // 获取平台 所有as信息
//        List<ScalingPolicies> scalingPolicies = hcsoScalingPoliciesRepository.listByVendorId(vendor.getId());
//        Map<String, ScalingPolicies> scalingPoliciesMap = Maps.newHashMap();
//        for (ScalingPolicies scalingPolicie : scalingPolicies) {
//            scalingPoliciesMap.put(scalingPolicie.getScaling_policy_id(), scalingPolicie);
//        }
//
//        for (ScalingPoliciesModel scalingPoliciesModel : scalingPoliciesModels) {
//            ScalingPolicies scalingPolicies1 = null;
//            if (scalingPoliciesMap.containsKey(scalingPoliciesModel.getScaling_policy_id())) {//update
//                scalingPolicies1 = scalingPoliciesMap.get(scalingPoliciesModel.getScaling_policy_id());
//                BeanUtils.copyProperties(scalingPoliciesModel, scalingPolicies1);
//                hcsoScalingPoliciesRepository.update(scalingPolicies1);
//                scalingPoliciesMap.remove(scalingPoliciesModel.getScaling_policy_id());
//                continue;
//            }
//            //新增
//            scalingPolicies1 = new ScalingPolicies();
//            BeanUtils.copyProperties(scalingPoliciesModel, scalingPolicies1);
//            scalingPolicies1.setVendorId(vendor.getId());
//            hcsoScalingPoliciesRepository.save(scalingPolicies1);
//            scalingPoliciesMap.remove(scalingPoliciesModel.getScaling_policy_id());
//        }
//
//        //删除
//        for (Map.Entry<String, ScalingPolicies> entry : scalingPoliciesMap.entrySet()) {
//            ScalingPolicies scalingPolicie = entry.getValue();
//            hcsoScalingPoliciesRepository.remove(ScalingPolicies.class, scalingPolicie.getId());
//        }
//
//    }
//
//    private void syncScalingConfiguration(List<ScalingConfigurationModel> scalingConfigurationModels, CloudVendor vendor, Long userId) throws Exception {
//        if (scalingConfigurationModels == null) {
//            return;
//        }
//
//        if (scalingConfigurationModels.isEmpty()) {
//            hcsoScalingConfigurationRepository.removeByVid(vendor.getId(), userId);
//            return;
//        }
//
//        // 获取平台 所有as信息
//        List<ScalingConfiguration> scalingConfigurations = hcsoScalingConfigurationRepository.listByVendorId(vendor.getId());
//        Map<String, ScalingConfiguration> scalingConfigurationsMap = Maps.newHashMap();
//        for (ScalingConfiguration scalingConfiguration : scalingConfigurations) {
//            scalingConfigurationsMap.put(scalingConfiguration.getScaling_configuration_id(), scalingConfiguration);
//        }
//
//        for (ScalingConfigurationModel scalingConfigurationModel : scalingConfigurationModels) {
//            ScalingConfiguration scalingConfiguration = null;
//            if (scalingConfigurationsMap.containsKey(scalingConfigurationModel.getScaling_configuration_id())) {//update
//                scalingConfiguration = scalingConfigurationsMap.get(scalingConfigurationModel.getScaling_configuration_id());
//                BeanUtils.copyProperties(scalingConfigurationModel, scalingConfiguration);
//                hcsoScalingConfigurationRepository.update(scalingConfiguration);
//                scalingConfigurationsMap.remove(scalingConfigurationModel.getScaling_configuration_id());
//                continue;
//            }
//            //新增
//            scalingConfiguration = new ScalingConfiguration();
//            BeanUtils.copyProperties(scalingConfigurationModel, scalingConfiguration);
//            scalingConfiguration.setVendorId(vendor.getId());
//            hcsoScalingConfigurationRepository.save(scalingConfiguration);
//            scalingConfigurationsMap.remove(scalingConfigurationModel.getScaling_configuration_id());
//        }
//
//        //删除
//        for (Map.Entry<String, ScalingConfiguration> entry : scalingConfigurationsMap.entrySet()) {
//            ScalingConfiguration scalingConfiguration = entry.getValue();
//            hcsoScalingConfigurationRepository.remove(ScalingConfiguration.class, scalingConfiguration.getId());
//        }
//
//    }
//
//	
//	private void syncClusterIngress(List<NetworkModel> networkModels, CloudVendor vendor, Long userId) throws Exception {
//        if (networkModels == null) {
//            return;
//        }
//
//        if (networkModels.isEmpty()) {
//            hcsoClusterNetworkIngressRepository.removeByVid(vendor.getId(), userId);
//            return;
//        }
//
//        // 获取平台 规格 信息
//        List<NetworkIngress> networkIngresses = hcsoClusterNetworkIngressRepository.listByVendorId(vendor.getId());
//        Map<String, NetworkIngress> networkIngressMap = Maps.newHashMap();
//        for (NetworkIngress networkIngress : networkIngresses) {
//            networkIngressMap.put(networkIngress.getUid(), networkIngress);
//        }
//
//        for (NetworkModel networkModel : networkModels) {
//            NetworkIngress networkIngress = null;
//            if (networkIngressMap.containsKey(networkModel.getUid())) {//update
//                networkIngress = networkIngressMap.get(networkModel.getUid());
//                BeanUtils.copyProperties(networkModel, networkIngress);
//                hcsoClusterNetworkIngressRepository.update(networkIngress);
//                networkIngressMap.remove(networkModel.getUid());
//                continue;
//            }
//
//            //新增
//            networkIngress = new NetworkIngress();
//            BeanUtils.copyProperties(networkModel, networkIngress);
//            networkIngress.setVendorId(vendor.getId());
//            hcsoClusterNetworkIngressRepository.save(networkIngress);
//            networkIngressMap.remove(networkModel.getUid());
//        }
//
//
//        //删除
//        for (Map.Entry<String, NetworkIngress> entry : networkIngressMap.entrySet()) {
//            NetworkIngress networkIngress = entry.getValue();
//            hcsoClusterNetworkIngressRepository.remove(NetworkIngress.class, networkIngress.getId());
//
//        }
//
//    }
//	
//	private void syncClusterNetworkpolicy(List<NetworkModel> networkModels, CloudVendor vendor, Long userId) throws Exception {
//        if (networkModels == null) {
//            return;
//        }
//
//        if (networkModels.isEmpty()) {
//            hcsoClusterNetworkNetworkPolicyRepository.removeByVid(vendor.getId(), userId);
//            return;
//        }
//
//        // 获取平台 规格 信息
//        List<NetworkNetworkPolicy> clusterNodePools = hcsoClusterNetworkNetworkPolicyRepository.listByVendorId(vendor.getId());
//        Map<String, NetworkNetworkPolicy> networkNetworkPolicyMap = Maps.newHashMap();
//        for (NetworkNetworkPolicy networkNetworkPolicy : clusterNodePools) {
//            networkNetworkPolicyMap.put(networkNetworkPolicy.getUid(), networkNetworkPolicy);
//        }
//
//        for (NetworkModel networkModel : networkModels) {
//            NetworkNetworkPolicy networkNetworkPolicy = null;
//            if (networkNetworkPolicyMap.containsKey(networkModel.getUid())) {//update
//                networkNetworkPolicy = networkNetworkPolicyMap.get(networkModel.getUid());
//                BeanUtils.copyProperties(networkModel, networkNetworkPolicy);
//                hcsoClusterNetworkNetworkPolicyRepository.update(networkNetworkPolicy);
//                networkNetworkPolicyMap.remove(networkModel.getUid());
//                continue;
//            }
//
//            //新增
//            networkNetworkPolicy = new NetworkNetworkPolicy();
//            BeanUtils.copyProperties(networkModel, networkNetworkPolicy);
//            networkNetworkPolicy.setVendorId(vendor.getId());
//            hcsoClusterNetworkNetworkPolicyRepository.save(networkNetworkPolicy);
//            networkNetworkPolicyMap.remove(networkModel.getUid());
//        }
//
//
//        //删除
//        for (Map.Entry<String, NetworkNetworkPolicy> entry : networkNetworkPolicyMap.entrySet()) {
//            NetworkNetworkPolicy networkNetworkPolicy = entry.getValue();
//            hcsoClusterNetworkNetworkPolicyRepository.remove(NetworkNetworkPolicy.class, networkNetworkPolicy.getId());
//
//        }
//
//    }
//	
//	private void syncClusterNameSpace(List<ClusterNodepoolsModel> nameSpacesModels, CloudVendor vendor, Long userId) throws Exception {
//        if (nameSpacesModels == null) {
//            return;
//        }
//
//        if (nameSpacesModels.isEmpty()) {
//            hcsoClusterNameSpaceRepository.removeByVid(vendor.getId(), userId);
//            return;
//        }
//
//        // 获取平台 规格 信息
//        List<NameSpace> nameSpaces = hcsoClusterNameSpaceRepository.listByVendorId(vendor.getId());
//        Map<String, NameSpace> nameSpaceMap = Maps.newHashMap();
//        for (NameSpace nameSpace : nameSpaces) {
//            nameSpaceMap.put(nameSpace.getUid(), nameSpace);
//        }
//
//        for (ClusterNodepoolsModel nameSpaceModel : nameSpacesModels) {
//            NameSpace nameSpace = null;
//            if (nameSpaceMap.containsKey(nameSpaceModel.getUid())) {//update
//                nameSpace = nameSpaceMap.get(nameSpaceModel.getUid());
//                BeanUtils.copyProperties(nameSpaceModel, nameSpace);
//                hcsoClusterNameSpaceRepository.update(nameSpace);
//                nameSpaceMap.remove(nameSpaceModel.getUid());
//                continue;
//            }
//
//            //新增
//            nameSpace = new NameSpace();
//            BeanUtils.copyProperties(nameSpaceModel, nameSpace);
//            nameSpace.setVendorId(vendor.getId());
//            nameSpace.setTenantId(0L);
//            hcsoClusterNameSpaceRepository.save(nameSpace);
//            nameSpaceMap.remove(nameSpaceModel.getUid());
//        }
//
//
//        //删除
//        for (Map.Entry<String, NameSpace> entry : nameSpaceMap.entrySet()) {
//            NameSpace nameSpace = entry.getValue();
//            hcsoClusterNameSpaceRepository.remove(NameSpace.class, nameSpace.getId());
//
//        }
//
//    }
//	
//	private void syncClusterServices(List<NetworkModel> networkModels, CloudVendor vendor, Long userId) throws Exception {
//        if (networkModels == null) {
//            return;
//        }
//
//        if (networkModels.isEmpty()) {
//            hcsoClusterNetworkServiceRepository.removeByVid(vendor.getId(), userId);
//            return;
//        }
//
//        // 获取平台 规格 信息
//        List<NetworkService> clusterNodePools = hcsoClusterNetworkServiceRepository.listByVendorId(vendor.getId());
//        Map<String, NetworkService> networkServiceMap = Maps.newHashMap();
//        for (NetworkService networkService : clusterNodePools) {
//            networkServiceMap.put(networkService.getUid(), networkService);
//        }
//
//        for (NetworkModel networkModel : networkModels) {
//            NetworkService networkService = null;
//            if (networkServiceMap.containsKey(networkModel.getUid())) {//update
//                networkService = networkServiceMap.get(networkModel.getUid());
//                BeanUtils.copyProperties(networkModel, networkService);
//                hcsoClusterNetworkServiceRepository.update(networkService);
//                networkServiceMap.remove(networkModel.getUid());
//                continue;
//            }
//
//            //新增
//            networkService = new NetworkService();
//            BeanUtils.copyProperties(networkModel, networkService);
//            networkService.setVendorId(vendor.getId());
//            hcsoClusterNetworkServiceRepository.save(networkService);
//            networkServiceMap.remove(networkModel.getUid());
//        }
//
//
//        //删除
//        for (Map.Entry<String, NetworkService> entry : networkServiceMap.entrySet()) {
//            NetworkService networkService = entry.getValue();
//            hcsoClusterNetworkServiceRepository.remove(NetworkService.class, networkService.getId());
//
//        }
//
//    }
//	
//	private void syncClusterNodePool(List<ClusterNodepoolsModel> clusterNodepoolsModels, CloudVendor vendor, Long userId) throws Exception {
//        if (clusterNodepoolsModels == null) {
//            return;
//        }
//
//        if (clusterNodepoolsModels.isEmpty()) {
//            hcsoClusterNodePoolRepository.removeByVid(vendor.getId(), userId);
//            return;
//        }
//
//        // 获取平台 规格 信息
//        List<ClusterNodePool> clusterNodePools = hcsoClusterNodePoolRepository.listByVendorId(vendor.getId());
//        Map<String, ClusterNodePool> clusterMap = Maps.newHashMap();
//        for (ClusterNodePool clusterNodePool : clusterNodePools) {
//            clusterMap.put(clusterNodePool.getUuid(), clusterNodePool);
//        }
//
//        for (ClusterNodepoolsModel clusterNodepoolsModel : clusterNodepoolsModels) {
//            ClusterNodePool clusterNodePool = null;
//            if (clusterMap.containsKey(clusterNodepoolsModel.getUuid())) {//update
//                clusterNodePool = clusterMap.get(clusterNodepoolsModel.getUuid());
//                BeanUtils.copyProperties(clusterNodepoolsModel, clusterNodePool);
//                hcsoClusterNodePoolRepository.update(clusterNodePool);
//                clusterMap.remove(clusterNodepoolsModel.getUuid());
//                continue;
//            }
//
//            //新增
//            clusterNodePool = new ClusterNodePool();
//            BeanUtils.copyProperties(clusterNodepoolsModel, clusterNodePool);
//            clusterNodePool.setVendorId(vendor.getId());
//            hcsoClusterNodePoolRepository.save(clusterNodePool);
//            clusterMap.remove(clusterNodepoolsModel.getUuid());
//        }
//
//
//        //删除
//        for (Map.Entry<String, ClusterNodePool> entry : clusterMap.entrySet()) {
//            ClusterNodePool clusterNodePool = entry.getValue();
//            hcsoClusterNodePoolRepository.remove(ClusterNodePool.class, clusterNodePool.getId());
//
//        }
//
//    }
//
//	
//	private void syncSwrNamepace(List<SwrNamespaceModel> swrNamespaceModels, CloudVendor vendor, Long userId) throws Exception {
//        if (swrNamespaceModels == null) {
//            return;
//        }
//        if (swrNamespaceModels.isEmpty()) {
//            hcsoSwrNamespaceRepository.removeByVid(vendor.getId());
//            return;
//        }
//        // 获取平台 规格 信息
//        List<SwrNamepace> swrNamepaceList = hcsoSwrNamespaceRepository.listByVendorId(vendor.getId());
//        Map<Long, SwrNamepace> swrNamepaceMap = Maps.newHashMap();
//        for (SwrNamepace swrNamepace : swrNamepaceList) {
//            swrNamepaceMap.put(swrNamepace.getId(), swrNamepace);
//        }
//
//        for (SwrNamespaceModel swrNamespaceModel : swrNamespaceModels) {
//            SwrNamepace swrNamepace = null;
//            if (swrNamepaceMap.containsKey(swrNamespaceModel.getId())) {//update
//                swrNamepace = swrNamepaceMap.get(swrNamespaceModel.getId());
//                BeanUtils.copyProperties(swrNamespaceModel, swrNamepace);
//                hcsoSwrNamespaceRepository.update(swrNamepace);
//                swrNamepaceMap.remove(swrNamespaceModel.getId());
//                continue;
//            }
//            //新增
//            swrNamepace = new SwrNamepace();
//            BeanUtils.copyProperties(swrNamespaceModel, swrNamepace);
//            swrNamepace.setVendorId(vendor.getId());
//            hcsoSwrNamespaceRepository.save(swrNamepace);
//            swrNamepaceMap.remove(swrNamespaceModel.getId());
//        }
//        //删除
//        for (Map.Entry<Long, SwrNamepace> entry : swrNamepaceMap.entrySet()) {
//            SwrNamepace swrNamepace = entry.getValue();
//            hcsoSwrNamespaceRepository.removeByid(swrNamepace.getId(),vendor.getId());
//
//        }
//
//    }
//
//	
//	private void syncHcsoUser(List<HcsoUserModel> hcsoUserModels, CloudVendor vendor, Long userId) throws Exception {
//        if (hcsoUserModels == null) {
//            return;
//        }
//        if (hcsoUserModels.isEmpty()) {
//            hcsoIamRepository.removeByVid(vendor.getId());
//            return;
//        }
//        // 获取平台 规格 信息
//        List<HcsoUser> hcsoUsers = hcsoIamRepository.listByVendorId(vendor.getId());
//        Map<String, HcsoUser> hcsoUserHashMap = Maps.newHashMap();
//        for (HcsoUser hcsoUser : hcsoUsers) {
//            hcsoUserHashMap.put(hcsoUser.getUser_id(), hcsoUser);
//        }
//
//        for (HcsoUserModel hcsoUserModel : hcsoUserModels) {
//            HcsoUser hcsoUser = null;
//            if (hcsoUserHashMap.containsKey(hcsoUserModel.getUser_id())) {//update
//                hcsoUser = hcsoUserHashMap.get(hcsoUserModel.getUser_id());
//                BeanUtils.copyProperties(hcsoUserModel, hcsoUser);
//                hcsoIamRepository.update(hcsoUser);
//                hcsoUserHashMap.remove(hcsoUserModel.getUser_id());
//                continue;
//            }
//            //新增
//            hcsoUser = new HcsoUser();
//            BeanUtils.copyProperties(hcsoUserModel, hcsoUser);
//            hcsoUser.setVendorId(vendor.getId());
//            hcsoIamRepository.save(hcsoUser);
//            hcsoUserHashMap.remove(hcsoUser.getUser_id());
//        }
//        //删除
//        for (Map.Entry<String, HcsoUser> entry : hcsoUserHashMap.entrySet()) {
//            HcsoUser hcsoUser = entry.getValue();
//            hcsoIamRepository.remove(HcsoUser.class, hcsoUser.getId());
//        }
//    }
//	
//	private void syncClusterNode(List<ClusterNodeModel> clusterNodeModels, CloudVendor vendor, Long userId, Map<String, CloudServer> serverMap) throws Exception {
//        if (clusterNodeModels == null) {
//            return;
//        }
//
//        if (clusterNodeModels.isEmpty()) {
//            hcsoClusterNodeRepository.removeByVid(vendor.getId(), userId);
//            return;
//        }
//
//        // 获取平台 规格 信息
//        List<ClusterNode> clusterNodes = hcsoClusterNodeRepository.listByVendorId(vendor.getId());
//        Map<String, ClusterNode> clusterMap = Maps.newHashMap();
//        for (ClusterNode clusterNode : clusterNodes) {
//            clusterMap.put(clusterNode.getUid(), clusterNode);
//        }
//
//        for (ClusterNodeModel clusterNodeModel : clusterNodeModels) {
//        	String serverId = JSONObject.parseObject(clusterNodeModel.getStatus()).getString("serverid");
//            ClusterNode clusterNode = null;
//            if (clusterMap.containsKey(clusterNodeModel.getUid())) {//update
//                clusterNode = clusterMap.get(clusterNodeModel.getUid());
//                BeanUtils.copyProperties(clusterNodeModel, clusterNode);
//                hcsoClusterNodeRepository.update(clusterNode);
//				if (serverMap.containsKey(serverId)) {
//					CloudServer server = serverMap.get(serverId);
//					server.setNodeId(clusterNode.getId());
//					cloudServerRepository.update(server);
//				}
//				clusterMap.remove(clusterNodeModel.getUid());
//                continue;
//            }
//
//            //新增
//            clusterNode = new ClusterNode();
//            BeanUtils.copyProperties(clusterNodeModel, clusterNode);
//            clusterNode.setVendorId(vendor.getId());
//            hcsoClusterNodeRepository.save(clusterNode);
//			if (serverMap.containsKey(serverId)) {
//				CloudServer server = serverMap.get(serverId);
//				server.setNodeId(clusterNode.getId());
//				cloudServerRepository.update(server);
//			}
//            clusterMap.remove(clusterNodeModel.getUid());
//        }
//
//
//        //删除
//        for (Map.Entry<String, ClusterNode> entry : clusterMap.entrySet()) {
//            ClusterNode clusterNode = entry.getValue();
//            hcsoClusterNodeRepository.remove(ClusterNode.class, clusterNode.getId());
//
//        }
//
//    }
//	
//	private void syncCluster(List<ClusterModel> clusterModels, CloudVendor vendor, Long userId) throws Exception {
//        if (clusterModels == null) {
//            return;
//        }
//
//        if (clusterModels.isEmpty()) {
//            hcsoClusterRepository.removeByVid(vendor.getId(), userId);
//            return;
//        }
//
//        // 获取平台 规格 信息
//        List<Cluster> clusters = hcsoClusterRepository.listByVendorId(vendor.getId());
//        Map<String, Cluster> clusterMap = Maps.newHashMap();
//        for (Cluster cluster : clusters) {
//            clusterMap.put(cluster.getUid(), cluster);
//        }
//
//        for (ClusterModel clusterModel : clusterModels) {
//            Cluster cluster = null;
//            if (clusterMap.containsKey(clusterModel.getUid())) {//update
//                cluster = clusterMap.get(clusterModel.getUid());
//                BeanUtils.copyProperties(clusterModel, cluster);
//                hcsoClusterRepository.update(cluster);
//                clusterMap.remove(clusterModel.getUid());
//                continue;
//            }
//
//            //新增
//            cluster = new Cluster();
//            BeanUtils.copyProperties(clusterModel, cluster);
//            cluster.setVendorId(vendor.getId());
//            cluster.setTenantId(0L);
//            hcsoClusterRepository.save(cluster);
//            clusterMap.remove(clusterModel.getUid());
//        }
//
//
//        //删除
//        for (Map.Entry<String, Cluster> entry : clusterMap.entrySet()) {
//            Cluster cluster = entry.getValue();
//            hcsoClusterRepository.remove(Cluster.class, cluster.getId());
//
//        }
//
//    }
//	
//	private void syncContainerImage(List<com.bocloud.cmp.model.hcso.ContainerImage> containerImageModels, CloudVendor vendor, Long userId) throws Exception {
//
//        if (containerImageModels == null) {
//            return;
//        }
//        if (containerImageModels.isEmpty()) {
//            hcsoContainerImageRepository.removeByVid(vendor.getId());
//            return;
//        }
//        List<ContainerImage> containerImages = hcsoContainerImageRepository.listByVendorId(vendor.getId());
//        Map<String, ContainerImage> containerImageMap = Maps.newHashMap();
//        for (ContainerImage containerImage : containerImages) {
//            containerImageMap.put(containerImage.getName(), containerImage);
//        }
//
//        for (com.bocloud.cmp.model.hcso.ContainerImage containerImage : containerImageModels) {
//            ContainerImage instance = null;
//            if (containerImageMap.containsKey(containerImage.getName())) {
//                instance = containerImageMap.get(containerImage.getName());
//                containerImage.setId(instance.getId());
//                containerImage.setVendorId(instance.getVendorId());
//                containerImage.setDeleted(false);
//                BeanUtils.copyProperties(containerImage, instance);
//                hcsoContainerImageRepository.update(instance);
//                containerImageMap.remove(containerImage.getName());
//                continue;
//            }
//            // 新增
//            instance = new ContainerImage();
//            BeanUtils.copyProperties(containerImage, instance);
//            instance.setVendorId(vendor.getId());
//            hcsoContainerImageRepository.save(instance);
//            containerImageMap.remove(containerImage.getName());
//        }
//        // 删除
//        for (Map.Entry<String, ContainerImage> entry : containerImageMap.entrySet()) {
//            ContainerImage containerImage = entry.getValue();
//            containerImage.setDeleted(true);
//            hcsoContainerImageRepository.update(containerImage);
//        }
//    }
//
//	private void syncFirewallRule(List<FirewallRuleModel> firewallRuleModels, String regionId, CloudVendor vendor,
//			Long userId) {
//		try {
//			if (ListTool.isEmpty(firewallRuleModels)) {
//				firewallRuleRepository.removeByVid(vendor.getId(), userId);
//				return;
//			}
//			List<FirewallRule> firewallRules = firewallRuleRepository.listByVid(vendor.getId());
//			Map<String, FirewallRule> firewallRuleMap = firewallRules.stream()
//					.collect(Collectors.toMap(FirewallRule::getRuleUuid, Function.identity(), (key1, key2) -> key2));
//			FirewallRule firewallRule = null;
//			for (FirewallRuleModel model : firewallRuleModels) {
//				String uuid = model.getRuleUuid();
//				if (firewallRuleMap.containsKey(uuid)) {
//					firewallRule = firewallRuleMap.get(uuid);
//					BeanUtils.copyProperties(model, firewallRule);
//					firewallRuleRepository.update(firewallRule);
//					firewallRuleMap.remove(uuid);
//					continue;
//				}
//				firewallRule = new FirewallRule();
//				BeanUtils.copyProperties(model, firewallRule);
//				firewallRule.setGmtModify(new Date());
//				firewallRule.setGmtCreate(new Date());
//				firewallRule.setCreatorId(userId);
//				firewallRule.setVendorId(vendor.getId());
//				firewallRule.setVendorType(vendor.getType());
//				firewallRule.setTenantId(0L);
//				firewallRule.setProjectId(0L);
//				firewallRuleRepository.save(firewallRule);
//			}
//			for (Map.Entry<String, FirewallRule> entry : firewallRuleMap.entrySet()) {
//				firewallRuleRepository.remove(entry.getValue().getId(), userId);
//			}
//		} catch (Exception e) {
//			logger.info("同步防火墙规则异常：" + e);
//		}
//	}
//
//	private void syncFirewallPolicy(List<FirewallPolicyModel> firewallPolicyModel, String regionId, CloudVendor vendor,
//			Long userId, Map<String, FirewallRule> firewallRuleMap, Map<String, Firewall> firewallMap) {
//		try {
//			if (ListTool.isEmpty(firewallPolicyModel)) {
//				firewallPolicyRepository.removeByVid(vendor.getId(), userId);
//				return;
//			}
//			List<FirewallPolicy> firewallPolicies = firewallPolicyRepository.listByVid(vendor.getId());
//			Map<String, FirewallPolicy> firewallPolicyMap = firewallPolicies.stream().collect(
//					Collectors.toMap(FirewallPolicy::getPolicyUuid, Function.identity(), (key1, key2) -> key2));
//			FirewallPolicy firewallPolicy = null;
//			for (FirewallPolicyModel model : firewallPolicyModel) {
//				String uuid = model.getPolicyUuid();
//				if (firewallPolicyMap.containsKey(uuid)) {
//					firewallPolicy = firewallPolicyMap.get(uuid);
//					BeanUtils.copyProperties(model, firewallPolicy);
//					firewallPolicy.setVendorType(vendor.getType());
//					firewallPolicyRepository.update(firewallPolicy);
//					updateFirewallRule(model.getRuleUuids(), firewallPolicy, firewallRuleMap, firewallMap);
//					firewallPolicyMap.remove(uuid);
//					continue;
//				}
//				firewallPolicy = new FirewallPolicy();
//				BeanUtils.copyProperties(model, firewallPolicy);
//				firewallPolicy.setGmtModify(new Date());
//				firewallPolicy.setGmtCreate(new Date());
//				firewallPolicy.setCreatorId(userId);
//				firewallPolicy.setVendorId(vendor.getId());
//				firewallPolicy.setVendorType(vendor.getType());
//				firewallPolicy.setTenantId(0L);
//				firewallPolicy.setProjectId(0L);
//				firewallPolicyRepository.save(firewallPolicy);
//				updateFirewallRule(model.getRuleUuids(), firewallPolicy, firewallRuleMap, firewallMap);
//			}
//			for (Map.Entry<String, FirewallPolicy> entry : firewallPolicyMap.entrySet()) {
//				firewallPolicyRepository.remove(entry.getValue().getId(), userId);
//			}
//		} catch (Exception e) {
//			logger.info("同步防火墙策略异常：" + e);
//		}
//	}
//
//	private void updateFirewallRule(List<String> ruleUuids, FirewallPolicy firewallPolicy,
//			Map<String, FirewallRule> firewallRuleMap, Map<String, Firewall> firewallMap) {
//		try {
//			if (ListTool.isEmpty(ruleUuids)) {
//				return;
//			}
//			for (String ruleUuid : ruleUuids) {
//				if (firewallRuleMap.containsKey(ruleUuid) && null != firewallRuleMap.get(ruleUuid)) {
//					FirewallRule firewallRule = firewallRuleMap.get(ruleUuid);
//					firewallRule.setPolicyId(firewallPolicy.getId());
//					firewallRule.setPolicyUuid(firewallPolicy.getPolicyUuid());
//					if (firewallMap.containsKey(firewallPolicy.getPolicyUuid())
//							&& null != firewallMap.get(firewallPolicy.getPolicyUuid())) {
//						firewallRule.setFirewallId(firewallMap.get(firewallPolicy.getPolicyUuid()).getId());
//						firewallRule.setFirewallUuid(firewallMap.get(firewallPolicy.getPolicyUuid()).getFirewallUuid());
//					}
//					firewallRuleRepository.update(firewallRule);
//				}
//			}
//		} catch (Exception e) {
//			logger.error("更新防火墙规则异常：" + e.getMessage());
//		}
//	}
//
//	private void syncFirewall(List<FirewallModel> firewallModels, String regionId, Long vendorId, Long userId) {
//		try {
//			if (ListTool.isEmpty(firewallModels)) {
//				firewallRepository.removeByVid(vendorId, regionId, userId);
//				return;
//			}
//			List<Firewall> allFirewalls = firewallRepository.listByVid(vendorId, regionId);
//			Map<String, Firewall> firewallMap = Maps.newHashMap();
//			for (Firewall firewall : allFirewalls) {
//				firewallMap.put(firewall.getFirewallUuid(), firewall);
//			}
//			Firewall firewall = null;
//			for (FirewallModel model : firewallModels) {
//				String uuid = model.getFirewallUuid();
//				if (firewallMap.containsKey(uuid)) {
//					firewall = firewallMap.get(uuid);
//					BeanUtils.copyProperties(model, firewall);
//					firewallRepository.update(firewall);
//					subnetRepository.updateSubnetByFirewall(firewall.getId());
//					syncSubnetByFirewall(firewall, model.getSubnetUuids());
//					firewallMap.remove(uuid);
//					continue;
//				}
//				firewall = new Firewall();
//				BeanUtils.copyProperties(model, firewall);
//				firewall.setGmtModify(model.getUpdateTime());
//				firewall.setGmtCreate(new Date());
//				firewall.setCreatorId(userId);
//				firewall.setVendorId(vendorId);
//				firewall.setTenantId(0L);
//				firewall.setProjectId(0L);
//				firewallRepository.save(firewall);
//				subnetRepository.updateSubnetByFirewall(firewall.getId());
//				syncSubnetByFirewall(firewall, model.getSubnetUuids());
//			}
//			for (Map.Entry<String, Firewall> entry : firewallMap.entrySet()) {
//				firewallRepository.remove(entry.getValue().getId(), userId);
//			}
//		} catch (Exception e) {
//			logger.info("同步防火墙ACL异常：" + e);
//		}
//	}
//	
//	public void syncSubnetByFirewall(Firewall firewall, List<String> subnetUuids) {
//		try {
//			if (ListTool.isEmpty(subnetUuids)) {
//				return;
//			}
//			for (String subnetUuid : subnetUuids) {
//				Subnet subnet = subnetRepository.getBySubId(subnetUuid, firewall.getVendorId());
//				if (null != subnet) {
//					subnet.setFirewallId(firewall.getId());
//					subnetRepository.update(subnet);
//				}
//			}
//		} catch (Exception e) {
//			logger.error("修改防火墙子网关联关系异常：" + e);
//		}
//	}
//
//	private void syncCloudServerGroups(List<CloudServerGroupModel> cloudServerGroupModels, String regionId, Long vendorId, Long userId) {
//		try {
//			if (ListTool.isEmpty(cloudServerGroupModels)) {
//				cloudServerGroupRepository.deleteByVid(vendorId, userId);
//				return;
//			}
//			List<CloudServerGroup> cloudServerGroups = cloudServerGroupRepository.listByVid(vendorId);
//
//			Map<String, CloudServerGroup> cloudServerGroupMap = Maps.newHashMap();
//			for (CloudServerGroup cloudServerGroup : cloudServerGroups) {
//				cloudServerGroupMap.put(cloudServerGroup.getServerGroupUuid(), cloudServerGroup);
//			}
//			CloudServerGroup cloudServerGroup = null;
//			for (CloudServerGroupModel model : cloudServerGroupModels) {
//				String uuid = model.getServerGroupUuid();
//				if (cloudServerGroupMap.containsKey(uuid)) {
//					cloudServerGroup = cloudServerGroupMap.get(uuid);
//					BeanUtils.copyProperties(model, cloudServerGroup);
//					cloudServerGroup.setMemberCount(0);
//					// 处理服务器下成员数据
//					List<String> members = JSON.parseArray(model.getMembers(), String.class);
//					List<CloudServer> cloudServers =
//						cloudServerRepository.listByServerGroupId(vendorId, cloudServerGroup.getId());
//					if (!ListTool.isEmpty(cloudServers)) {
//						cloudServers.forEach(cloudServer -> {
//							cloudServer.setCloudServerGroupId(null);
//							cloudServerRepository.update(cloudServer);
//						});
//					}
//					if (!ListTool.isEmpty(members)) {
//						for (String instanceId : members) {
//							CloudServer cloudServer = cloudServerRepository.get(vendorId, instanceId);
//							if (null != cloudServer) {
//								cloudServer.setCloudServerGroupId(cloudServerGroup.getId());
//								cloudServerRepository.update(cloudServer);
//							}
//						}
//						cloudServerGroup.setMemberCount(members.size());
//					}
//					cloudServerGroupRepository.update(cloudServerGroup);
//					cloudServerGroupMap.remove(uuid);
//					continue;
//				}
//				cloudServerGroup = new CloudServerGroup();
//				BeanUtils.copyProperties(model, cloudServerGroup);
//				cloudServerGroup.setVendorId(vendorId);
//				cloudServerGroup.setCreatorId(0L);
//				cloudServerGroup.setMemberCount(0);
//				List<String> members = JSON.parseArray(model.getMembers(), String.class);
//				List<CloudServer> cloudServers = cloudServerRepository.listByServerGroupId(vendorId, cloudServerGroup.getId());
//				if (!ListTool.isEmpty(cloudServers)) {
//					cloudServers.forEach(cloudServer -> {
//						cloudServer.setCloudServerGroupId(null);
//						cloudServerRepository.update(cloudServer);
//					});
//				}
//				if (!ListTool.isEmpty(members)) {
//					for (String instanceId : members) {
//						CloudServer cloudServer = cloudServerRepository.get(vendorId, instanceId);
//						if (null != cloudServer) {
//							cloudServer.setCloudServerGroupId(cloudServerGroup.getId());
//							cloudServerRepository.update(cloudServer);
//						}
//					}
//					cloudServerGroup.setMemberCount(members.size());
//				}
//				cloudServerGroupRepository.save(cloudServerGroup);
//			}
//			for (Map.Entry<String, CloudServerGroup> entry : cloudServerGroupMap.entrySet()) {
//				cloudServerGroupRepository.delete(entry.getValue().getId(), userId);
//			}
//		} catch (Exception e) {
//			logger.info("同步云服务器异常异常：" + e);
//		}
//
//	}

	private void syncRouteTables(List<RouteTableModel> models, Long vendorId, Long userId, Map<String, Long> vpcMap,
		String region) throws Exception {
		if (ListTool.isEmpty(models)) {
			routeTableRepository.removeByVid(vendorId, region, userId);
			routeRepository.removeByVid(vendorId, region, userId);
			return;
		}
		List<RouteTable> routeTables = routeTableRepository.listByVid(vendorId, region);
		Map<String, RouteTable> routeTableMap = Maps.newHashMap();
		routeTables.forEach((RouteTable routeTable) -> {
			routeTableMap.put(routeTable.getRouterId(), routeTable);
		});

		for (RouteTableModel model : models) {
			RouteTable routeTable = new RouteTable();
			String uuid = model.getRouterId();
			if (routeTableMap.containsKey(uuid)) {
				routeTable = routeTableMap.get(uuid);
				BeanUtils.copyProperties(model, routeTable);
				// 关联vpc
				if (!StringUtils.isEmpty(model.getVpcUuid()) && null != vpcMap.get(model.getVpcUuid())) {
					routeTable.setVpcId(vpcMap.get(model.getVpcUuid()));
				}
				routeTable.setMenderId(userId);
				routeTable.setGmtModify(new Date());
				routeTable.setVendorId(vendorId);
				routeTable.setRegionId(region);
				routeTableRepository.update(routeTable);
				List<String> subnetlds = model.getSubnetlds();
				if (!ListTool.isEmpty(subnetlds)) {
					subnetlds.forEach(subnetId -> {
						Subnet subnet = subnetRepository.getBySubId(subnetId, vendorId);
						if (null != subnet) {
							subnet.setRouteTableId(uuid);
							subnetRepository.update(subnet);
						}
					});
				}
				routeTableMap.remove(uuid);
			} else {
				BeanUtils.copyProperties(model, routeTable);
				// 关联vpc
				if (!StringUtils.isEmpty(model.getVpcUuid()) && null != vpcMap.get(model.getVpcUuid())) {
					routeTable.setVpcId(vpcMap.get(model.getVpcUuid()));
				}
				routeTable.setCreatorId(userId);
				routeTable.setGmtCreate(new Date());
				routeTable.setVendorId(vendorId);
				routeTable.setRegionId(region);
				routeTableRepository.save(routeTable);
				List<String> subnetlds = model.getSubnetlds();
				if (!ListTool.isEmpty(subnetlds)) {
					subnetlds.forEach(subnetId -> {
						Subnet subnet = subnetRepository.getBySubId(subnetId, vendorId);
						if (null != subnet) {
							subnet.setRouteTableId(uuid);
							subnetRepository.update(subnet);
						}
					});
				}
				routeTableMap.remove(uuid);
			}
			syncRouteEntry(model.getRouteModels(), routeTable, vendorId, userId, region);
		}
		for (Map.Entry<String, RouteTable> entry : routeTableMap.entrySet()) {
			routeTableRepository.remove(entry.getValue().getId(), userId);
			routeRepository.removeByVid(vendorId, region, userId, entry.getValue().getId());
		}
	}

	private void syncRouteEntry(List<RouteModel> models, RouteTable routeTable, Long vendorId, Long userId, String region)
		throws Exception {
		if (ListTool.isEmpty(models)) {
			routeRepository.removeByVid(vendorId, region, userId, routeTable.getId());
			return;
		}
		List<Route> routes = routeRepository.listByVid(vendorId, region, routeTable.getId());
		Map<String, Route> routeMap = Maps.newHashMap();
		routes.forEach((Route route) -> {
			routeMap.put(route.getUuid() + route.getName() + route.getDestination() + route.getType(), route);
		});
		for (RouteModel model : models) {
			Route route = new Route();
			String key = model.getUuid() + model.getName() + model.getDestination() + model.getType();
			if (routeMap.containsKey(key)) {
				route = routeMap.get(key);
				BeanUtils.copyProperties(model, route);
				route.setRouteTableId(routeTable.getId());
				route.setRouteTableUuid(routeTable.getRouterId());
				route.setVpcUuid(routeTable.getVpcUuid());
				route.setMenderId(userId);
				route.setGmtModify(new Date());
				route.setVendorId(vendorId);
				route.setRegionId(region);
				routeRepository.update(route);
				routeMap.remove(key);
			} else {
				BeanUtils.copyProperties(model, route);
				route.setRouteTableId(routeTable.getId());
				route.setRouteTableUuid(routeTable.getRouterId());
				route.setVpcUuid(routeTable.getVpcUuid());
				route.setCreatorId(userId);
				route.setGmtCreate(new Date());
				route.setVendorId(vendorId);
				route.setRegionId(region);
				routeRepository.save(route);
				routeMap.remove(key);
			}
		}
		for (Map.Entry<String, Route> entry : routeMap.entrySet()) {
			routeRepository.remove(entry.getValue().getId(), userId);
		}
	}

//	private void syncVpcPeerings(List<VpcPeeringModel> vpcPeeringModels, String regionId, Long vendorId, Long userId) {
//		try {
//			if (ListTool.isEmpty(vpcPeeringModels)) {
//				vpcPeeringsRepository.removeByVid(vendorId);
//				return;
//			}
//			List<VpcPeerings> vpcPeeringList = vpcPeeringsRepository.listByVid(vendorId);
//			Map<String, VpcPeerings> vpcPeeringsMap = Maps.newHashMap();
//			for (VpcPeerings vpcPeering : vpcPeeringList) {
//				vpcPeeringsMap.put(vpcPeering.getVpcPeeringId(), vpcPeering);
//			}
//			VpcPeerings vpcPeerings = null;
//			for (VpcPeeringModel model : vpcPeeringModels) {
//				String uuid = model.getVpcPeeringId();
//				if (vpcPeeringsMap.containsKey(uuid)) {
//					vpcPeerings = vpcPeeringsMap.get(uuid);
//					vpcPeerings.setName(model.getName());
//					vpcPeerings.setStatus(model.getStatus());
//					vpcPeerings.setDescription(model.getDescription());
//					vpcPeerings.setGmtModify(model.getUpdatedAt());
//					vpcPeerings.setCreateTime(model.getCreatedAt());
//					vpcPeerings.setIsDeleted(false);
//					VpcInfo requestVpcInfo = model.getRequestVpcInfo();
//					if (null != requestVpcInfo) {
//						vpcPeerings.setRequestVpcId(requestVpcInfo.getVpcId());
//					}
//					VpcInfo acceptVpcInfo = model.getAcceptVpcInfo();
//					if (null != acceptVpcInfo) {
//						vpcPeerings.setAcceptProjectId(acceptVpcInfo.getTenantId());
//						vpcPeerings.setAcceptVpcId(acceptVpcInfo.getVpcId());
//					}
//					vpcPeeringsRepository.update(vpcPeerings);
//					vpcPeeringsMap.remove(uuid);
//					continue;
//				}
//				vpcPeerings = new VpcPeerings();
//				vpcPeerings.setVpcPeeringId(model.getVpcPeeringId());
//				vpcPeerings.setName(model.getName());
//				vpcPeerings.setStatus(model.getStatus());
//				vpcPeerings.setDescription(model.getDescription());
//				vpcPeerings.setIsDeleted(false);
//				vpcPeerings.setGmtModify(model.getUpdatedAt());
//				vpcPeerings.setCreateTime(model.getCreatedAt());
//				vpcPeerings.setVendorId(vendorId);
//				VpcInfo requestVpcInfo = model.getRequestVpcInfo();
//				if (null != requestVpcInfo) {
//					vpcPeerings.setRequestVpcId(requestVpcInfo.getVpcId());
//				}
//				VpcInfo acceptVpcInfo = model.getAcceptVpcInfo();
//				if (null != acceptVpcInfo) {
//					vpcPeerings.setAcceptProjectId(acceptVpcInfo.getTenantId());
//					vpcPeerings.setAcceptVpcId(acceptVpcInfo.getVpcId());
//				}
//				vpcPeeringsRepository.save(vpcPeerings);
//			}
//			for (Map.Entry<String, VpcPeerings> entry : vpcPeeringsMap.entrySet()) {
//				vpcPeeringsRepository.remove(entry.getValue().getId(), userId);
//			}
//		} catch (Exception e) {
//			logger.info("同步预定义标签异常：" + e);
//		}
//	}
//
//	private void syncPredefineTags(List<TagModel> tagModels, String regionId, Long vendorId, Long userId) {
//		try {
//			if (ListTool.isEmpty(tagModels)) {
//				predefineTagsRepository.removeByVid(vendorId, regionId);
//				return;
//			}
//			List<PredefineTags> predefineTagsList = predefineTagsRepository.listByVid(vendorId, regionId);
//			Map<String, PredefineTags> predefineTagsMap = Maps.newHashMap();
//			for (PredefineTags predefineTags : predefineTagsList) {
//				predefineTagsMap.put(predefineTags.getName() + "_" + predefineTags.getContent(), predefineTags);
//			}
//			PredefineTags predefineTags = null;
//			for (TagModel model : tagModels) {
//				String uuid = model.getKey() + "_" + model.getValue();
//				if (predefineTagsMap.containsKey(uuid)) {
//					predefineTags = predefineTagsMap.get(uuid);
//					predefineTags.setUpdateTime(model.getUpdateTime());
//					predefineTagsRepository.update(predefineTags);
//					predefineTagsMap.remove(uuid);
//					continue;
//				}
//				predefineTags = new PredefineTags();
//				predefineTags.setTenantId(0L);
//				predefineTags.setCreateId(userId);
//				predefineTags.setRegionId(regionId);
//				predefineTags.setVendorId(vendorId);
//				predefineTags.setName(model.getKey());
//				predefineTags.setContent(model.getValue());
//				predefineTags.setUpdateTime(model.getUpdateTime());
//				predefineTagsRepository.save(predefineTags);
//			}
//			for (Map.Entry<String, PredefineTags> entry : predefineTagsMap.entrySet()) {
//				predefineTagsRepository.remove(entry.getValue().getId());
//			}
//		} catch (Exception e) {
//			logger.info("同步预定义标签异常：" + e);
//		}
//	}

	public void syncEnterpriseProject(List<EnterpriseProjectModel> enterpriseProjectModels, Long vendorId, Long userId,
		String regionId) {
		if (ListTool.isEmpty(enterpriseProjectModels)) {
			osTenantRepository.removeByVid(vendorId);
			return;
		}
		List<OSTenant> listByVid = osTenantRepository.listByVid(vendorId);

		Map<String, OSTenant> vaultsMap = Maps.newHashMap();
		for (OSTenant osTenant : listByVid) {
			vaultsMap.put(osTenant.getTenantUuid(), osTenant);
		}
		OSTenant osTenant = null;
		for (EnterpriseProjectModel model : enterpriseProjectModels) {
			String enterpriseProjectUuid = model.getEnterpriseProjectUuid();
			if (vaultsMap.containsKey(enterpriseProjectUuid)) {
				osTenant = vaultsMap.get(enterpriseProjectUuid);
				BeanUtils.copyProperties(model, osTenant);
				osTenant.setCreatorId(userId);
				osTenant.setVendorId(vendorId);
				osTenant.setTenantUuid(model.getEnterpriseProjectUuid());
				osTenantRepository.update(osTenant);
				vaultsMap.remove(enterpriseProjectUuid);
				continue;
			}
			osTenant = new OSTenant();
			BeanUtils.copyProperties(model, osTenant);
			osTenant.setTenantId(0L);
			osTenant.setCreatorId(userId);
			osTenant.setVendorId(vendorId);
			osTenant.setTenantUuid(model.getEnterpriseProjectUuid());
			osTenantRepository.save(osTenant);
		}
		for (Map.Entry<String, OSTenant> entry : vaultsMap.entrySet()) {
			osTenantRepository.remove(entry.getValue().getId());
		}

	}

//	private void syncBackupVaults(List<VaultsModel> vaultsModels, Long vendorId, Long userId, String regionId, Map<String, Volume> volumeMap, Map<String, CloudServer> sMap) {
//		// 当浮动IP为空时，清空数据库
//		if (ListTool.isEmpty(vaultsModels)) {
//			backupVaultsRepository.deleteByVendorId(vendorId, regionId, userId);
//			backupRepository.removeByVid(vendorId, userId);
//			return;
//		}
//		List<BackupVaults> backupVaultsList = backupVaultsRepository.list(vendorId, regionId);
//		Map<String, BackupVaults> vaultsMap = Maps.newHashMap();
//		for (BackupVaults backupVaults : backupVaultsList) {
//			vaultsMap.put(backupVaults.getVaultsUuid(), backupVaults);
//		}
//		BackupVaults backupVaults = null;
//		for (VaultsModel model : vaultsModels) {
//			String vaultsUuid = model.getVaultsUuid();
//			if (vaultsMap.containsKey(vaultsUuid)) {
//				backupVaults = vaultsMap.get(vaultsUuid);
//				BeanUtils.copyProperties(model, backupVaults);
//				backupVaults.setMenderId(userId);
//				backupVaults.setRegionId(regionId);
//				backupVaults.setGmtModify(new Date());
//				backupVaults.setCreatorId(userId);
//				backupVaults.setVendorId(vendorId);
//				backupVaults.setCatalog(RequestContext.Catalog.Manager);
//				backupVaults.setTenantUuid(model.getEnterpriseProjectUuid());
//				backupVaultsRepository.update(backupVaults);
//				syncResourceRelation(vendorId, backupVaults.getId(), model, volumeMap, sMap);
//				vaultsMap.remove(vaultsUuid);
//				continue;
//			}
//			backupVaults = new BackupVaults();
//			BeanUtils.copyProperties(model, backupVaults);
//			backupVaults.setMenderId(userId);
//			backupVaults.setRegionId(regionId);
//			backupVaults.setGmtModify(new Date());
//			backupVaults.setTenantId(0L);
//			backupVaults.setProjectId(0L);
//			backupVaults.setCreatorId(userId);
//			backupVaults.setVendorId(vendorId);
//			backupVaults.setCatalog(RequestContext.Catalog.Manager);
//			backupVaults.setTenantUuid(model.getEnterpriseProjectUuid());
//			backupVaultsRepository.save(backupVaults);
//			syncResourceRelation(vendorId, backupVaults.getId(), model, volumeMap, sMap);
//		}
//		for (Map.Entry<String, BackupVaults> entry : vaultsMap.entrySet()) {
//			backupVaultsRepository.delete(entry.getValue().getId(), userId);
//			backupRepository.removeByVaultsId(entry.getValue().getId(), userId);
//		}
//
//	}

//	private void syncResourceRelation(Long vendorId, Long vaultsId, VaultsModel model, Map<String, Volume> volumeMap,
//		Map<String, CloudServer> serverMap) {
//
//		String objectType = model.getObjectType();
//		switch (objectType) {
//			case "disk":
//				List<VolumeModel> volumeModels = model.getVolumeModels();
//				if (ListTool.isEmpty(volumeModels)) {
//					return;
//				}
//				List<Volume> resourceVolumes = volumeRepository.listByVaultsUuid(model.getVaultsUuid(), vendorId, model.getRegionId());
//				for (Volume volume : resourceVolumes) {
//					volume.setVaultsUuid(null);
//					volume.setBackupCount(null);
//					volume.setVaultsId(null);
//					volume.setBackupSize(null);
//					volumeRepository.update(volume);
//				}
//				for (VolumeModel volumeModel : volumeModels) {
//					String volumeUuid = volumeModel.getVolumeUuid();
//					if (volumeMap.containsKey(volumeUuid)) {
//						Volume volume = volumeMap.get(volumeUuid);
//						volume.setVaultsUuid(model.getVaultsUuid());
//						volume.setBackupCount(volumeModel.getBackupCount());
//						volume.setBackupSize(volumeModel.getBackupSize());
//						volume.setVaultsId(vaultsId);
//						volumeRepository.update(volume);
//					}
//				}
//				break;
//			case "server":
//				List<ServerModel> serverModels = model.getServerModels();
//				if (ListTool.isEmpty(serverModels)) {
//					return;
//				}
//				List<CloudServer> servers =
//					cloudServerRepository.listByVaultsUuid(model.getVaultsUuid(), vendorId, model.getRegionId());
//				for (CloudServer cloudServer : servers) {
//					cloudServer.setVaultsUuid(null);
//					cloudServer.setBackupCount(null);
//					cloudServer.setVaultsId(null);
//					cloudServer.setBackupSize(null);
//					cloudServerRepository.update(cloudServer);
//				}
//				for (ServerModel serverModel : serverModels) {
//					String instanceId = serverModel.getInstanceId();
//					if (serverMap.containsKey(instanceId)) {
//						CloudServer cloudServer = serverMap.get(instanceId);
//						cloudServer.setVaultsUuid(model.getVaultsUuid());
//						cloudServer.setBackupCount(serverModel.getBackupCount());
//						cloudServer.setVaultsId(vaultsId);
//						cloudServer.setBackupSize(serverModel.getBackupSize());
//						cloudServerRepository.update(cloudServer);
//					}
//				}
//				break;
//			default:
//				break;
//		}
//	}
//
//	public void syncBackupResources(List<BackupModel> backupModels, Long vendorId, Long userId, String regionId, Map<String, BackupVaults> valutsMap) {
//		if (ListTool.isEmpty(backupModels)) {
//			backupRepository.deleteByVendorId(vendorId, regionId, userId);
//			return;
//		}
//		List<Backup> backupList = backupRepository.list(vendorId, regionId);
//		Map<String, Backup> backupMap = Maps.newHashMap();
//		for (Backup backup : backupList) {
//			if (backupMap.containsKey(backup.getBackupUuid())) {
//				backupRepository.delete(backup.getId(), userId);
//			} else {
//				backupMap.put(backup.getBackupUuid(), backup);
//			}
//		}
//		Backup backup = null;
//		for (BackupModel model : backupModels) {
//			String backupUuid = model.getBackupUuid();
//			if (backupMap.containsKey(backupUuid)) {
//				backup = backupMap.get(backupUuid);
//				BeanUtils.copyProperties(model, backup);
//				backup.setMenderId(userId);
//				backup.setRegionId(regionId);
//				backup.setGmtModify(new Date());
//				backup.setCreatorId(userId);
//				backup.setVendorId(vendorId);
//				Optional.ofNullable(valutsMap.get(model.getVaultsUuid())).map(BackupVaults::getTenantUuid).ifPresent(backup::setTenantUuid);
//				Optional.ofNullable(valutsMap.get(model.getVaultsUuid())).map(BackupVaults::getId).ifPresent(backup::setVaultsId);
//				backupRepository.update(backup);
//				if ("OS::Cinder::Volume".equals(model.getResourceType())) {
//					syncSnapshotBackupId(model.getSnapshotModel(), backup.getId());
//				}
//				backupMap.remove(backupUuid);
//				continue;
//			}
//			backup = new Backup();
//			BeanUtils.copyProperties(model, backup);
//			backup.setMenderId(userId);
//			backup.setRegionId(regionId);
//			backup.setGmtModify(new Date());
//			Optional.ofNullable(valutsMap.get(model.getVaultsUuid())).map(BackupVaults::getTenantId).ifPresent(backup::setTenantId);
//			backup.setProjectId(0L);
//			backup.setCreatorId(userId);
//			backup.setVendorId(vendorId);
//			Optional.ofNullable(valutsMap.get(model.getVaultsUuid())).map(BackupVaults::getTenantUuid).ifPresent(backup::setTenantUuid);
//			Optional.ofNullable(valutsMap.get(model.getVaultsUuid())).map(BackupVaults::getId).ifPresent(backup::setVaultsId);
//			backupRepository.save(backup);
//			if ("OS::Cinder::Volume".equals(model.getResourceType())) {
//				syncSnapshotBackupId(model.getSnapshotModel(), backup.getId());
//			}
//		}
//		for (Map.Entry<String, Backup> entry : backupMap.entrySet()) {
//			backupRepository.delete(entry.getValue().getId(), userId);
//			if ("OS::Cinder::Volume".equals(entry.getValue().getResourceType())) {
//				snapshotRepository.removeByBackupId(entry.getValue().getId(), userId);
//			}
//		}
//
//	}
//
//	private void syncSnapshotBackupId(SnapshotModel snapshotModel, Long backupId) {
//		if (snapshotModel != null) {
//			String snapshotUuid = snapshotModel.getSnapshotUuid();
//			Snapshot bySnapUuid = snapshotRepository.getBySnapUuid(snapshotUuid);
//			if (bySnapUuid != null) {
//				bySnapUuid.setBackupId(backupId);
//				snapshotRepository.update(bySnapUuid);
//			}
//		}
//	}
//
//	private void syncBackupPolicys(List<BackupPolicyModel> policyModels, Long vendorId, Long userId, String regionId) {
//		if (ListTool.isEmpty(policyModels)) {
//			backupPolicyRepository.deleteByVendorId(vendorId, regionId, userId);
//			return;
//		}
//		List<BackupPolicy> backupList = backupPolicyRepository.list(vendorId, regionId);
//		Map<String, BackupPolicy> backupMap = Maps.newHashMap();
//		for (BackupPolicy backup : backupList) {
//			if (backupMap.containsKey(backup.getBackupPolicyUuid())) {
//				backupPolicyRepository.delete(backup.getId(), userId);
//			} else {
//				backupMap.put(backup.getBackupPolicyUuid(), backup);
//			}
//		}
//		BackupPolicy backup = null;
//		for (BackupPolicyModel model : policyModels) {
//			String backupUuid = model.getBackupPolicyUuid();
//			if (backupMap.containsKey(backupUuid)) {
//				backup = backupMap.get(backupUuid);
//				BeanUtils.copyProperties(model, backup);
//				backup.setMenderId(userId);
//				backup.setRegionId(regionId);
//				backup.setGmtModify(new Date());
//				backup.setCreatorId(userId);
//				backup.setVendorId(vendorId);
//				backup.setPolicyTrigger(model.getTrigger());
//				backupPolicyRepository.update(backup);
//				List<VaultsModel> vaultsModels = JSONArray.parseArray(model.getAssociatedVaults(), VaultsModel.class);
//				syncPolicyId(vaultsModels, backup.getId(), vendorId);
//				backupMap.remove(backupUuid);
//				continue;
//			}
//			backup = new BackupPolicy();
//			BeanUtils.copyProperties(model, backup);
//			backup.setMenderId(userId);
//			backup.setRegionId(regionId);
//			backup.setGmtModify(new Date());
//			backup.setTenantId(0L);
//			backup.setProjectId(0L);
//			backup.setCreatorId(userId);
//			backup.setVendorId(vendorId);
//			backup.setPolicyTrigger(model.getTrigger());
//			backupPolicyRepository.save(backup);
//			List<VaultsModel> vaultsModels = JSONArray.parseArray(model.getAssociatedVaults(), VaultsModel.class);
//			syncPolicyId(vaultsModels, backup.getId(), vendorId);
//		}
//		for (Map.Entry<String, BackupPolicy> entry : backupMap.entrySet()) {
//			backupPolicyRepository.delete(entry.getValue().getId(), userId);
//		}
//
//	}
//
//	public void syncBackupLogs(List<OperationLogModel> policyModels, Long vendorId, Long userId, String regionId) {
//		if (ListTool.isEmpty(policyModels)) {
//			backupPolicyRepository.deleteByVendorId(vendorId, regionId, userId);
//			return;
//		}
//		List<BackupLog> backupList = logRepository.list(vendorId, regionId);
//		Map<String, BackupLog> backupMap = Maps.newHashMap();
//		for (BackupLog backup : backupList) {
//			if (backupMap.containsKey(backup.getUuid())) {
//				logRepository.delete(backup.getId(), userId);
//			} else {
//				backupMap.put(backup.getUuid(), backup);
//			}
//		}
//		BackupLog backup = null;
//		for (OperationLogModel model : policyModels) {
//			String backupUuid = model.getUuid();
//			if (backupMap.containsKey(backupUuid)) {
//				backup = backupMap.get(backupUuid);
//				BeanUtils.copyProperties(model, backup);
//				backup.setMenderId(userId);
//				backup.setRegionId(regionId);
//				backup.setGmtModify(model.getUpdateTime());
//				backup.setCreatorId(userId);
//				backup.setVendorId(vendorId);
//				backup.setRemove(model.getDelete());
//				backup.setGmtCreate(model.getCreateTime());
//				backup.setVaultsUuid(model.getVaultsUuid());
//				backup.setStartTime(model.getStartedTime());
//				logRepository.update(backup);
//				backupMap.remove(backupUuid);
//				continue;
//			}
//			backup = new BackupLog();
//			BeanUtils.copyProperties(model, backup);
//			backup.setMenderId(userId);
//			backup.setRegionId(regionId);
//			backup.setGmtModify(model.getUpdateTime());
//			backup.setCreatorId(userId);
//			backup.setVendorId(vendorId);
//			backup.setRemove(model.getDelete());
//			backup.setGmtCreate(model.getCreateTime());
//			backup.setVaultsUuid(model.getVaultsUuid());
//			backup.setStartTime(model.getStartedTime());
//			backup.setTenantId(0L);
//			logRepository.save(backup);
//		}
//		for (Map.Entry<String, BackupLog> entry : backupMap.entrySet()) {
//			logRepository.delete(entry.getValue().getId(), userId);
//		}
//
//	}
//
//	private void syncPolicyId(List<VaultsModel> vaultsModels, Long policyId, Long vendorId) {
//		List<BackupVaults> vaultsList = backupVaultsRepository.listByPolicyId(vendorId, policyId);
//		for (BackupVaults vaults : vaultsList) {
//			vaults.setPolicyId(null);
//			backupVaultsRepository.update(vaults);
//		}
//		for (VaultsModel vaultsUuid : vaultsModels) {
//			BackupVaults vaults = backupVaultsRepository.getByVaultsUuid(vaultsUuid.getVaultId());
//			if (vaults != null) {
//				vaults.setPolicyId(policyId);
//				backupVaultsRepository.update(vaults);
//			}
//		}
//	}

	private void syncSubnet(List<SubnetModel> models, Long vendorId, Long userId, String region, String vpcId, Map<String, Vpc> vpcMap) throws Exception {
		if (models == null) {
			return;
		}
		if (models.isEmpty()) {
			subnetRepository.deleteByVpcId(vendorId, vpcId, userId);
			return;
		}
		List<Subnet> subnetList = subnetRepository.listByVpcId(vendorId, vpcId);
		Map<String, Subnet> subnetMap = Maps.newHashMap();
		for (Subnet subnet : subnetList) {
			subnetMap.put(subnet.getSubnetUuid(), subnet);
		}
		for (SubnetModel model : models) {
			Subnet subnet = new Subnet();
			if (subnetMap.containsKey(model.getSubnetUuid())) {
				subnet = subnetMap.get(model.getSubnetUuid());
				BeanUtils.copyProperties(model, subnet);
				subnet.setMenderId(userId);
				subnet.setRegionId(region);
				Vpc vpc = vpcMap.get(vpcId);
				if(null != vpc) {
					subnet.setVpcId(vpc.getId());
					subnet.setTenantUuid(vpc.getTenantUuid());
				}
				subnetRepository.update(subnet);
				subnetMap.remove(model.getSubnetUuid());
				continue;
			}
			BeanUtils.copyProperties(model, subnet);
			subnet.setMenderId(userId);
			subnet.setGmtModify(new Date());
			subnet.setCreatorId(userId);
			subnet.setVendorId(vendorId);
			subnet.setRegionId(region);
			Vpc vpc = vpcMap.get(vpcId);
			if(null != vpc) {
				subnet.setVpcId(vpc.getId());
				subnet.setTenantUuid(vpc.getTenantUuid());
			}
			subnetRepository.save(subnet);
			subnetMap.remove(model.getSubnetUuid());
		}
		for (Entry<String, Subnet> entry : subnetMap.entrySet()) {
			subnetRepository.remove(entry.getValue().getId(), userId);
		}
	}

	private void syncVpc(List<VpcModel> models, Long vendorId, Long userId, String region) throws Exception {
		if (models == null) {
			return;
		}
		if (models.isEmpty()) {
			vpcRepository.deleteByVid(vendorId, region, userId);
			return;
		}
		List<Vpc> vpcs = vpcRepository.list(vendorId, region);
		Map<String, Vpc> vpcMap = Maps.newHashMap();
		for (Vpc vpc : vpcs) {
			vpcMap.put(vpc.getVpcId(), vpc);
		}
		for (VpcModel model : models) {
			Vpc vpc = new Vpc();
			if (vpcMap.containsKey(model.getVpcId())) {
				vpc = vpcMap.get(model.getVpcId());
				BeanUtils.copyProperties(model, vpc);
				vpc.setRegionId(region);
				vpcRepository.update(vpc);
				// 同步子网
				this.syncSubnet(model.getSubnetModels(), vendorId, userId, region, vpc.getVpcId(), vpcMap);
				vpcMap.remove(model.getVpcId());
				continue;
			}
			BeanUtils.copyProperties(model, vpc);
			vpc.setCreatorId(userId);
			vpc.setVendorId(vendorId);
			vpc.setMenderId(userId);
			vpc.setRegionId(region);
			vpc.setTenantId(0L);
			vpc.setProjectId(0L);
			vpcRepository.save(vpc);
			// 同步子网
			this.syncSubnet(model.getSubnetModels(), vendorId, userId, region, vpc.getVpcId(), vpcMap);
			vpcMap.remove(model.getVpcId());
		}
		for (Entry<String, Vpc> entry : vpcMap.entrySet()) {
			vpcRepository.delete(entry.getValue().getId(), userId);
		}
	}

	/**
	 * 同步安全组和规则
	 *
	 * @param models
	 * @param vendorId
	 * @param userId
	 * @throws Exception
	 */
	private void syncSecurityGroup(List<SecurityGroupModel> models, Map<String, Long> vpcMap, Long vendorId, Long userId, String region) throws Exception {
		// 当安全组为空时,删除数据库残留数据
		if (models == null) {
			return;
		}
		if (models.isEmpty()) {
			securityGroupRepository.removeByVid(vendorId, region, userId);
			return;
		}
		List<SecurityGroup> groups = securityGroupRepository.listByVendorId(vendorId, region);
		Map<String, SecurityGroup> groupMap = Maps.newHashMap();
		for (SecurityGroup group : groups) {
			groupMap.put(group.getGroupUuid(), group);
		}
		for (SecurityGroupModel model : models) {
			SecurityGroup group = new SecurityGroup();
			if (groupMap.containsKey(model.getGroupUuid())) {
				group = groupMap.get(model.getGroupUuid());
				BeanUtils.copyProperties(model, group);
				group.setVpcId(vpcMap.get(group.getVpcUuid()));
				group.setMenderId(userId);
				securityGroupRepository.update(group);
				securityGroupRuleRepository.removeBySgId(group.getId(), userId);
				for (SecurityGroupRuleModel securityGroupRuleModel : model.getModels()) {
					SecurityGroupRule securityGroupRule = new SecurityGroupRule();
					BeanUtils.copyProperties(securityGroupRuleModel, securityGroupRule);
					securityGroupRule.setCreatorId(userId);
					securityGroupRule.setVendorId(vendorId);
					securityGroupRule.setGroupId(group.getId());
					securityGroupRule.setGroupUuid(group.getGroupUuid());
					securityGroupRuleRepository.save(securityGroupRule);
				}
				groupMap.remove(model.getGroupUuid());
				continue;
			}
			group = JSONObject.parseObject(JSONObject.toJSONString(model), SecurityGroup.class);
			group.setVpcId(vpcMap.get(group.getVpcUuid()));
			group.preSave(userId, userId, vendorId, 0L, 0L);
			securityGroupRepository.save(group);
			for (SecurityGroupRuleModel securityGroupRuleModel : model.getModels()) {
				SecurityGroupRule securityGroupRule = new SecurityGroupRule();
				BeanUtils.copyProperties(securityGroupRuleModel, securityGroupRule);
				securityGroupRule.setCreatorId(userId);
				securityGroupRule.setVendorId(vendorId);
				securityGroupRule.setGroupId(group.getId());
				securityGroupRule.setGroupUuid(group.getGroupUuid());
				securityGroupRuleRepository.save(securityGroupRule);
			}
		}
		// 删除不存在的安全组
		for (Entry<String, SecurityGroup> entry : groupMap.entrySet()) {
			securityGroupRepository.remove(entry.getValue().getId(), userId);
		}
	}

	/**
	 * 同步所属域
	 *
	 * @param userId
	 * @throws Exception
	 */
	private void syncRegions(List<RegionModel> regionModels, CloudVendor vendor, Long userId, String regionId) throws Exception {
		if (regionModels == null) {
			return;
		}
		if (regionModels.isEmpty()) {
			regionRepository.deleteByVid(vendor.getId(), regionId);
			zoneRepository.deleteByRegionId(regionId, vendor.getId());
			return;
		}
		for (RegionModel model : regionModels) {
			// 同步区
			syncZone(model.getZones(), model.getCode(), vendor, userId);
		}
	}

	private void syncZone(List<ZoneModel> models, String regionId, CloudVendor vendor, Long userId) throws Exception {
		if (models == null) {
			return;
		}
		if (models.isEmpty()) {
			zoneRepository.deleteByRegionId(regionId, vendor.getId());
			return;
		}
		List<Zone> zones = zoneRepository.listByRegionId(regionId, vendor.getId());
		Map<String, Zone> zoneMap = Maps.newHashMap();
		for (Zone zone : zones) {
			zoneMap.put(zone.getZoneId(), zone);
		}
		Zone zone = null;
		for (ZoneModel model : models) {
			zone = new Zone();
			if (zoneMap.containsKey(model.getZoneId())) {
				zone = zoneMap.get(model.getZoneId());
				BeanUtils.copyProperties(model, zone);
				zone.setVendorId(vendor.getId());
				zone.setRegionId(regionId);
				zoneRepository.update(zone);
				zoneMap.remove(model.getZoneId());
				continue;
			}
			BeanUtils.copyProperties(model, zone);
			zone.setVendorId(vendor.getId());
			zone.setRegionId(regionId);
			zoneRepository.save(zone);
			zoneMap.remove(model.getZoneId());
		}
		for (Map.Entry<String, Zone> entry : zoneMap.entrySet()) {
			zoneRepository.delete(entry.getValue().getId());
		}

	}

	/**
	 * 同步云主机
	 *
	 * @param serverModels
	 * @param vendor
	 * @param userId
	 * @param region
	 * @param type
	 * @param serverMap
	 * @param infos
	 * @param infos
	 * @throws Exception
	 */
	private void syncServer(List<ServerModel> serverModels, CloudVendor vendor, Long userId, Region region, String type,
		Map<String, CloudServer> serverMap, List<CmdbInfo> infos) throws Exception {
		if (serverModels == null) {
			return;
		}
		if (serverModels.isEmpty()) {
			List<CloudServer> servers = cloudServerRepository.listByVendorId(vendor.getId(), region.getRegionId());
			for (CloudServer server : servers) {
				serverSgroupRepository.removeBySid(server.getId());
				volumeRepository.detachVolumes(server.getId(), userId);
//				serverLabelRepository.deleteByTarget(server.getId(), "VM");
				// cmdb：删除云主机
				infos.add(CmdbInfoConvertor.getInfo(server, "delete", null));
			}
			cloudServerRepository.removeByVid(vendor.getId(), region.getRegionId(), userId);
			// 删除资源表
			resourceRepository.removeByVidReg(vendor.getId(), region.getRegionId(), userId);
			return;
		}
		// 获取平台云主机信息
		List<CloudServer> servers = cloudServerRepository.listByVendorId(vendor.getId(), region.getRegionId());
		Map<String, CloudServer> cloudSeverMap = Maps.newHashMap();
		for (CloudServer server : servers) {
			cloudSeverMap.put(server.getInstanceId(), server);
		}
		// 获取平台安全组信息
		List<SecurityGroup> securityGroups = securityGroupRepository.listByVendorId(vendor.getId(), region.getRegionId());
		Map<String, Long> groupMap = Maps.newHashMap();
		for (SecurityGroup group : securityGroups) {
			groupMap.put(group.getName(), group.getId());
		}
		CloudServer vm = null;
		for (ServerModel server : serverModels) {
			List<CmdbRelation> relations = new ArrayList<>();
			relations.add(new CmdbRelation(ModuleCode.REGION.name(), 1L, ListUtils.getList(region.getGuid())));
			Flavor flavor = flavorRepository.getByFlavorUuid(server.getFlavorUuid());
			// 更新已创建的云主机
			if (cloudSeverMap.containsKey(server.getInstanceId())) {
				vm = cloudSeverMap.get(server.getInstanceId());

				String account = vm.getAccount();
				if (StringUtils.hasText(account)) {
					Image image = imageRepository.getByImageUuid(server.getImageUuid());
					if (null != image) {
						account = image.getDefaultUser();
					}
				}
				server.setAccount(account);
				server.setPassword(vm.getPassword());
				BeanUtils.copyProperties(server, vm);

				vm.setOsCategory(server.getOsCategory());
				vm.setOsName(server.getOsName());
				vm.setOsVersion(server.getOsVersion());
				if ("error".equalsIgnoreCase(server.getStatus())) {
					vm.setStatus(BocloudStatus.Server.EXCEPTION.name());
				} else {
					vm.setStatus(server.getStatus());
				}

				List<Long> sgIds = null;
				String groups = server.getGroups();
				if (!StringUtils.hasText(groups)) {
					List<String> groupList = JSONArray.parseArray(groups, String.class);
					if (null != groupList && groupList.size() > 0) {
						sgIds = new ArrayList<Long>();
						for (String sgName : groupList) {
							sgIds.add(groupMap.get(sgName));
						}
					}
				}

				vm.setHostId(0L);
				vm.setPassword(server.getPassword());
				vm.setIsTemplate(false);
				vm.setGmtVmCreate(server.getGmtVmCreate());
				vm.setPrivateIps(server.getPrivateIps());
				if (null != flavor) {
					vm.setCpu(flavor.getCpu());
					vm.setMemory(flavor.getMemory());
				}
				vm.setRegionId(region.getRegionId());
				vm.setVendorId(vendor.getId());
				setSubnetUuid(vm);
				cloudServerRepository.update(vm);
				// CMDB更新集群数据
				infos.add(CmdbInfoConvertor.getInfo(vm, null, relations));
				// 更新资源表
				updateResource(vm, vendor, region.getRegionId(), userId);
				cloudSeverMap.remove(vm.getInstanceId());
				// 更新云主机绑定的安全组
				serverSgroupRepository.removeBySid(vm.getId());
				updateSGroup(vm.getId(), JSON.toJSONString(server.getSecurityGroups()), groupMap);
				serverMap.remove(vm.getInstanceId());
//				syncTag(server.getTagModels(), vendor.getId(), userId, region.getRegionId(), vm.getInstanceId());
				continue;
			}
			vm = new CloudServer();
			BeanUtils.copyProperties(server, vm);
			if ("error".equalsIgnoreCase(server.getStatus())) {
				vm.setStatus(BocloudStatus.Server.EXCEPTION.name());
			} else {
				vm.setStatus(server.getStatus());
			}
			vm.setVendorId(vendor.getId());
			vm.setRegionId(region.getRegionId());
			vm.setIsTemplate(false);
			vm.setResourceId(IDFactory.instance().uuid());
			vm.setVendorType(type);
			vm.setGmtVmCreate(server.getGmtVmCreate());
			vm.setPrivateIps(server.getPrivateIps());
			vm.setMenderId(0L);
			vm.setOwnerId(0L);
			vm.setTenantId(0L);
			vm.setProjectId(0L);

			List<Long> sgIds = null;
			String groups = server.getGroups();
			if (!StringUtils.hasText(groups)) {
				List<String> groupList = JSONArray.parseArray(groups, String.class);
				if (null != groupList && groupList.size() > 0) {
					sgIds = new ArrayList<Long>();
					for (String sgName : groupList) {
						sgIds.add(groupMap.get(sgName));
					}
				}
			}
			vm.setRecycle(false);
			vm.preSave(userId, userId, vendor.getId(), 0L, null, null, 0L, 0L);
			if (StringUtils.hasText(vm.getOsCategory())) {
				vm.setOsCategory(OSCategory.LINUX.name());
			}
			String account = vm.getAccount();
			if (StringUtils.hasText(account)) {
				Image image = imageRepository.getByImageUuid(vm.getImageUuid());
				if (null != image) {
					account = image.getDefaultUser();
				}
			}
			server.setAccount(account);
			if (null != flavor) {
				vm.setCpu(flavor.getCpu());
				vm.setMemory(flavor.getMemory());
			}
			setSubnetUuid(vm);
			cloudServerRepository.save(vm);
			// CMDB更新集群数据
			infos.add(CmdbInfoConvertor.getInfo(vm, null, relations));
			// 更新资源表
			updateResource(vm, vendor, region.getRegionId(), userId);
			serverSgroupRepository.removeBySid(vm.getId());
			updateSGroup(vm.getId(), JSON.toJSONString(server.getSecurityGroups()), groupMap);

//			syncTag(server.getTagModels(), vendor.getId(), userId, region.getRegionId(), vm.getInstanceId());
		}
		for (Map.Entry<String, CloudServer> entry : cloudSeverMap.entrySet()) {
			CloudServer server = entry.getValue();
			resourceRepository
				.remove(server.getId(), ResourceCategory.Computer.name(), ResourceCatalog.LOGICAL.name(), userId);
			// cmdb：删除云主机
			infos.add(CmdbInfoConvertor.getInfo(entry.getValue(), "delete", null));
			volumeRepository.detachVolumes(server.getId(), userId);
			serverSgroupRepository.removeBySid(server.getId());
			cloudServerRepository.remove(server.getId(), userId);
//			serverLabelRepository.deleteByTarget(server.getId(), "VM");
			tagRepository.removeByRes(vendor.getId(), region.getRegionId(), server.getInstanceId(), "instance");
		}
	}

	private void setSubnetUuid(CloudServer server) {
		List<JSONObject> parseArray = JSONObject.parseArray(server.getPrivateIps(), JSONObject.class);
		for (JSONObject netObject : parseArray) {
			if (server.getManagerIp().equalsIgnoreCase(netObject.getString("address"))) {
				server.setSubnetUuid(netObject.getString("subnetUuid"));
			}
		}
	}

	/**
	 * 更新资源表相关信息
	 *
	 * @param server
	 * @param vendor
	 * @param userId
	 * @throws Exception
	 */
	private void updateResource(CloudServer server, CloudVendor vendor, String region, Long userId) throws Exception {
		// 更新资源表
		Resource resource =
			resourceRepository.query(ResourceCategory.Computer.name(), ResourceCatalog.LOGICAL.name(), server.getId());
		// 保存资源
		List<String> ips = Lists.newArrayList();
		if (!StringUtils.hasText(server.getPrivateIps())) {
			List<JSONObject> objects = JSONObject.parseArray(server.getPrivateIps(), JSONObject.class);
			for (JSONObject object : objects) {
				ips.add(object.getString("address"));
			}
		}
		if (null != resource) {
			resource.setStatus(server.getStatus());
			resource.setPrivateIps(JSONObject.toJSONString(ips));
			resource.setRegionId(region);
			resource.setMenderId(userId);
			resource.setAccurated(false);
			resource.setAuthed(false);
			resourceRepository.update(resource);
			server.setResource(resource);
		} else {
			resource =
				new Resource(ResourceCategory.Computer.name(), ResourceCatalog.LOGICAL.name(), server.getId(), null,
					server.getOsCategory(), vendor.getId());
			resource.preSave(server.getName(), server.getStatus(), userId, 0L, 0L);
			resource.setInventory(JSONObject.toJSONString(server));
			resource.setRegionId(region);
			resource.setPrivateIps(JSONObject.toJSONString(ips));
			resource.setOwnerId(userId);
			resource.setAccurated(false);
			resource.setAuthed(false);
			resourceRepository.save(resource);
			server.setResource(resource);
		}
	}

	private void updateSGroup(Long serverId, String groups, Map<String, Long> groupMap) throws Exception {
		if (!StringUtils.hasText(groups)) {
			return;
		}
		List<String> groupList = JSONArray.parseArray(groups, String.class);
		if (ListTool.isEmpty(groupList)) {
			return;
		}
		for (String group : groupList) {
			if ("default".equals(group)) {
				group = "Sys-" + group;
			}
			Long groupId = groupMap.get(group);
			ServerSgroup serverSgroupInfo = serverSgroupRepository.getByServerGroup(serverId, groupId);
			if (null == serverSgroupInfo) {
				ServerSgroup serverSgroup = new ServerSgroup(serverId, groupMap.get(group));
				serverSgroupRepository.save(serverSgroup);
			}
		}
	}

	/**
	 * 同步云硬盘快照
	 *
	 * @param models
	 * @param vendorId
	 * @param userId
	 * @param regionId
	 * @param volumeMap
	 * @throws Exception
	 */
	public void syncSnapshot(List<SnapshotModel> models, Long vendorId, Long userId, String regionId, Map<String, Volume> volumeMap) throws Exception {
		if (models == null) {
			return;
		}
		if (models.isEmpty()) {
			snapshotRepository.removeByVid(vendorId, regionId, userId);
			return;
		}
		List<Snapshot> snapshots = snapshotRepository.listByVid(vendorId, regionId);
		Map<String, Snapshot> snapshotMap = Maps.newHashMap();
		for (Snapshot snapshot : snapshots) {
			snapshotMap.put(snapshot.getSnapshotUuid(), snapshot);
		}
		Region region = regionRepository.getByRegionId(regionId, vendorId);
		for (SnapshotModel model : models) {
			if (snapshotMap.containsKey(model.getSnapshotUuid())) {
				Snapshot snapshot = snapshotMap.get(model.getSnapshotUuid());
				BeanUtils.copyProperties(model, snapshot);
				snapshot.setRegionId(regionId);
				snapshot.setMenderId(userId);
				if (null != region) {
					snapshot.setRegion(region.getId());
				}
				Volume volume = volumeMap.get(model.getVolumeUuid());
				if (null != volume) {
					snapshot.setVolumeId(volume.getId());
					snapshot.setZone(volume.getZone());
				}
				snapshotRepository.update(snapshot);
				snapshotMap.remove(model.getSnapshotUuid());
			} else {
				Snapshot snapshot = JSONObject.parseObject(JSONObject.toJSONString(model), Snapshot.class);
				snapshot.setRegionId(regionId);
				if (null != region) {
					snapshot.setRegion(region.getId());
				}
				Volume volume = volumeMap.get(model.getVolumeUuid());
				if (null != volume) {
					snapshot.setVolumeId(volume.getId());
					snapshot.setZone(volume.getZone());
				}
				snapshot.preSave(userId, userId, vendorId, null, 0L, 0L);
				snapshot.setSource(Snapshot.Source.MANUAL.name());
				snapshotRepository.save(snapshot);
			}
		}
		for (Map.Entry<String, Snapshot> entry : snapshotMap.entrySet()) {
			snapshotRepository.remove(entry.getValue().getId(), userId);
		}
	}

	/**
	 * 同步云硬盘
	 *
	 * @param volumeModels
	 * @param vendorId
	 * @param regionId
	 * @param userId
	 * @param serverMap
	 * @throws Exception
	 */
	private void syncVolume(List<VolumeModel> volumeModels, Long vendorId, String regionId, Long userId, Map<String, CloudServer> serverMap) throws Exception {
		if (volumeModels == null) {
			return;
		}
		if (volumeModels.isEmpty()) {
			volumeRepository.removeByVid(vendorId, regionId, userId);
			return;
		}
		List<Volume> volumes = volumeRepository.listByVendorId(vendorId, regionId);
		Map<String, Volume> volumeMap = Maps.newHashMap();
		for (Volume volume : volumes) {
			volumeMap.put(volume.getVolumeUuid(), volume);
		}
		Volume volume = null;
		for (VolumeModel volumeModel : volumeModels) {
			if (volumeMap.containsKey(volumeModel.getVolumeUuid())) {
				volume = volumeMap.get(volumeModel.getVolumeUuid());
				BeanUtils.copyProperties(volumeModel, volume);
				volume.setRegionId(regionId);
				volume.setVendorId(vendorId);
				volume.setStatus(volumeModel.getStatus().toUpperCase());
				volume.setCreateTime(volumeModel.getCreateTime());
				List<ServerVolumeModel> models = volumeModel.getModels();
				if (null != models && models.size() > 0) {
					ServerVolumeModel serverVolumeModel = models.get(0);
					volume.setDevice(serverVolumeModel.getDevice());
					volume.setInstanceId(serverVolumeModel.getInstanceId());
					CloudServer cloudServer = serverMap.get(serverVolumeModel.getInstanceId());
					if (null != cloudServer) {
						volume.setServerId(cloudServer.getId());
					}
				} else {
					volume.setServerId(null);
				}
				volumeRepository.update(volume);
				volumeMap.remove(volumeModel.getVolumeUuid());
//				syncTag(volumeModel.getTagModels(), vendorId, userId, regionId, volumeModel.getVolumeUuid());
				continue;
			}
			volume = new Volume();
			BeanUtils.copyProperties(volumeModel, volume);
			volume.setMenderId(0L);
			volume.setOwnerId(0L);
			volume.setRegionId(regionId);
			volume.setVendorId(vendorId);
			volume.setProjectId(0L);
			volume.setTenantId(0L);
			volume.setCreatorId(0L);
			volume.setStatus(volumeModel.getStatus().toUpperCase());
			volume.setCreateTime(volumeModel.getCreateTime());
			List<ServerVolumeModel> models = volumeModel.getModels();
			if (null != models && models.size() > 0) {
				ServerVolumeModel serverVolumeModel = models.get(0);
				volume.setDevice(serverVolumeModel.getDevice());
				volume.setInstanceId(serverVolumeModel.getInstanceId());
				CloudServer cloudServer = serverMap.get(serverVolumeModel.getInstanceId());
				if (null != cloudServer) {
					volume.setServerId(cloudServer.getId());
				}
			}
			volumeRepository.save(volume);

//			syncTag(volumeModel.getTagModels(), vendorId, userId, regionId, volumeModel.getVolumeUuid());
		}
		// 删除异常数据
		for (Map.Entry<String, Volume> entry : volumeMap.entrySet()) {
			volumeRepository.remove(entry.getValue().getId(), userId);
			tagRepository.removeByRes(vendorId, regionId, entry.getValue().getVolumeUuid(), "volume");
		}
	}

	/**
	 * 同步云硬盘类型
	 *
	 * @param typeModels
	 * @param vendorId
	 * @param regionId
	 * @param userId
	 * @param zoneMap
	 * @throws Exception
	 */
	private void syncVolumeType(List<VolumeTypeModel> typeModels, Long vendorId, String regionId, Long userId, Map<String, Long> zoneMap) throws Exception {
		if (typeModels == null) {
			return;
		}
		if (typeModels.isEmpty()) {
			volumeTypeRepository.deleteByVendorId(vendorId, regionId);
			return;
		}
		List<VolumeType> volumeTypes = volumeTypeRepository.listByVendorId(vendorId, regionId);
		Map<String, VolumeType> volumeTypeMap = Maps.newHashMap();
		for (VolumeType type : volumeTypes) {
			volumeTypeMap.put(type.getVolumeTypeUuid(), type);
		}
		VolumeType volumeType = null;
		for (VolumeTypeModel typeModel : typeModels) {
			if (volumeTypeMap.containsKey(typeModel.getVolumeTypeUuid())) {
				volumeType = volumeTypeMap.get(typeModel.getVolumeTypeUuid());
				BeanUtils.copyProperties(typeModel, volumeType);
				volumeType.setRegionId(regionId);
				volumeType.setVendorId(vendorId);
				volumeType.setVolumeType(typeModel.getName());
				volumeTypeRepository.update(volumeType);
				volumeTypeMap.remove(typeModel.getVolumeTypeUuid());
				continue;
			}
			volumeType = new VolumeType();
			BeanUtils.copyProperties(typeModel, volumeType);
			volumeType.setRegionId(regionId);
			volumeType.setVendorId(vendorId);
			volumeType.setVolumeType(typeModel.getName());
			volumeTypeRepository.save(volumeType);
			volumeTypeMap.remove(typeModel.getVolumeTypeUuid());
			this.syncVolumeTypeZone(typeModel.getZones(), typeModel.getSoldOutZones(), volumeType.getId(), zoneMap);
		}
		// 删除异常数据
		for (Map.Entry<String, VolumeType> entry : volumeTypeMap.entrySet()) {
			volumeTypeRepository.remove(entry.getValue().getId());
			volumeTypeZoneRepository.removeByVolumeTypeId(entry.getValue().getId());
		}
	}

	private void syncVolumeTypeZone(List<String> zones, List<String> soldOutZones, Long volumeTypeId, Map<String, Long> zoneMap) throws Exception {
		if (zones == null) {
			return;
		}
		if (zones.isEmpty()) {
			volumeTypeZoneRepository.removeByVolumeTypeId(volumeTypeId);
			return;
		}
		List<VolumeTypeZone> relations = volumeTypeZoneRepository.listByVolumeTypeId(volumeTypeId);
		Map<Long, VolumeTypeZone> relationMap = Maps.newHashMap();
		for (VolumeTypeZone volumeTypeZone : relations) {
			relationMap.put(volumeTypeZone.getId(), volumeTypeZone);
		}
		for (String zone : zones) {
			VolumeTypeZone relation = volumeTypeZoneRepository.getByVolumeTypeIdAndZoneId(volumeTypeId, zoneMap.get(zone));
			if (null == relation) {
				if (zoneMap.get(zone) == null) {
					continue;
				}
				VolumeTypeZone newRelation = new VolumeTypeZone();
				newRelation.setVolumeTypeId(volumeTypeId);
				newRelation.setZoneId(zoneMap.get(zone));
				if (soldOutZones != null && soldOutZones.contains(zone)) {
					newRelation.setIsSoldOut(true);
				} else {
					newRelation.setIsSoldOut(false);
				}

				volumeTypeZoneRepository.save(newRelation);
			} else {
				relationMap.remove(relation.getId());
			}
		}
		for (Map.Entry<Long, VolumeTypeZone> entry : relationMap.entrySet()) {
			volumeTypeZoneRepository.remove(entry.getValue().getId());
		}

	}

	/**
	 * 同步镜像
	 *
	 * @param models
	 * @param vendorId
	 * @param userId
	 * @param type
	 * @param imageMap
	 * @throws Exception
	 */
	private void syncImage(List<ImageModel> models, Long vendorId, String regionId, Long userId, String type, Map<String, Image> imageMap) throws Exception {
		if (models == null) {
			return;
		}
		if (models.isEmpty()) {
			imageRepository.removeByVid(vendorId, regionId, userId);
			return;
		}
		List<Image> images = imageRepository.listByVendorId(vendorId, regionId);
		Map<String, Image> imagesMap = Maps.newConcurrentMap();
		for (Image image : images) {
			if (null != image.getImageUuid()) {
				if (imagesMap.containsKey(image.getImageUuid())) {
					imageRepository.remove(image.getId(), userId);
				} else {
					imagesMap.put(image.getImageUuid(), image);
				}
			} else {
				imageRepository.remove(image.getId(), userId);
			}
		}
		List<Image> updateList = new ArrayList<Image>();
		List<Image> instertList = new ArrayList<Image>();
		for (ImageModel model : models) {
			Image image = new Image();
			// 过滤掉非active的镜像
			if ("ACTIVE".equalsIgnoreCase(model.getStatus())) {
				if (imagesMap.containsKey(model.getImageUuid())) {
					image = imagesMap.get(model.getImageUuid());
					BeanUtils.copyProperties(model, image);
					image.setMenderId(userId);
					image.setVendorType(type);
					image.setVendorId(vendorId);
					image.setRegionId(regionId);
					image.setDefaultUser(model.getDefaultUser());
					updateList.add(image);
					imagesMap.remove(model.getImageUuid());
					continue;
				}
				BeanUtils.copyProperties(model, image);
				image.setVendorId(vendorId);
				image.setCreatorId(userId);
				image.setVendorType(type);
				image.setRegionId(regionId);
				image.setMenderId(userId);
				image.setTenantId(0L);
				image.setProjectId(0L);
				if (!StringUtils.hasText(image.getOsCategory())) {
					image.setOsCategory(image.getOsCategory());
				} else {
					image.setOsCategory("Linux");
				}
				image.setCatalog("VM");
				instertList.add(image);
			} else {
				image = imagesMap.get(model.getImageUuid());
				if (null != image) {
					imageRepository.remove(image.getId(), userId);
				}
			}
		}
		if (!updateList.isEmpty()) {
			imageRepository.batchUpdate(updateList, updateList.size());
		}
		if (!instertList.isEmpty()) {
			imageRepository.batchSave(instertList, instertList.size());
		}
		for (Map.Entry<String, Image> set : imagesMap.entrySet()) {
			imageRepository.remove(set.getValue().getId(), userId);
		}
	}

	/**
	 * 同步规格
	 *
	 * @param models
	 * @param vendorId
	 * @param userId
	 * @param regionId
	 * @throws Exception
	 */
	private void syncFlavor(List<FlavorModel> models, Long vendorId, Long userId, String regionId) throws Exception {
		if (models == null) {
			return;
		}
		if (models.isEmpty()) {
			flavorRepository.removeByVid(vendorId, regionId);
			return;
		}
		List<Flavor> flavors = flavorRepository.listByVendorId(vendorId, regionId);
		Map<String, Flavor> flavorMap = new HashMap<String, Flavor>(8);
		for (Flavor flavor : flavors) {
			flavorMap.put(flavor.getFlavorUuid(), flavor);
		}
		List<Flavor> updateList = new ArrayList<Flavor>();
		List<Flavor> instertList = new ArrayList<Flavor>();
		for (FlavorModel model : models) {
			Flavor flavor = new Flavor();
			if (flavorMap.containsKey(model.getFlavorUuid())) {
				flavor = flavorMap.get(model.getFlavorUuid());
				BeanUtils.copyProperties(model, flavor);
				flavor.setOsExtraSpecs(JSONObject.toJSONString(model.getOsExtraSpecs()));
				flavor.setAttachableQuantity(JSONObject.toJSONString(model.getAttachableQuantity()));
				flavor.setVendorId(vendorId);
				flavor.setRegionId(regionId);
				flavorRepository.update(flavor);
				flavorMap.remove(model.getName());
				continue;
			}
			BeanUtils.copyProperties(model, flavor);
			flavor.setOsExtraSpecs(JSONObject.toJSONString(model.getOsExtraSpecs()));
			flavor.setAttachableQuantity(JSONObject.toJSONString(model.getAttachableQuantity()));
			flavor.setVendorId(vendorId);
			flavor.setRegionId(regionId);
			flavorRepository.save(flavor);
		}

		for (Map.Entry<String, Flavor> entry : flavorMap.entrySet()) {
			flavorRepository.delete(entry.getValue().getId());
		}
	}

	/**
	 * 同步密钥
	 *
	 * @param models
	 * @param vendorId
	 * @param userId
	 * @throws Exception
	 */
	private void syncKeypair(List<KeypairModel> models, String regionId, Long vendorId, Long userId) throws Exception {
		if (models == null) {
			return;
		}
		if (models.isEmpty()) {
			keypairRepository.removeByVid(vendorId, regionId, userId);
			return;
		}
		List<Keypair> keypairs = keypairRepository.listByVid(vendorId, regionId);
		Map<String, Keypair> keypairMap = Maps.newHashMap();
		for (Keypair keypair : keypairs) {
			keypairMap.put(keypair.getName(), keypair);
		}
		for (KeypairModel model : models) {
			Keypair keypair = new Keypair();
			if (keypairMap.containsKey(model.getName())) {
				keypair = keypairMap.get(model.getName());
				BeanUtils.copyProperties(model, keypair);
				model.setGmtCreate(keypair.getGmtCreate());
				model.setUserUuid(keypair.getUserUuid());
				keypair.setMenderId(userId);
				keypair.setGmtModify(new Date());
				keypairRepository.update(keypair);
				keypairMap.remove(keypair.getName());
				continue;
			}
			BeanUtils.copyProperties(model, keypair);
			keypair.setCreatorId(userId);
			keypair.setGmtCreate(model.getGmtCreate());
			keypair.setVendorId(vendorId);
			keypair.setTenantId(0L);
			keypair.setProjectId(0L);
			keypairRepository.save(keypair);
		}
		for (Map.Entry<String, Keypair> entry : keypairMap.entrySet()) {
			keypairRepository.remove(entry.getValue().getId(), userId);
		}
	}

	/**
	 * 同步端口
	 *
	 * @param models
	 * @param vendorId
	 * @param userId
	 * @throws Exception
	 */
	private void syncPort(List<PortModel> models, String regionId, Long vendorId, Long userId) throws Exception {
		if (models == null) {
			return;
		}
		if (models.isEmpty()) {
			portRepository.removeByVid(vendorId, regionId, userId);
			return;
		}
		List<Subnet> subnets = subnetRepository.listByRegion(vendorId, regionId);
		Map<String, Long> subnetMap = new HashMap<>(8);
		for (Subnet subnet : subnets) {
			subnetMap.put(subnet.getSubnetUuid(), subnet.getId());
		}
		List<Port> ports = portRepository.listByVid(vendorId, regionId);
		Map<String, Port> portMap = Maps.newHashMap();
		for (Port port : ports) {
			portMap.put(port.getPortUuid(), port);
		}
		for (PortModel model : models) {
			Port port = new Port();
			if (portMap.containsKey(model.getPortUuid())) {
				port = portMap.get(model.getPortUuid());
				BeanUtils.copyProperties(model, port);
				port.setGmtCreate(port.getGmtCreate());
				port.setMenderId(userId);
				port.setRegionId(regionId);
				port.setGmtModify(new Date());
				portRepository.update(port);
				portMap.remove(port.getPortUuid());
				continue;
			}
			BeanUtils.copyProperties(model, port);
			port.setCreatorId(userId);
			port.setRegionId(regionId);
			port.setGmtCreate(new Date());
			port.setVendorId(vendorId);
			portRepository.save(port);

			List<PortFixedIpModel> portFixedIpModels = model.getPortFixedIps();

			if (portFixedIpModels == null) {
				return;
			}
			if (portFixedIpModels.isEmpty()) {
				portFixedIpRepository.deleteByPortId(port.getId());
				return;
			}
			List<PortFixedIp> portFixedIps = portFixedIpRepository.listByPortId(port.getId());
			Map<String, PortFixedIp> portFixedIpMap = Maps.newHashMap();
			for (PortFixedIp portFixedIp : portFixedIps) {
				portFixedIpMap.put(portFixedIp.getSubnetUuid() + portFixedIp.getIpAddress(), portFixedIp);
			}
			for (PortFixedIpModel portFixedIpModel : portFixedIpModels) {
				PortFixedIp portFixedIp = new PortFixedIp();
				if (portFixedIpMap.containsKey(portFixedIpModel.getSubnetUuid() + portFixedIpModel.getIpAddress())) {
					portFixedIp = portFixedIpMap.get(portFixedIpModel.getSubnetUuid() + portFixedIpModel.getIpAddress());
					BeanUtils.copyProperties(portFixedIpModel, portFixedIp);
					portFixedIp.setPortId(port.getId());
					portFixedIp.setPortUuid(port.getPortUuid());
					portFixedIp.setSubnetId(subnetMap.get(portFixedIp.getSubnetUuid()));
					portFixedIpRepository.update(portFixedIp);
					portMap.remove(portFixedIp.getSubnetUuid() + portFixedIp.getIpAddress());
					continue;
				}
				BeanUtils.copyProperties(portFixedIpModel, portFixedIp);
				portFixedIp.setPortId(port.getId());
				portFixedIp.setPortUuid(port.getPortUuid());
				portFixedIp.setSubnetId(subnetMap.get(portFixedIp.getSubnetUuid()));
				portFixedIpRepository.save(portFixedIp);
			}
			for (Map.Entry<String, PortFixedIp> entry : portFixedIpMap.entrySet()) {
				portFixedIpRepository.delete(entry.getValue().getId());
			}
		}
		for (Map.Entry<String, Port> entry : portMap.entrySet()) {
			portRepository.remove(entry.getValue().getId(), userId);
		}
	}

	private void syncElasticIp(List<ElasticIpModel> models, String region, Long vendorId, Long userId) throws Exception {
		if (models == null) {
			return;
		}
		if (models.isEmpty()) {
			elasticIpRepository.removeByVid(vendorId, userId, region);
			return;
		}
		List<ElasticIp> elasticIps = elasticIpRepository.listByVid(vendorId, region);
		Map<String, ElasticIp> elasticIpMap = Maps.newHashMap();
		for (ElasticIp elasticIp : elasticIps) {
			elasticIpMap.put(elasticIp.getElasticIpUuid(), elasticIp);
		}
		for (ElasticIpModel model : models) {
			ElasticIp elasticIp = new ElasticIp();
			if (elasticIpMap.containsKey(model.getElasticIpUuid())) {
				elasticIp = elasticIpMap.get(model.getElasticIpUuid());
				BeanUtils.copyProperties(model, elasticIp);
				elasticIp.setInstanceId(model.getPortId());
				elasticIp.setVendorId(vendorId);
				elasticIp.setGmtModify(new Date());
				elasticIp.setRegionId(region);
				elasticIp.setCreateTime(model.getCreateTime());
				elasticIpRepository.update(elasticIp);
				elasticIpMap.remove(elasticIp.getElasticIpUuid());
				continue;
			}
			BeanUtils.copyProperties(model, elasticIp);
			elasticIp.setInstanceId(model.getPortId());
			elasticIp.setCreatorId(0L);
			elasticIp.setMenderId(0L);
			elasticIp.setVendorId(vendorId);
			elasticIp.setRegionId(region);
			elasticIp.setCreateTime(model.getCreateTime());
			elasticIpRepository.save(elasticIp);
			elasticIpMap.remove(model.getElasticIpUuid());
		}
		for (Map.Entry<String, ElasticIp> entry : elasticIpMap.entrySet()) {
			elasticIpRepository.remove(entry.getValue().getId(), userId);
		}
	}

//	private void syncBandwidth(List<BandwidthModel> models, String region, Long vendorId, Long userId) throws Exception {
//		if (models == null) {
//			return;
//		}
//		if (models.isEmpty()) {
//			bandwidthRepository.removeByVid(vendorId, userId, region);
//			return;
//		}
//		List<Bandwidth> bandwidths = bandwidthRepository.listByVid(vendorId, region);
//		Map<String, Bandwidth> bandwidthMap = Maps.newHashMap();
//		for (Bandwidth bandwidth : bandwidths) {
//			bandwidthMap.put(bandwidth.getUuid(), bandwidth);
//		}
//		for (BandwidthModel model : models) {
//			Bandwidth bandwidth = new Bandwidth();
//			if (bandwidthMap.containsKey(model.getUuid())) {
//				bandwidth = bandwidthMap.get(model.getUuid());
//				BeanUtils.copyProperties(model, bandwidth);
//				bandwidth.setVendorId(vendorId);
//				bandwidth.setGmtModify(new Date());
//				bandwidth.setRegionId(region);
//				bandwidth.setTenantUuid(model.getEnterpriseProjectId());
//				bandwidthRepository.update(bandwidth);
//				bandwidthMap.remove(bandwidth.getUuid());
//				continue;
//			}
//			BeanUtils.copyProperties(model, bandwidth);
//			bandwidth.setCreatorId(0L);
//			bandwidth.setMenderId(0L);
//			bandwidth.setVendorId(vendorId);
//			bandwidth.setGmtCreate(new Date());
//			bandwidth.setRegionId(region);
//			bandwidth.setTenantUuid(model.getEnterpriseProjectId());
//			bandwidthRepository.save(bandwidth);
//			bandwidthMap.remove(model.getUuid());
//		}
//		for (Map.Entry<String, Bandwidth> entry : bandwidthMap.entrySet()) {
//			bandwidthRepository.remove(entry.getValue().getId(), userId);
//		}
//	}

	/**
	 * 同步nat网关
	 *
	 * @param models
	 * @param vendorId
	 * @param userId
	 * @throws Exception
	 */
	private void syncNatGateway(List<NatGatewayModel> models, String regionId, Long vendorId, Long userId, Map<String, Long> vpcMap, Map<String, Long> subnetMap) throws Exception {
		if (models == null) {
			return;
		}
		if (models.isEmpty()) {
			natGatewayRepository.removeByVid(vendorId, regionId, userId);
			return;
		}
		List<NatGateway> natGateways = natGatewayRepository.listByVendorId(vendorId, regionId);
		Map<String, NatGateway> natGatewayMap = Maps.newHashMap();
		for (NatGateway gateway : natGateways) {
			natGatewayMap.put(gateway.getUuid(), gateway);
		}
		List<NatGateway> updateList = new ArrayList<NatGateway>();
		List<NatGateway> instertList = new ArrayList<NatGateway>();
		for (NatGatewayModel model : models) {
			NatGateway natGateway = new NatGateway();
			if (natGatewayMap.containsKey(model.getUuid())) {
				natGateway = natGatewayMap.get(model.getUuid());
				BeanUtils.copyProperties(model, natGateway);
				natGateway.setMenderId(userId);
				natGateway.setGmtModify(new Date());
				natGateway.setCreateTime(model.getGmtCreate());
				natGateway.setVpcId(vpcMap.get(model.getVpcUuid()));
				natGateway.setSubnetId(subnetMap.get(model.getSubnetUuid()));
				natGatewayRepository.update(natGateway);
				natGatewayMap.remove(natGateway.getUuid());
				continue;
			}
			BeanUtils.copyProperties(model, natGateway);
			natGateway.setCreatorId(userId);
			natGateway.setCreateTime(model.getGmtCreate());
			natGateway.setVendorId(vendorId);
			natGateway.setVpcId(vpcMap.get(model.getVpcUuid()));
			natGateway.setSubnetId(subnetMap.get(model.getSubnetUuid()));
			natGateway.setTenantId(0L);
			natGateway.setProjectId(0L);
			natGatewayRepository.save(natGateway);
		}
		for (Map.Entry<String, NatGateway> entry : natGatewayMap.entrySet()) {
			natGatewayRepository.delete(entry.getValue().getId(), userId);
		}
	}

	/**
	 * 同步nat网关dnat规则
	 *
	 * @param models
	 * @param vendorId
	 * @param userId
	 * @throws Exception
	 */
	private void syncNatGatewayDnatRule(List<NatGatewayDnatRuleModel> models, String regionId, Long vendorId, Long userId, Map<String, Long> natGatewayMap, Map<String, Long> elasticIpMap, Map<String, Long> portMap)
		throws Exception {
		if (models == null) {
			return;
		}
		if (models.isEmpty()) {
			dnatRuleRepository.removeByVid(vendorId, regionId, userId);
			return;
		}
		List<NatGatewayDnatRule> dnatRules = dnatRuleRepository.listByVendorId(vendorId, regionId);
		Map<String, NatGatewayDnatRule> dnatRuleMap = Maps.newHashMap();
		for (NatGatewayDnatRule dnatRule : dnatRules) {
			dnatRuleMap.put(dnatRule.getUuid(), dnatRule);
		}
		List<NatGatewayDnatRule> updateList = new ArrayList<NatGatewayDnatRule>();
		List<NatGatewayDnatRule> instertList = new ArrayList<NatGatewayDnatRule>();
		for (NatGatewayDnatRuleModel model : models) {
			NatGatewayDnatRule dnatRule = new NatGatewayDnatRule();
			if (dnatRuleMap.containsKey(model.getUuid())) {
				dnatRule = dnatRuleMap.get(model.getUuid());
				BeanUtils.copyProperties(model, dnatRule);
				dnatRule.setMenderId(userId);
				dnatRule.setGmtModify(new Date());
				dnatRule.setNatGatewayId(natGatewayMap.get(model.getNatGatewayId()));
				dnatRule.setElasticIpId(elasticIpMap.get(model.getFloatingIpId()));
				dnatRule.setPortId(portMap.get(model.getPortUuid()));
				updateList.add(dnatRule);
				dnatRuleMap.remove(dnatRule.getUuid());
				continue;
			}
			BeanUtils.copyProperties(model, dnatRule);
			dnatRule.setCreatorId(userId);
			dnatRule.setGmtCreate(model.getGmtCreate());
			dnatRule.setVendorId(vendorId);
			dnatRule.setNatGatewayId(natGatewayMap.get(model.getNatGatewayId()));
			dnatRule.setElasticIpId(elasticIpMap.get(model.getFloatingIpId()));
			dnatRule.setPortId(portMap.get(model.getPortUuid()));
			instertList.add(dnatRule);
		}
		if (!updateList.isEmpty()) {
			dnatRuleRepository.batchUpdate(updateList);
		}
		if (!instertList.isEmpty()) {
			dnatRuleRepository.batchSave(instertList);
		}
		for (Map.Entry<String, NatGatewayDnatRule> entry : dnatRuleMap.entrySet()) {
			dnatRuleRepository.delete(entry.getValue().getId(), userId);
		}
	}

	/**
	 * 同步nat网关snat规则
	 *
	 * @param models
	 * @param vendorId
	 * @param userId
	 * @throws Exception
	 */
	private void syncNatGatewaySnatRule(List<NatGatewaySnatRuleModel> models, String regionId, Long vendorId, Long userId, Map<String, Long> natGatewayMap, Map<String, Long> elasticIpMap, Map<String, Long> subnetMap)
		throws Exception {
		if (models == null) {
			return;
		}
		List<NatGatewaySnatRule> snatRules = snatRuleRepository.listByVendorId(vendorId, regionId);
		if (models.isEmpty()) {
			snatRuleRepository.removeByVid(vendorId, regionId, userId);
			for (NatGatewaySnatRule snatRule : snatRules) {
				ruleRelationRepository.removeBySnatRuleId(snatRule.getId());
			}
			return;
		}

		Map<String, NatGatewaySnatRule> snatRuleMap = Maps.newHashMap();
		for (NatGatewaySnatRule snatRule : snatRules) {
			snatRuleMap.put(snatRule.getUuid(), snatRule);
		}
		for (NatGatewaySnatRuleModel model : models) {
			NatGatewaySnatRule snatRule = new NatGatewaySnatRule();
			if (snatRuleMap.containsKey(model.getUuid())) {
				snatRule = snatRuleMap.get(model.getUuid());
				BeanUtils.copyProperties(model, snatRule);
				snatRule.setMenderId(userId);
				snatRule.setGmtModify(new Date());
				snatRule.setNatGatewayId(natGatewayMap.get(model.getNatGatewayId()));
				snatRule.setSubnetId(subnetMap.get(model.getSubnetUuid()));
				snatRuleRepository.update(snatRule);
				List<String> list = Arrays.asList(model.getFloatingIpId().split(",")).stream().map(s -> (s.trim())).collect(Collectors.toList());
				this.syncSnatRuleRelation(list, snatRule.getId(), elasticIpMap);
				snatRuleMap.remove(snatRule.getUuid());
				continue;
			}
			BeanUtils.copyProperties(model, snatRule);
			snatRule.setCreatorId(userId);
			snatRule.setGmtCreate(model.getGmtCreate());
			snatRule.setVendorId(vendorId);
			snatRule.setNatGatewayId(natGatewayMap.get(model.getNatGatewayId()));
			snatRule.setSubnetId(subnetMap.get(model.getSubnetUuid()));
			snatRuleRepository.save(snatRule);
			snatRuleMap.remove(model.getUuid());
			List<String> list = Arrays.asList(model.getFloatingIpId().split(",")).stream().map(s -> (s.trim())).collect(Collectors.toList());
			this.syncSnatRuleRelation(list, snatRule.getId(), elasticIpMap);
		}
		for (Map.Entry<String, NatGatewaySnatRule> entry : snatRuleMap.entrySet()) {
			snatRuleRepository.delete(entry.getValue().getId(), userId);
			ruleRelationRepository.removeBySnatRuleId(entry.getValue().getId());
		}
	}

	private void syncSnatRuleRelation(List<String> elasticIpIds, Long snatRuleId, Map<String, Long> elasticIpMap) throws Exception {
		if (elasticIpIds == null) {
			return;
		}
		if (elasticIpIds.isEmpty()) {
			ruleRelationRepository.removeBySnatRuleId(snatRuleId);
			return;
		}
		List<NatGatewaySnatRuleRelation> relations = ruleRelationRepository.listBySnatRuleId(snatRuleId);
		Map<Long, NatGatewaySnatRuleRelation> ruleRelationMap = Maps.newHashMap();
		for (NatGatewaySnatRuleRelation snatRule : relations) {
			ruleRelationMap.put(snatRule.getId(), snatRule);
		}
		for (String elasticIpId : elasticIpIds) {
			if (!elasticIpMap.containsKey(elasticIpId)) {
				continue;
			}
			NatGatewaySnatRuleRelation ruleRelation =
				ruleRelationRepository.getBySnatRuleIdAndElasticIpId(snatRuleId, elasticIpMap.get(elasticIpId));
			if (null == ruleRelation) {
				NatGatewaySnatRuleRelation relation = new NatGatewaySnatRuleRelation();
				relation.setSnatRuleId(snatRuleId);
				relation.setElasticIpId(elasticIpMap.get(elasticIpId));
				ruleRelationRepository.save(relation);
			} else {
				ruleRelationMap.remove(ruleRelation.getId());
			}
		}
		for (Map.Entry<Long, NatGatewaySnatRuleRelation> entry : ruleRelationMap.entrySet()) {
			ruleRelationRepository.remove(entry.getValue().getId());
		}

	}

	/**
	 * 同步负载均衡
	 *
	 * @param models
	 * @param vendorId
	 * @param userId
	 * @throws Exception
	 */
	private void syncLoadBalancer(List<LbModel> models, Map<String, Long> vpcMap, Map<String, Subnet> neutronSubnetMap,
		Long vendorId, Long userId, String region, Map<String, Long> subnetMap, Map<String, Long> elasticIpMap) throws Exception {
		if (models == null) {
			return;
		}
		if (models.isEmpty()) {
			loadBalancerRepository.removeByVid(vendorId, region, userId);
			return;
		}
		List<LoadBalancer> balancers = loadBalancerRepository.listByVid(vendorId, region);
		Map<String, LoadBalancer> balancerMap = Maps.newHashMap();
		for (LoadBalancer balancer : balancers) {
			balancerMap.put(balancer.getLbUuid(), balancer);
		}
		for (LbModel model : models) {
			LoadBalancer balancer = new LoadBalancer();
			if (balancerMap.containsKey(model.getLbUuid())) {
				balancer = balancerMap.get(model.getLbUuid());
				BeanUtils.copyProperties(model, balancer);
				balancer.setVpcId(vpcMap.get(balancer.getVpcUuid()));
				Long eipId = elasticIpMap.get(model.getElasticIpUuid());
				balancer.setElasticIpId(eipId);
				Subnet neutronSubnet = neutronSubnetMap.get(model.getAfterSubnetUuid());
				if (null != neutronSubnet) {
					balancer.setSubnetUuid(neutronSubnet.getSubnetUuid());
					balancer.setSubnetId(neutronSubnet.getId());
				}
				balancer.setAfterSubnetUuid(model.getAfterSubnetUuid());
				balancer.setMenderId(userId);
				balancer.setVendorId(vendorId);
				balancer.setGmtModify(new Date());
				balancer.setCreateTime(model.getCreateTime());
				balancer.setRegion(region);
				balancer.setAvailabilityZones(model.getAvailabilityZones().toJSONString());
				loadBalancerRepository.update(balancer);
				balancerMap.remove(balancer.getLbUuid());
				continue;
			}
			BeanUtils.copyProperties(model, balancer);
			balancer.setVpcId(vpcMap.get(balancer.getVpcUuid()));
			Long eipId = elasticIpMap.get(model.getElasticIpUuid());
			balancer.setElasticIpId(eipId);
			Subnet neutronSubnet = neutronSubnetMap.get(model.getAfterSubnetUuid());
			if (null != neutronSubnet) {
				balancer.setSubnetUuid(neutronSubnet.getSubnetUuid());
				balancer.setSubnetId(neutronSubnet.getId());
			}
			balancer.setAfterSubnetUuid(model.getAfterSubnetUuid());

			balancer.setCreatorId(userId);
			balancer.setVendorId(vendorId);
			balancer.setCreateTime(model.getCreateTime());
			balancer.setRegion(region);
			balancer.setAvailabilityZones(model.getAvailabilityZones().toJSONString());
			loadBalancerRepository.save(balancer);
			balancerMap.remove(balancer.getLbUuid());
		}
		for (Map.Entry<String, LoadBalancer> entry : balancerMap.entrySet()) {
			loadBalancerRepository.remove(entry.getValue().getId(), userId);
		}
	}

	/**
	 * 同步监听器
	 *
	 * @param models
	 * @param vendorId
	 * @param userId
	 * @throws Exception
	 */
	private void syncLbListener(List<LbListenerModel> models, Map<String, Long> balancerMap, Long vendorId, Long userId,
		String region) throws Exception {
		if (models == null) {
			return;
		}
		if (models.isEmpty()) {
			lbListenerRepository.removeByVid(vendorId, userId, region);
			return;
		}
		List<LbListener> listenerList = lbListenerRepository.listByVid(vendorId, region);
		Map<String, LbListener> listenerMap = Maps.newHashMap();
		for (LbListener lbListener : listenerList) {
			listenerMap.put(lbListener.getListenerUuid(), lbListener);
		}
		for (LbListenerModel model : models) {
			LbListener lbListener = new LbListener();
			if (listenerMap.containsKey(model.getListenerUuid())) {
				lbListener = listenerMap.get(model.getListenerUuid());
				BeanUtils.copyProperties(model, lbListener);
				lbListener.setLbId(balancerMap.get(lbListener.getLbUuid()));
				lbListener.setVendorId(vendorId);
				lbListener.setGmtModify(new Date());
				lbListener.setRegionId(region);
//				lbListener.setSniContainerRefs(JSONObject.toJSONString(model.getSnicontainerRefs()));
				lbListener.setConfiguration(JSONObject.toJSONString(model));
				lbListenerRepository.update(lbListener);
				listenerMap.remove(model.getListenerUuid());
				continue;
			}
			BeanUtils.copyProperties(model, lbListener);
			lbListener.setLbId(balancerMap.get(lbListener.getLbUuid()));

			lbListener.setVendorId(vendorId);
			lbListener.setRegionId(region);
//			lbListener.setSniContainerRefs(JSONObject.toJSONString(model.getSnicontainerRefs()));
			lbListener.setConfiguration(JSONObject.toJSONString(model));
			lbListenerRepository.save(lbListener);
			listenerMap.remove(model.getListenerUuid());
		}
		for (Map.Entry<String, LbListener> entry : listenerMap.entrySet()) {
			lbListenerRepository.remove(entry.getValue().getId(), userId);
		}
	}

	/**
	 * 后端云服务器组
	 *
	 * @param models
	 * @param vendorId
	 * @param userId
	 * @throws Exception
	 */
	private void syncLbPool(List<LbPoolModel> models, Map<String, Long> listenerMap, Map<String, Long> balancerMap, Long vendorId, Long userId, String region) throws Exception {
		if (models == null) {
			return;
		}
		if (models.isEmpty()) {
			lbPoolRepository.removeByVid(vendorId, userId, region);
			return;
		}
		List<LbPool> lbTargetGroups = lbPoolRepository.listByVid(vendorId, region);
		Map<String, LbPool> targetGroupMap = Maps.newHashMap();
		for (LbPool lbTargetGroup : lbTargetGroups) {
			targetGroupMap.put(lbTargetGroup.getPoolUuid(), lbTargetGroup);
		}
		for (LbPoolModel model : models) {
			LbPool lbTargetGroup = new LbPool();
			if (targetGroupMap.containsKey(model.getPoolUuid())) {
				lbTargetGroup = targetGroupMap.get(model.getPoolUuid());
				BeanUtils.copyProperties(model, lbTargetGroup);
				lbTargetGroup.setListenerId(listenerMap.get(lbTargetGroup.getListenerUuid()));
				lbTargetGroup.setLbId(balancerMap.get(lbTargetGroup.getLbUuid()));
				lbTargetGroup.setMenderId(userId);
				lbTargetGroup.setVendorId(vendorId);
				lbTargetGroup.setGmtModify(new Date());
				lbTargetGroup.setRegionId(region);
				lbPoolRepository.update(lbTargetGroup);
				targetGroupMap.remove(lbTargetGroup.getPoolUuid());
				continue;
			}
			BeanUtils.copyProperties(model, lbTargetGroup);
			lbTargetGroup.setListenerId(listenerMap.get(lbTargetGroup.getListenerUuid()));
			lbTargetGroup.setLbId(balancerMap.get(lbTargetGroup.getLbUuid()));
			lbTargetGroup.setCreatorId(userId);
			lbTargetGroup.setVendorId(vendorId);
			lbTargetGroup.setGmtCreate(new Date());
			lbTargetGroup.setRegionId(region);
			lbPoolRepository.save(lbTargetGroup);
			targetGroupMap.remove(lbTargetGroup.getPoolUuid());
		}
		for (Map.Entry<String, LbPool> entry : targetGroupMap.entrySet()) {
			lbPoolRepository.remove(entry.getValue().getId(), userId);
		}
	}

	/**
	 * 后端云服务器
	 *
	 * @param models
	 * @param vendorId
	 * @param userId
	 * @throws Exception
	 */
	private void syncLbMember(List<LbMemberModel> models, Map<String, LbPool> tgMap, Map<String, Subnet> neutronSubnetMap, Long vendorId, Long userId, String region) throws Exception {
		if (models == null) {
			return;
		}
		if (models.isEmpty()) {
			lbMemberRepository.removeByVid(vendorId, userId, region);
			return;
		}
		List<LbMember> lbTargets = lbMemberRepository.listByVid(vendorId, region);
		Map<String, LbMember> targetMap = Maps.newHashMap();
		for (LbMember lbTarget : lbTargets) {
			targetMap.put(lbTarget.getPoolUuid() + lbTarget.getMemberUuid(), lbTarget);
		}
		for (LbMemberModel model : models) {
			LbMember lbTarget = new LbMember();
			String uuid = model.getPoolUuid() + model.getMemberUuid();
			if (targetMap.containsKey(uuid)) {
				lbTarget = targetMap.get(uuid);
				BeanUtils.copyProperties(model, lbTarget);
				LbPool pool = tgMap.get(lbTarget.getPoolUuid());
				if (null != pool) {
					lbTarget.setPoolId(pool.getId());
					lbTarget.setListenerId(pool.getListenerId());
					lbTarget.setLbId(pool.getLbId());
				}
				Subnet subnet = neutronSubnetMap.get(lbTarget.getSubnetUuid());
				if (null != subnet) {
					lbTarget.setSubnetId(subnet.getId());
				}
				PortFixedIp portFixedIp = portFixedIpRepository.getPortFixedBySubnet(lbTarget.getSubnetUuid(), lbTarget.getAddress());
				if (null != portFixedIp) {
					Port port = portRepository.query(portFixedIp.getPortId());
					if (null != port && port.getDeviceOwner().contains("compute")) {
						CloudServer cloudServer = cloudServerRepository.get(vendorId, port.getDeviceUuid());
						if (null != cloudServer) {
							lbTarget.setName(cloudServer.getName());
							lbTarget.setStatus(cloudServer.getStatus());
							lbTarget.setInstanceId(cloudServer.getInstanceId());
						}
					}
				}
				lbTarget.setVendorId(vendorId);
				lbTarget.setGmtModify(new Date());
				lbTarget.setRegionId(region);
				lbMemberRepository.update(lbTarget);
				targetMap.remove(uuid);
				continue;
			}
			BeanUtils.copyProperties(model, lbTarget);
			LbPool pool = tgMap.get(lbTarget.getPoolUuid());
			if (null != pool) {
				lbTarget.setPoolId(pool.getId());
				lbTarget.setListenerId(pool.getListenerId());
				lbTarget.setLbId(pool.getLbId());
			}
			Subnet subnet = neutronSubnetMap.get(lbTarget.getSubnetUuid());
			if (null != subnet) {
				lbTarget.setSubnetId(subnet.getId());
			}
			PortFixedIp portFixedIp = portFixedIpRepository.getPortFixedBySubnet(lbTarget.getSubnetUuid(), lbTarget.getAddress());
			if (null != portFixedIp) {
				Port port = portRepository.query(portFixedIp.getPortId());
				if (null != port && port.getDeviceOwner().contains("compute")) {
					CloudServer cloudServer = cloudServerRepository.get(vendorId, port.getDeviceUuid());
					if (null != cloudServer) {
						lbTarget.setName(cloudServer.getName());
						lbTarget.setStatus(cloudServer.getStatus());
						lbTarget.setInstanceId(cloudServer.getInstanceId());
					}
				}
			}

			lbTarget.setCreatorId(0L);
			lbTarget.setVendorId(vendorId);
			lbTarget.setGmtCreate(new Date());
			lbTarget.setRegionId(region);
			lbMemberRepository.save(lbTarget);
			targetMap.remove(lbTarget.getPoolUuid() + lbTarget.getMemberUuid());
		}
		for (Map.Entry<String, LbMember> entry : targetMap.entrySet()) {
			lbMemberRepository.remove(entry.getValue().getId(), userId);
		}
	}

	/**
	 * 后端云服务器
	 *
	 * @param models
	 * @param vendorId
	 * @param userId
	 * @throws Exception
	 */
	private void syncHealthMonitor(List<HealthMonitorModel> models, Map<String, LbPool> lbPoolMap, Long vendorId, Long userId, String region) throws Exception {
		if (models == null) {
			return;
		}
		if (models.isEmpty()) {
			healthMonitorRepository.removeByVid(vendorId, userId, region);
			return;
		}
		List<HealthMonitor> lbTargets = healthMonitorRepository.listByVid(vendorId, region);
		Map<String, HealthMonitor> targetMap = Maps.newHashMap();
		for (HealthMonitor lbTarget : lbTargets) {
			targetMap.put(lbTarget.getPoolUuid() + lbTarget.getHealthUuid(), lbTarget);
		}
		for (HealthMonitorModel model : models) {
			HealthMonitor lbTarget = new HealthMonitor();
			if (targetMap.containsKey(model.getPoolUuid() + model.getHealthUuid())) {
				lbTarget = targetMap.get(model.getPoolUuid() + model.getHealthUuid());
				BeanUtils.copyProperties(model, lbTarget);
				LbPool lbPool = lbPoolMap.get(lbTarget.getPoolUuid());
				if (null != lbPool) {
					lbTarget.setPoolId(lbPool.getId());
					lbTarget.setListenerId(lbPool.getListenerId());
				}

				lbTarget.setMenderId(userId);
				lbTarget.setVendorId(vendorId);
				lbTarget.setGmtModify(new Date());
				lbTarget.setRegionId(region);
				healthMonitorRepository.update(lbTarget);
				targetMap.remove(lbTarget.getPoolUuid() + lbTarget.getHealthUuid());
				continue;
			}
			BeanUtils.copyProperties(model, lbTarget);
			LbPool lbPool = lbPoolMap.get(lbTarget.getPoolUuid());
			if (null != lbPool) {
				lbTarget.setPoolId(lbPool.getId());
				lbTarget.setListenerId(lbPool.getListenerId());
			}
			lbTarget.setCreatorId(userId);
			lbTarget.setVendorId(vendorId);
			lbTarget.setGmtCreate(new Date());
			lbTarget.setRegionId(region);
			healthMonitorRepository.save(lbTarget);
			targetMap.remove(lbTarget.getPoolUuid() + lbTarget.getHealthUuid());
		}
		for (Map.Entry<String, HealthMonitor> entry : targetMap.entrySet()) {
			healthMonitorRepository.remove(entry.getValue().getId(), userId);
		}
	}

	/**
	 * 转发策略
	 *
	 * @param models
	 * @param vendorId
	 * @param userId
	 * @throws Exception
	 */
	private void syncL7policy(List<LbListenerPolicyModel> models, Map<String, Long> lbPoolMap, Map<String, Long> listenerMap, Long vendorId, Long userId, String region) throws Exception {
		if (models == null) {
			return;
		}
		if (models.isEmpty()) {
			lbListenerPolicyRepository.removeByVid(vendorId, userId, region);
			return;
		}
		List<LbListenerPolicy> lbTargets = lbListenerPolicyRepository.listByVid(vendorId, region);
		Map<String, LbListenerPolicy> targetMap = Maps.newHashMap();
		for (LbListenerPolicy lbTarget : lbTargets) {
			targetMap.put(lbTarget.getPolicyUuid(), lbTarget);
		}
		for (LbListenerPolicyModel model : models) {
			LbListenerPolicy lbTarget = new LbListenerPolicy();
			if (targetMap.containsKey(model.getPolicyUuid())) {
				lbTarget = targetMap.get(model.getPolicyUuid());
				BeanUtils.copyProperties(model, lbTarget);
				lbTarget.setListenerId(listenerMap.get(lbTarget.getListenerUuid()));
				lbTarget.setRedirectListenerId(listenerMap.get(lbTarget.getRedirectListenerUuid()));
				lbTarget.setRedirectPoolId(lbPoolMap.get(lbTarget.getRedirectPoolUuid()));
				lbTarget.setMenderId(userId);
				lbTarget.setVendorId(vendorId);
				lbTarget.setGmtModify(new Date());
				lbTarget.setRegionId(region);
				lbListenerPolicyRepository.update(lbTarget);
				targetMap.remove(lbTarget.getPolicyUuid());
				continue;
			}
			BeanUtils.copyProperties(model, lbTarget);
			lbTarget.setListenerId(listenerMap.get(lbTarget.getListenerUuid()));
			lbTarget.setRedirectListenerId(listenerMap.get(lbTarget.getRedirectListenerUuid()));
			lbTarget.setRedirectPoolId(lbPoolMap.get(lbTarget.getRedirectPoolUuid()));
			lbTarget.setCreatorId(userId);
			lbTarget.setVendorId(vendorId);
			lbTarget.setGmtCreate(new Date());
			lbTarget.setRegionId(region);
			lbListenerPolicyRepository.save(lbTarget);
			targetMap.remove(lbTarget.getPolicyUuid());
		}
		for (Map.Entry<String, LbListenerPolicy> entry : targetMap.entrySet()) {
			lbListenerPolicyRepository.remove(entry.getValue().getId(), userId);
		}
	}

	/**
	 * 准发规则
	 *
	 * @param models
	 * @param vendorId
	 * @param userId
	 * @throws Exception
	 */
	private void syncL7rule(List<LbListenerRuleModel> models, Map<String, Long> lbPolicyMap, Long vendorId, Long userId,
		String region) throws Exception {
		if (models == null) {
			return;
		}
		if (models.isEmpty()) {
			lbListenerRuleRepository.removeByVid(vendorId, userId, region);
			return;
		}
		List<LbListenerRule> lbTargets = lbListenerRuleRepository.listByVid(vendorId, region);
		Map<String, LbListenerRule> targetMap = Maps.newHashMap();
		for (LbListenerRule lbTarget : lbTargets) {
			targetMap.put(lbTarget.getRuleUuid() + lbTarget.getPolicyUuid(), lbTarget);
		}
		for (LbListenerRuleModel model : models) {
			LbListenerRule lbTarget = new LbListenerRule();
			if (targetMap.containsKey(model.getRuleUuid() + model.getPolicyUuid())) {
				lbTarget = targetMap.get(model.getRuleUuid() + model.getPolicyUuid());
				BeanUtils.copyProperties(model, lbTarget);
				lbTarget.setPolicyId(lbPolicyMap.get(lbTarget.getPolicyUuid()));

				lbTarget.setMenderId(userId);
				lbTarget.setVendorId(vendorId);
				lbTarget.setGmtModify(new Date());
				lbTarget.setRegionId(region);
				lbListenerRuleRepository.update(lbTarget);
				targetMap.remove(lbTarget.getRuleUuid() + lbTarget.getPolicyUuid());
				continue;
			}
			BeanUtils.copyProperties(model, lbTarget);
			lbTarget.setPolicyId(lbPolicyMap.get(lbTarget.getPolicyUuid()));
			lbTarget.setCreatorId(userId);
			lbTarget.setVendorId(vendorId);
			lbTarget.setGmtCreate(new Date());
			lbTarget.setRegionId(region);
			lbListenerRuleRepository.save(lbTarget);
			targetMap.remove(lbTarget.getRuleUuid() + lbTarget.getPolicyUuid());
		}
		for (Map.Entry<String, LbListenerRule> entry : targetMap.entrySet()) {
			lbListenerRuleRepository.remove(entry.getValue().getId(), userId);
		}
	}

//	private void syncCeratificate(List<LbCertificateModel> models, Long vendorId, Long userId, String region) throws Exception {
//		if (models == null) {
//			return;
//		}
//		if (models.isEmpty()) {
//			ceratificateRepository.removeByVid(vendorId, userId, region);
//			return;
//		}
//		List<LbCeratificate> lbTargets = ceratificateRepository.listByVid(vendorId, region);
//		Map<String, LbCeratificate> targetMap = Maps.newHashMap();
//		for (LbCeratificate lbTarget : lbTargets) {
//			targetMap.put(lbTarget.getUuid(), lbTarget);
//		}
//		for (LbCertificateModel model : models) {
//			LbCeratificate lbCeratificate = new LbCeratificate();
//			if (targetMap.containsKey(model.getUuid())) {
//				lbCeratificate = targetMap.get(model.getUuid());
//				BeanUtils.copyProperties(model, lbCeratificate);
//				lbCeratificate.setMenderId(userId);
//				lbCeratificate.setVendorId(vendorId);
//				lbCeratificate.setGmtModify(model.getUpdateTime());
//				lbCeratificate.setGmtCreate(model.getCreateTime());
//				lbCeratificate.setRegionId(region);
//				ceratificateRepository.update(lbCeratificate);
//				targetMap.remove(lbCeratificate.getUuid());
//				continue;
//			}
//			BeanUtils.copyProperties(model, lbCeratificate);
//			lbCeratificate.setCreatorId(userId);
//			lbCeratificate.setVendorId(vendorId);
//			lbCeratificate.setGmtModify(model.getUpdateTime());
//			lbCeratificate.setGmtCreate(model.getCreateTime());
//			lbCeratificate.setRegionId(region);
//			ceratificateRepository.save(lbCeratificate);
//			targetMap.remove(lbCeratificate.getUuid());
//		}
//		for (Map.Entry<String, LbCeratificate> entry : targetMap.entrySet()) {
//			ceratificateRepository.remove(entry.getValue().getId(), userId);
//		}
//	}

//	private void syncIpGroup(List<LbIpGroupModel> models, Long vendorId, Long userId, String region) throws Exception {
//		if (models == null) {
//			return;
//		}
//		if (models.isEmpty()) {
//			ipGroupRepository.removeByVid(vendorId, userId, region);
//			lbIpRepository.removeByIpVendorId(vendorId);
//			return;
//		}
//		List<LbIpGroup> lbIpGroups = ipGroupRepository.listByVid(vendorId, region);
//		Map<String, LbIpGroup> targetMap = Maps.newHashMap();
//		for (LbIpGroup lbTarget : lbIpGroups) {
//			targetMap.put(lbTarget.getUuid(), lbTarget);
//		}
//		for (LbIpGroupModel model : models) {
//			LbIpGroup lbCeratificate = new LbIpGroup();
//			if (targetMap.containsKey(model.getUuid())) {
//				lbCeratificate = targetMap.get(model.getUuid());
//				BeanUtils.copyProperties(model, lbCeratificate);
//				lbCeratificate.setMenderId(userId);
//				lbCeratificate.setVendorId(vendorId);
//				lbCeratificate.setTenantId(0L);
//				lbCeratificate.setIpList(JSONObject.toJSONString(model.getIpList()));
//				lbCeratificate.setListenerUuids(JSONObject.toJSONString(model.getListenerUuids()));
//				ipGroupRepository.update(lbCeratificate);
//				syncIp(model.getIpList(), vendorId, lbCeratificate.getId());
//				targetMap.remove(lbCeratificate.getUuid());
//				continue;
//			}
//			BeanUtils.copyProperties(model, lbCeratificate);
//			lbCeratificate.setCreatorId(userId);
//			lbCeratificate.setVendorId(vendorId);
//			lbCeratificate.setRegionId(region);
//			lbCeratificate.setRegionId(region);
//			lbCeratificate.setIpList(JSONObject.toJSONString(model.getIpList()));
//			lbCeratificate.setListenerUuids(JSONObject.toJSONString(model.getListenerUuids()));
//			ipGroupRepository.save(lbCeratificate);
//			syncIp(model.getIpList(), vendorId, lbCeratificate.getId());
//			targetMap.remove(lbCeratificate.getUuid());
//		}
//		for (Map.Entry<String, LbIpGroup> entry : targetMap.entrySet()) {
//			ipGroupRepository.remove(entry.getValue().getId(), userId);
//			lbIpRepository.removeByIpGroupId(entry.getValue().getId());
//		}
//	}
//
//
//	public void syncIp(List<LbIpGroupModel.IpInfo> models, Long vendorId, Long ipGroupId)
//		throws Exception {
//		if (models == null) {
//			return;
//		}
//		if (models.isEmpty()) {
//			lbIpRepository.removeByIpGroupId(ipGroupId);
//			return;
//		}
//		lbIpRepository.removeByIpGroupId(ipGroupId);
//		for (LbIpGroupModel.IpInfo ipInfo : models) {
//			LbIp lbIp = new LbIp();
//			lbIp.setIp(ipInfo.getIp());
//			lbIp.setRemark(ipInfo.getRemark());
//			lbIp.setIpGroupId(ipGroupId);
//			lbIp.setVendorId(vendorId);
//			lbIpRepository.save(lbIp);
//		}
//	}
//
//	/**
//	 * 同步标签
//	 *
//	 * @param models
//	 * @param vendorId
//	 * @param userId
//	 * @throws Exception
//	 */
//	public void syncTag(List<TagModel> models, Long vendorId, Long userId, String region, String resourceId)
//			throws Exception {
//		if (models == null) {
//			return;
//		}
//		if (models.isEmpty()) {
//			tagRepository.removeByRes(vendorId, region, resourceId, "");
//			return;
//		}
//		List<Tag> tagList = tagRepository.listByRes(vendorId, region, resourceId, "");
//		Map<String, Tag> tagMap = Maps.newHashMap();
//		for (Tag tag : tagList) {
//			tagMap.put(tag.getKey() + tag.getValue() + tag.getResourceId(), tag);
//		}
//		for (TagModel model : models) {
//			Tag tag = new Tag();
//			if (tagMap.containsKey(model.getKey() + model.getValue() + model.getResourceId())) {
//				tag = tagMap.get(model.getKey() + model.getValue() + model.getResourceId());
//				BeanUtils.copyProperties(model, tag);
//				tag.setResourceType(model.getResourceType());
//				tag.setVendorId(vendorId);
//				tag.setGmtModify(new Date());
//				tag.setRegionId(region);
//				tag.setTagUuid(model.getKey() + "_" +model.getValue());
//				tagRepository.update(tag);
//				tagMap.remove(model.getKey() + model.getValue() + model.getResourceId());
//				continue;
//			}
//			BeanUtils.copyProperties(model, tag);
//			tag.setResourceType(model.getResourceType());
//			tag.setVendorId(vendorId);
//			tag.setRegionId(region);
//			tag.setTagUuid(model.getKey() + "_" +model.getValue());
//			tagRepository.save(tag);
//			tagMap.remove(model.getKey() + model.getValue() + model.getResourceId());
//		}
//		for (Map.Entry<String, Tag> entry : tagMap.entrySet()) {
//			tagRepository.remove(entry.getValue().getId());
//		}
//	}
//
//	private void syncBuckets(List<BucketModel> bucketModels, Long vendorId, Long userId, String regionId) {
//		if (ListTool.isEmpty(bucketModels)) {
//			bucketRepository.removeByVid(vendorId, regionId, userId);
//			objectRepository.removeByVid(vendorId, userId);
//			return;
//		}
//		List<Bucket> buckets = bucketRepository.listByVendorId(vendorId, regionId);
//		Map<String, Bucket> bucketMap = Maps.newHashMap();
//		for (Bucket bucket : buckets) {
//			if (bucketMap.containsKey(bucket.getName())) {
//				bucketRepository.remove(bucket.getId(), userId);
//				objectRepository.removeByBucketId(bucket.getId(), userId);
//			} else {
//				bucketMap.put(bucket.getName(), bucket);
//			}
//		}
//		Bucket bucket = null;
//		for (BucketModel model : bucketModels) {
//			String bucketName = model.getName();
//			if (bucketMap.containsKey(bucketName)) {
//				bucket = bucketMap.get(bucketName);
//				BeanUtils.copyProperties(model, bucket);
//				bucket.setMenderId(userId);
//				bucket.setRegionId(regionId);
//				bucket.setGmtModify(new Date());
//				bucket.setCreatorId(userId);
//				bucket.setVendorId(vendorId);
//				bucket.setSize(model.getSize());
//				bucket.setTenantUuid(model.getEnterpriseProjectUuid());
//				bucket.setCreateTime(model.getCreateTime());
//				bucketRepository.update(bucket);
//				syncBucketObjects(model.getBucketObjectModels(), vendorId, bucket.getId(), userId);
//				bucketMap.remove(bucketName);
//				continue;
//			}
//			bucket = new Bucket();
//			BeanUtils.copyProperties(model, bucket);
//			bucket.setTenantId(0L);
//			bucket.setMenderId(userId);
//			bucket.setRegionId(regionId);
//			bucket.setGmtModify(new Date());
//			bucket.setTenantId(0L);
//			bucket.setCreatorId(userId);
//			bucket.setVendorId(vendorId);
//			bucket.setSize(model.getSize());
//			bucket.setTenantUuid(model.getEnterpriseProjectUuid());
//			bucket.setCreateTime(model.getCreateTime());
//			bucketRepository.save(bucket);
//			syncBucketObjects(model.getBucketObjectModels(), vendorId, bucket.getId(), userId);
//		}
//		for (Map.Entry<String, Bucket> entry : bucketMap.entrySet()) {
//			bucketRepository.remove(entry.getValue().getId(), userId);
//			objectRepository.removeByBucketId(entry.getValue().getId(), userId);
//		}
//
//	}
//
//	public void syncBucketObjects(List<BucketObjectModel> objectModels, Long vendorId, Long bucketId, Long userId) {
//		if (ListTool.isEmpty(objectModels)) {
//			objectRepository.removeByBucketId(bucketId, userId);
//			return;
//		}
//		List<BucketObject> bucketObjects = objectRepository.listByBucketId(bucketId, vendorId);
//		Map<String, BucketObject> objectMap = Maps.newHashMap();
//		for (BucketObject object : bucketObjects) {
//			if (objectMap.containsKey(object.getKey())) {
//				objectRepository.remove(object.getId(), userId);
//			} else {
//				objectMap.put(object.getKey(), object);
//			}
//		}
//		BucketObject object = null;
//		for (BucketObjectModel model : objectModels) {
//			String key = model.getKey();
//			if (objectMap.containsKey(key)) {
//				object = objectMap.get(key);
//				BeanUtils.copyProperties(model, object);
//				object.setMenderId(userId);
//				object.setGmtModify(new Date());
//				object.setCreatorId(userId);
//				object.setVendorId(vendorId);
//				object.setSize(model.getSize());
//				object.setKey(model.getKey());
//				object.setObjectSize(model.getObjectSize());
//				object.setObjectSize(model.getObjectSize());
//				object.setBucketName(model.getBucketName());
//				object.setBucketId(bucketId);
//				objectRepository.update(object);
//				objectMap.remove(key);
//				continue;
//			}
//			object = new BucketObject();
//			BeanUtils.copyProperties(model, object);
//			object.setMenderId(userId);
//			object.setGmtModify(new Date());
//			object.setTenantId(0L);
//			object.setCreatorId(userId);
//			object.setVendorId(vendorId);
//			object.setSize(model.getSize());
//			object.setKey(model.getKey());
//			object.setObjectSize(model.getObjectSize());
//			object.setObjectSize(model.getObjectSize());
//			object.setBucketName(model.getBucketName());
//			object.setBucketId(bucketId);
//			objectRepository.save(object);
//		}
//		for (Map.Entry<String, BucketObject> entry : objectMap.entrySet()) {
//			objectRepository.remove(entry.getValue().getId(), userId);
//		}
//
//	}
//
//	private void syncCloudRds(List<DbInstanceModel> models, Map<String, Long> vpcMap, Map<String, Long> subnetMap,
//			Map<String, Long> securityGroupMap, Map<String, Long> projectMap, String region, Long vendorId, Long userId)
//			throws Exception {
//		if (models == null) {
//			return;
//		}
//		if (models.isEmpty()) {
//			cloudRdsRepository.removeByVid(vendorId, userId, region);
//			return;
//		}
//		List<CloudRds> cloudRdsList = cloudRdsRepository.listByVid(vendorId, region);
//		Map<String, CloudRds> cloudRdsMap = Maps.newHashMap();
//		for (CloudRds cloudRds : cloudRdsList) {
//			cloudRdsMap.put(cloudRds.getUuid(), cloudRds);
//		}
//		for (DbInstanceModel model : models) {
//			CloudRds cloudRds = new CloudRds();
//			if (cloudRdsMap.containsKey(model.getUuid())) {
//				cloudRds = cloudRdsMap.get(model.getUuid());
//				BeanUtils.copyProperties(model, cloudRds);
//				cloudRds.setVpcId(vpcMap.get(model.getVpcId()));
//				cloudRds.setSubnetId(subnetMap.get(model.getSubnetId()));
//				cloudRds.setSecurityGroupId(securityGroupMap.get(model.getSecurityGroupId()));
//				cloudRds.setEnterpriseProjectId(projectMap.get(model.getEnterpriseProjectId()));
//				cloudRds.setVendorId(vendorId);
//				cloudRds.setGmtModify(new Date());
//				cloudRds.setRegionId(region);
//				cloudRdsRepository.update(cloudRds);
//				cloudRdsMap.remove(cloudRds.getUuid());
//				syncTag(model.getTagModels(), vendorId, userId, region, model.getUuid());
//				continue;
//			}
//			BeanUtils.copyProperties(model, cloudRds);
//			cloudRds.setVpcId(vpcMap.get(model.getVpcId()));
//			cloudRds.setSubnetId(subnetMap.get(model.getSubnetId()));
//			cloudRds.setSecurityGroupId(securityGroupMap.get(model.getSecurityGroupId()));
//			cloudRds.setEnterpriseProjectId(projectMap.get(model.getEnterpriseProjectId()));
//			cloudRds.setCreatorId(userId);
//			cloudRds.setMenderId(userId);
//			cloudRds.setVendorId(vendorId);
//			cloudRds.setGmtCreate(new Date());
//			cloudRds.setRegionId(region);
//			cloudRdsRepository.save(cloudRds);
//			cloudRdsMap.remove(model.getUuid());
//			syncTag(model.getTagModels(), vendorId, userId, region, model.getUuid());
//		}
//		for (Map.Entry<String, CloudRds> entry : cloudRdsMap.entrySet()) {
//			cloudRdsRepository.remove(entry.getValue().getId(), userId);
//		}
//	}
//
//	private void syncRdsBackup(List<DbBackupModel> models, Map<String, CloudRds> rdsMap, String region, Long vendorId, Long userId)
//		throws Exception {
//		if (models == null) {
//			return;
//		}
//		if (models.isEmpty()) {
//			rdsBackupRepository.removeByVid(vendorId, userId, region);
//			return;
//		}
//		List<CloudRdsBackup> cloudRdsBackups = rdsBackupRepository.listByVid(vendorId, region);
//		Map<String, CloudRdsBackup> backupMap = Maps.newHashMap();
//		for (CloudRdsBackup backup : cloudRdsBackups) {
//			backupMap.put(backup.getBackupUuid(), backup);
//		}
//		for (DbBackupModel model : models) {
//			CloudRdsBackup cloudRds = new CloudRdsBackup();
//			if (backupMap.containsKey(model.getBackupUuid())) {
//				cloudRds = backupMap.get(model.getBackupUuid());
//				BeanUtils.copyProperties(model, cloudRds);
//				cloudRds.setVendorId(vendorId);
//				cloudRds.setRegionId(region);
//				cloudRds.setTenantId(0L);
//				cloudRds.setGmtCreate(model.getGmtCreate());
//				cloudRds.setGmtModify(model.getGmtModify());
//				Optional.ofNullable(rdsMap.get(model.getInstanceUuid())).map(CloudRds::getId).ifPresent(cloudRds::setRdsId);
//				rdsBackupRepository.update(cloudRds);
//				backupMap.remove(cloudRds.getBackupUuid());
//				continue;
//			}
//			BeanUtils.copyProperties(model, cloudRds);
//			cloudRds.setCreatorId(userId);
//			cloudRds.setMenderId(userId);
//			cloudRds.setVendorId(vendorId);
//			cloudRds.setRegionId(region);
//			cloudRds.setGmtCreate(model.getGmtCreate());
//			cloudRds.setGmtModify(model.getGmtModify());
//			Optional.ofNullable(rdsMap.get(model.getInstanceUuid())).map(CloudRds::getId).ifPresent(cloudRds::setRdsId);
//			rdsBackupRepository.save(cloudRds);
//			backupMap.remove(model.getBackupUuid());
//		}
//		for (Map.Entry<String, CloudRdsBackup> entry : backupMap.entrySet()) {
//			rdsBackupRepository.remove(entry.getValue().getId(), userId);
//		}
//	}
//
//	private void syncCloudRdsConfiguration(List<DbConfigurationModel> models, String region, Long vendorId, Long userId)
//			throws Exception {
//		if (models == null) {
//			return;
//		}
//		if (models.isEmpty()) {
//			cloudRdsConfigurationRepository.removeByVid(vendorId, userId, region);
//			return;
//		}
//		List<CloudRdsConfiguration> configurations = cloudRdsConfigurationRepository.listByVid(vendorId, region);
//		Map<String, CloudRdsConfiguration> configurationMap = Maps.newHashMap();
//		for (CloudRdsConfiguration configuration : configurations) {
//			configurationMap.put(configuration.getUuid(), configuration);
//		}
//		for (DbConfigurationModel model : models) {
//			CloudRdsConfiguration configuration = new CloudRdsConfiguration();
//			if (configurationMap.containsKey(model.getUuid())) {
//				configuration = configurationMap.get(model.getUuid());
//				BeanUtils.copyProperties(model, configuration);
//				configuration.setVendorId(vendorId);
//				configuration.setGmtModify(new Date());
//				configuration.setRegionId(region);
//				cloudRdsConfigurationRepository.update(configuration);
//				configurationMap.remove(configuration.getUuid());
//				continue;
//			}
//			BeanUtils.copyProperties(model, configuration);
//			configuration.setCreatorId(userId);
//			configuration.setMenderId(userId);
//			configuration.setVendorId(vendorId);
//			configuration.setGmtCreate(new Date());
//			configuration.setRegionId(region);
//			cloudRdsConfigurationRepository.save(configuration);
//			configurationMap.remove(model.getUuid());
//		}
//		for (Map.Entry<String, CloudRdsConfiguration> entry : configurationMap.entrySet()) {
//			cloudRdsConfigurationRepository.remove(entry.getValue().getId(), userId);
//		}
//	}
//
//	private void syncCloudRdsFlavor(List<DbFlavorModel> models, String region, Long vendorId, Long userId)
//			throws Exception {
//		if (models == null) {
//			return;
//		}
//		if (models.isEmpty()) {
//			cloudRdsFlavorRepository.removeByVid(vendorId, userId, region);
//			return;
//		}
//		List<CloudRdsFlavor> flavors = cloudRdsFlavorRepository.listByVid(vendorId, region);
//		Map<String, CloudRdsFlavor> flavorMap = Maps.newHashMap();
//		for (CloudRdsFlavor flavor : flavors) {
//			flavorMap.put(flavor.getUuid(), flavor);
//		}
//		for (DbFlavorModel model : models) {
//			CloudRdsFlavor flavor = new CloudRdsFlavor();
//			if (flavorMap.containsKey(model.getUuid())) {
//				flavor = flavorMap.get(model.getUuid());
//				BeanUtils.copyProperties(model, flavor);
//				flavor.setVendorId(vendorId);
//				flavor.setGmtModify(new Date());
//				flavor.setRegionId(region);
//				cloudRdsFlavorRepository.update(flavor);
//				flavorMap.remove(flavor.getUuid());
//				continue;
//			}
//			BeanUtils.copyProperties(model, flavor);
//			flavor.setCreatorId(userId);
//			flavor.setMenderId(userId);
//			flavor.setVendorId(vendorId);
//			flavor.setGmtCreate(new Date());
//			flavor.setRegionId(region);
//			cloudRdsFlavorRepository.save(flavor);
//			flavorMap.remove(model.getUuid());
//		}
//		for (Map.Entry<String, CloudRdsFlavor> entry : flavorMap.entrySet()) {
//			cloudRdsFlavorRepository.remove(entry.getValue().getId(), userId);
//		}
//	}
//
//	private void syncCloudRdsStorage(List<DbStorageModel> models, String region, Long vendorId, Long userId)
//			throws Exception {
//		if (models == null) {
//			return;
//		}
//		if (models.isEmpty()) {
//			cloudRdsStorageRepository.removeByVid(vendorId, userId, region);
//			return;
//		}
//		List<CloudRdsStorage> storageList = cloudRdsStorageRepository.listByVid(vendorId, region);
//		Map<String, CloudRdsStorage> cloudRdsMap = Maps.newHashMap();
//		for (CloudRdsStorage storage : storageList) {
//			cloudRdsMap.put(storage.getDbName() + storage.getDbVersion(), storage);
//		}
//		for (DbStorageModel model : models) {
//			CloudRdsStorage storage = new CloudRdsStorage();
//			if (cloudRdsMap.containsKey(model.getDbName() + model.getDbVersion())) {
//				storage = cloudRdsMap.get(model.getDbName() + model.getDbVersion());
//				BeanUtils.copyProperties(model, storage);
//				storage.setVendorId(vendorId);
//				storage.setGmtModify(new Date());
//				storage.setRegionId(region);
//				cloudRdsStorageRepository.update(storage);
//				cloudRdsMap.remove(storage.getDbName() + storage.getDbVersion());
//				continue;
//			}
//			BeanUtils.copyProperties(model, storage);
//			storage.setCreatorId(userId);
//			storage.setMenderId(userId);
//			storage.setVendorId(vendorId);
//			storage.setGmtCreate(new Date());
//			storage.setRegionId(region);
//			cloudRdsStorageRepository.save(storage);
//			cloudRdsMap.remove(storage.getDbName() + storage.getDbVersion());
//		}
//		for (Map.Entry<String, CloudRdsStorage> entry : cloudRdsMap.entrySet()) {
//			cloudRdsStorageRepository.remove(entry.getValue().getId(), userId);
//		}
//	}
//
//	private void syncCloudRdsVersion(List<DbVersionModel> models, String region, Long vendorId, Long userId)
//			throws Exception {
//		if (models == null) {
//			return;
//		}
//		if (models.isEmpty()) {
//			cloudRdsVersionRepository.removeByVid(vendorId, userId, region);
//			return;
//		}
//		List<CloudRdsVersion> rdsVersions = cloudRdsVersionRepository.listByVid(vendorId, region);
//		Map<String, CloudRdsVersion> versionMap = Maps.newHashMap();
//		for (CloudRdsVersion version : rdsVersions) {
//			versionMap.put(version.getUuid(), version);
//		}
//		for (DbVersionModel model : models) {
//			CloudRdsVersion version = new CloudRdsVersion();
//			if (versionMap.containsKey(model.getUuid())) {
//				version = versionMap.get(model.getUuid());
//				BeanUtils.copyProperties(model, version);
//				version.setVendorId(vendorId);
//				version.setGmtModify(new Date());
//				version.setRegionId(region);
//				cloudRdsVersionRepository.update(version);
//				versionMap.remove(version.getUuid());
//				continue;
//			}
//			BeanUtils.copyProperties(model, version);
//			version.setCreatorId(userId);
//			version.setMenderId(userId);
//			version.setVendorId(vendorId);
//			version.setGmtCreate(new Date());
//			version.setRegionId(region);
//			cloudRdsVersionRepository.save(version);
//			versionMap.remove(model.getUuid());
//		}
//		for (Map.Entry<String, CloudRdsVersion> entry : versionMap.entrySet()) {
//			cloudRdsVersionRepository.remove(entry.getValue().getId(), userId);
//		}
//	}
}
