package com.bocloud.ims.service.resource;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.network.NatGatewaySnatRuleDriver;
import com.bocloud.cmp.entity.enums.CloudProvider;
import com.bocloud.cmp.model.NatGatewaySnatRuleModel;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.GridBean;
import com.bocloud.common.model.OperateResult;
import com.bocloud.common.model.Pager;
import com.bocloud.common.model.Param;
import com.bocloud.common.model.RequestContext;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.GridHelper;
import com.bocloud.common.utils.JSONTools;
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.NatGateway;
import com.bocloud.ims.entity.resource.NatGatewaySnatRule;
import com.bocloud.ims.entity.resource.NatGatewaySnatRuleRelation;
import com.bocloud.ims.entity.resource.Port;
import com.bocloud.ims.entity.resource.Subnet;
import com.bocloud.ims.interfaces.resource.NatGatewaySnatRuleService;
import com.bocloud.ims.repository.NatGatewaySnatRuleRelationRepository;
import com.bocloud.ims.repository.resource.CloudServerRepository;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.ElasticIpRepository;
import com.bocloud.ims.repository.resource.NatGatewayRepository;
import com.bocloud.ims.repository.resource.NatGatewaySnatRuleRepository;
import com.bocloud.ims.repository.resource.PortRepository;
import com.bocloud.ims.repository.resource.SubnetRepository;
import com.bocloud.ims.service.utils.IPv4Address;
import com.bocloud.ims.service.utils.ResourceEventPublisher;
import com.bocloud.service.lock.BocloudACLock;
import com.bocloud.service.lock.LockFactory;
import com.google.common.collect.Maps;

import joptsimple.internal.Strings;

@Service("natGatewaySnatRuleService")
public class NatGatewaySnatRuleServiceImpl implements NatGatewaySnatRuleService {
	private static Logger logger = LoggerFactory.getLogger(NatGatewaySnatRuleServiceImpl.class);
	@Autowired
	private NatGatewaySnatRuleRepository snatRuleRepository;
	@Autowired
	private NatGatewayRepository natGatewayRepository;
	@Autowired
	private CloudVendorRepository cloudVendorRepository;
	@Autowired
	private SubnetRepository subnetRepository;
	@Autowired
	private ElasticIpRepository elasticIpRepository;
	@Autowired
	private NatGatewaySnatRuleRelationRepository relationRepository;
	@Autowired
	private NatGatewaySnatRuleDriver snatRuleDriver;
	@Autowired
	private LockFactory lockFactory;
	@Autowired
	private ThreadPoolTaskExecutor taskExecutor;
	@Autowired
	private ResourceEventPublisher resourceEventPublisher;
	@Autowired
	private CloudServerRepository cloudServerRepository;

	@Autowired
	private PortRepository portRepository;

	@Override
	public BocloudResult<GridBean<NatGatewaySnatRule>> list(Pager pager, RequestContext context) {
		try {
			List<Param> params = Optional.ofNullable(pager.getParams()).orElse(new ArrayList<>());
			Map<String, String> sorter = Optional.ofNullable(pager.getSorter()).orElse(Maps.newHashMap());
			sorter.put("gmtCreate", Common.ONE);
			Integer page = Optional.ofNullable(pager.getPage()).orElse(1);
			Integer rows = Optional.ofNullable(pager.getRows()).orElse(10);

			int total = snatRuleRepository.count(params);
			List<NatGatewaySnatRule> list = snatRuleRepository.list(page, rows, params, sorter);
			for (NatGatewaySnatRule snatRule : list) {
				List<NatGatewaySnatRuleRelation> relations = relationRepository.listBySnatRuleId(snatRule.getId());
				snatRule.setElasticIps(StringUtils
						.join(relations.stream().map(NatGatewaySnatRuleRelation::getElasticIp).toArray(), ","));
				if (snatRule.getSubnetId() != null) {
					Subnet subnet = subnetRepository.query(snatRule.getSubnetId());
					snatRule.setCidr(subnet.getCidr() + "(" + subnet.getName() + ")");
				}
			}
			GridBean<NatGatewaySnatRule> gridBean = GridHelper.getBean(page, rows, total, list);
			return new BocloudResult<GridBean<NatGatewaySnatRule>>(true, gridBean, "查询成功");
		} catch (Exception e) {
			logger.error("list natGateway failure:", e);
			return new BocloudResult<GridBean<NatGatewaySnatRule>>(false, "查询失败", null, null);
		}
	}

	@Override
	public BocloudResult create(NatGatewaySnatRule snatRule, RequestContext context) {
		try {
			Assert.notNull(snatRule, "参数格式不正确");
			Assert.notNull(snatRule.getVendorId(), "参数格式不正确");
			CloudVendor vendor = cloudVendorRepository.query(snatRule.getVendorId());
			Assert.notNull(vendor, "云平台不存在");
			if (CloudProvider.ALIYUN.name().equals(vendor.getType())) {
				return aliyunCreate(snatRule, vendor, context);
			}

			if (snatRule.getRegionId() == null || snatRule.getElasticIpIds().size() == 0
					|| snatRule.getSourceType() == null || snatRule.getNatGatewayId() == null) {
				return new BocloudResult<>(false, "参数格式不正确");
			}

			if (snatRule.getSourceType() == 1 && snatRule.getCidr() == null) {
				return new BocloudResult<>(false, "选择云专线/云连接时，cidr为必填");
			}
			if (snatRule.getSubnetId() != null && snatRule.getCidr() != null) {
				return new BocloudResult<>(false, "子网id和cidr不可同时存在");
			}
			if (snatRule.getSubnetId() == null && snatRule.getCidr() == null) {
				return new BocloudResult<>(false, "子网id和cidr需传其中一个");
			}

			NatGateway natGateway = natGatewayRepository.query(snatRule.getNatGatewayId());
			if (null == natGateway) {
				return new BocloudResult<>(false, "未找到nat网关");
			}

			Subnet subnet = subnetRepository.query(snatRule.getSubnetId());

			List<String> elasticIpUuids = new ArrayList<>();
			for (Long id : snatRule.getElasticIpIds()) {
				ElasticIp elasticIp = elasticIpRepository.query(id);
				if (null == elasticIp) {
					return new BocloudResult<>(false, "id为" + id + "的弹性公网IP未找到");
				}
				elasticIpUuids.add(elasticIp.getElasticIpUuid());
			}
			NatGatewaySnatRuleModel snatRuleModel = new NatGatewaySnatRuleModel();
			BeanUtils.copyProperties(snatRule, snatRuleModel);
			Optional.ofNullable(subnet).map(Subnet::getSubnetUuid).ifPresent(snatRuleModel::setSubnetUuid);
			// 弹性公网IP的id,多个弹性公网IP使用逗号分隔
			snatRuleModel.setFloatingIpId(Strings.join(elasticIpUuids, ","));
			snatRuleModel.setNatGatewayId(natGateway.getUuid());

			taskExecutor.submit(() -> {
				OperateResult result = null;
				if (CloudProvider.ALIYUN.name().equals(vendor.getType())) {
					result = new OperateResult(true, "", "huawei.createNatGatewaySnatRule", null,
							OperateResult.OperateCategory.ResourceEvent, context);
				} else {
					result = new OperateResult(true, "", "createNatGatewaySnatRule", null,
							OperateResult.OperateCategory.ResourceEvent, context);
				}
				BocloudResult createResult = snatRuleDriver.create(snatRuleModel, vendor.getUuid(),
						snatRule.getRegionId());
				if (createResult.isFailed()) {
					result.setSuccess(false);
					result.setMessage("创建nat网关snat规则失败：" + createResult.getMessage());
					resourceEventPublisher.send(result);
					return;
				}

				if (CloudProvider.ALIYUN.name().equals(vendor.getType())) {
					BeanUtils.copyProperties(snatRuleModel, snatRule);
					snatRule.setGmtCreate(new Date());
				} else {
					NatGatewaySnatRuleModel snatRuleModelresult = JSONObject.parseObject(
							JSONObject.toJSONString(createResult.getData()), NatGatewaySnatRuleModel.class);
					BeanUtils.copyProperties(snatRuleModelresult, snatRule);
					snatRule.setGmtCreate(snatRuleModelresult.getGmtCreate());
					Optional.ofNullable(subnetRepository.query(snatRuleModelresult.getSubnetUuid(), vendor.getId()))
							.map(Subnet::getId).ifPresent(snatRule::setSubnetId);
				}

				snatRule.setCreatorId(context.getTarget());
				snatRule.setVendorId(vendor.getId());
				snatRule.setNatGatewayId(natGateway.getId());
				snatRuleRepository.save(snatRule);

				if (CloudProvider.HUAWEI.name().equals(vendor.getType())) {
					// 根据natId查询网卡id，建立弹性IP与网卡关系
					Port port = portRepository.listByDeviceUuid(natGateway.getUuid(), vendor.getId(),
							"network:nat_gateway");
					for (Long id : snatRule.getElasticIpIds()) {
						NatGatewaySnatRuleRelation relation = new NatGatewaySnatRuleRelation();
						relation.setSnatRuleId(snatRule.getId());
						relation.setElasticIpId(id);
						relationRepository.save(relation);
						// 华为云弹性IP与实例绑定关系
						if (null != port) {
							try {
								ElasticIp elasticIp = elasticIpRepository.query(id);
								if (null != elasticIp) {
									elasticIp.setInstanceId(port.getPortUuid());
									elasticIp.setMenderId(context.getTarget());
									elasticIp.setStatus("ACTIVE");
									elasticIp.setGmtModify(new Date());
									elasticIpRepository.update(elasticIp);
								}

							} catch (Exception e) {
								logger.error("更新弹性公网IP与实例绑定关系失败", e);
							}

						}
					}

				} else {
					for (Long id : snatRule.getElasticIpIds()) {
						NatGatewaySnatRuleRelation relation = new NatGatewaySnatRuleRelation();
						relation.setSnatRuleId(snatRule.getId());
						relation.setElasticIpId(id);
						relationRepository.save(relation);
					}
				}

				result.setSuccess(true);
				result.setMessage("创建nat网关[" + natGateway.getName() + "]的snat规则成功");
				resourceEventPublisher.send(result);
				return;
			});

			return new BocloudResult<>(true, "任务已经下发，正在执行...");
		} catch (Exception e) {
			logger.error("create nat gateway snat rule failure:" + e.getMessage());
			return new BocloudResult<>(false, "创建失败 : "+ e.getMessage());
		}
	}

	private BocloudResult aliyunCreate(NatGatewaySnatRule snatRule, CloudVendor vendor, RequestContext context) {
		try {
			if (snatRule.getRegionId() == null || snatRule.getNatGatewayId() == null || snatRule.getCidr() == null
					|| snatRule.getSnatIp() == null) {
				return new BocloudResult<>(false, "参数格式不正确");
			}

			if (snatRule.getSubnetId() == null && snatRule.getEcsId() == null) {
				return new BocloudResult<>(false, "交换机id和ecsId需传其中一个");
			}

			NatGateway natGateway = natGatewayRepository.query(snatRule.getNatGatewayId());
			if (null == natGateway) {
				return new BocloudResult<>(false, "未找到nat网关");
			}
			if (StringUtils.isEmpty(natGateway.getSnatTableIds())) {
				return new BocloudResult<>(false, "nat网关缺少SnatTableId");
			}

			Subnet subnet = subnetRepository.query(snatRule.getSubnetId());

			NatGatewaySnatRuleModel snatRuleModel = new NatGatewaySnatRuleModel();
			BeanUtils.copyProperties(snatRule, snatRuleModel);
			// 弹性公网IP的id,多个弹性公网IP使用逗号分隔
			snatRuleModel.setFloatingIpAddress(snatRule.getSnatIp());
			snatRuleModel.setNatGatewayId(natGateway.getUuid());
			snatRuleModel.setSnatTableId(natGateway.getSnatTableIds().split(",")[0]);

			taskExecutor.submit(() -> {
				OperateResult result = new OperateResult(true, "", "huawei.createNatGatewaySnatRule", null,
						OperateResult.OperateCategory.ResourceEvent, context);
				BocloudResult createResult = snatRuleDriver.create(snatRuleModel, vendor.getUuid(),
						snatRule.getRegionId());
				if (createResult.isFailed()) {
					result.setSuccess(false);
					result.setMessage("创建nat网关snat规则失败：" + createResult.getMessage());
					resourceEventPublisher.send(result);
					return;
				}

				NatGatewaySnatRuleModel snatRuleModelresult = JSONObject
						.parseObject(JSONObject.toJSONString(createResult.getData()), NatGatewaySnatRuleModel.class);
				if (CloudProvider.ALIYUN.name().equals(vendor.getType())) {
					BeanUtils.copyProperties(snatRuleModelresult, snatRule);
					snatRule.setGmtCreate(new Date());
				} else {
					BeanUtils.copyProperties(snatRuleModelresult, snatRule);
					snatRule.setGmtCreate(snatRuleModelresult.getGmtCreate());
					Optional.ofNullable(subnetRepository.query(snatRuleModelresult.getSubnetUuid(), vendor.getId()))
							.map(Subnet::getId).ifPresent(snatRule::setSubnetId);
				}

				snatRule.setCreatorId(context.getTarget());
				snatRule.setVendorId(vendor.getId());
				snatRule.setNatGatewayId(natGateway.getId());
				snatRule.setRegionId(natGateway.getRegionId());
				snatRuleRepository.save(snatRule);
				for (Long id : snatRule.getElasticIpIds()) {
					NatGatewaySnatRuleRelation relation = new NatGatewaySnatRuleRelation();
					relation.setSnatRuleId(snatRule.getId());
					relation.setElasticIpId(id);
					relationRepository.save(relation);

				}

				result.setSuccess(true);
				result.setMessage("创建nat网关[" + natGateway.getName() + "]的snat规则成功");
				resourceEventPublisher.send(result);
				return;
			});

			return new BocloudResult<>(true, "任务已经下发，正在执行...");
		} catch (Exception e) {
			logger.error("create nat gateway snat rule failure:" + e.getMessage());
			return new BocloudResult<>(false, "创建失败", null, null);
		}
	}

	@Override
	public BocloudResult remove(Long id, RequestContext context) {
		try {
			NatGatewaySnatRule snatRule = snatRuleRepository.query(id);
			if (null == snatRule) {
				return new BocloudResult<>(false, "该snat规则不存在");
			}
			CloudVendor vendor = cloudVendorRepository.query(snatRule.getVendorId());
			if (null == vendor) {
				return new BocloudResult<>(false, "云平台不存在");
			}
			NatGateway natGateway = natGatewayRepository.query(snatRule.getNatGatewayId());
			if (null == natGateway) {
				return new BocloudResult<>(false, "未找到nat网关");
			}

			taskExecutor.submit(() -> {
				OperateResult result = new OperateResult(true, "", "huawei.removeNatGatewaySnatRule", null,
						OperateResult.OperateCategory.ResourceEvent, context);
				try (BocloudACLock lock = lockFactory.getACLock("huawei_removeNatGatewaySnatRule" + id)) {
					if (!lock.acquire(10, TimeUnit.SECONDS)) {
						result.setSuccess(false);
						result.setMessage("删除nat网关Snat规则失败，当前存在其他互斥任务正在执行，请稍后再试");
						resourceEventPublisher.send(result);
						return;
					}
					BocloudResult removeResult = null;
					if (CloudProvider.ALIYUN.name().equals(vendor.getType())) {
						removeResult = snatRuleDriver.remove(vendor.getUuid(), snatRule.getSnatTableId(),
								snatRule.getUuid(), snatRule.getRegionId());
					} else {
						removeResult = snatRuleDriver.remove(vendor.getUuid(), natGateway.getUuid(), snatRule.getUuid(),
								snatRule.getRegionId());
					}

					if (removeResult.isFailed()) {
						result.setSuccess(false);
						result.setMessage("删除nat网关Snat规则失败：" + removeResult.getMessage());
						resourceEventPublisher.send(result);
						return;
					}

					snatRuleRepository.delete(id, context.getTarget());
					if (CloudProvider.HUAWEI.name().equals(vendor.getType())) {
						List<NatGatewaySnatRuleRelation> relationList = relationRepository.listBySnatRuleId(id);
						if (CollectionUtils.isNotEmpty(relationList)) {
							for (NatGatewaySnatRuleRelation relation : relationList) {
								ElasticIp eip = elasticIpRepository.query(relation.getElasticIpId());
								if (null != eip) {
									eip.setMenderId(context.getTarget());
									eip.setStatus("DOWN");
									eip.setGmtModify(new Date());
									eip.setInstanceId(null);
									elasticIpRepository.update(eip);
								}
							}

						}
					}
					relationRepository.removeBySnatRuleId(id);

					result.setSuccess(true);
					result.setMessage("删除nat网关[" + natGateway.getName() + "]的Snat规则成功");
					resourceEventPublisher.send(result);
					return;
				} catch (Exception e) {
					logger.error("删除nat网关Snat规则失败：", e);
					result.setSuccess(false);
					result.setMessage("删除nat网关Snat规则失败：" + e.getMessage());
					resourceEventPublisher.send(result);
					return;
				}
			});

			return new BocloudResult<>(true, "任务已经下发，正在执行...");
		} catch (Exception e) {
			logger.error("remove nat gateway failure:" + e.getMessage());
			return new BocloudResult<>(false, "删除失败", null, null);
		}
	}

	@Override
	public BocloudResult modify(NatGatewaySnatRule snatRule, RequestContext context) {
		try {
			CloudVendor vendor = cloudVendorRepository.query(snatRule.getVendorId());
			if (null == vendor) {
				return new BocloudResult<>(false, "云平台不存在");
			}
			NatGatewaySnatRule dbSnatRule = snatRuleRepository.query(snatRule.getId());
			if (null == dbSnatRule) {
				return new BocloudResult<>(false, "该snat规则不存在");
			}
			NatGateway natGateway = natGatewayRepository.query(dbSnatRule.getNatGatewayId());
			if (null == natGateway) {
				return new BocloudResult<>(false, "未找到nat网关");
			}

			NatGatewaySnatRuleModel natGatewayModel = new NatGatewaySnatRuleModel();
			BeanUtils.copyProperties(snatRule, natGatewayModel);
			natGatewayModel.setStatus(dbSnatRule.getStatus());
			natGatewayModel.setUuid(dbSnatRule.getUuid());

			if (!CloudProvider.ALIYUN.name().equals(vendor.getType())) {
				List<String> elasticIps = new ArrayList<>();
				for (Long id : snatRule.getElasticIpIds()) {
					ElasticIp elasticIp = elasticIpRepository.query(id);
					if (null == elasticIp) {
						return new BocloudResult<>(false, "id为" + id + "的弹性公网IP未找到");
					}
					elasticIps.add(elasticIp.getPublicIp());
				}
				natGatewayModel.setFloatingIpAddress(Strings.join(elasticIps, ","));
				natGatewayModel.setNatGatewayId(natGateway.getUuid());
			} else {
				if (StringUtils.isEmpty(natGateway.getSnatTableIds())) {
					return new BocloudResult<>(false, "nat网关缺少SnatTableId");
				}
				natGatewayModel.setSnatTableId(natGateway.getSnatTableIds().split(",")[0]);
				natGatewayModel.setFloatingIpAddress(snatRule.getSnatIp());
				natGatewayModel.setNatGatewayId(natGateway.getUuid());
			}

			taskExecutor.submit(() -> {
				OperateResult result = new OperateResult(true, "", "huawei.modifyNatGatewaySnatRule", null,
						OperateResult.OperateCategory.ResourceEvent, context);
				try (BocloudACLock lock = lockFactory
						.getACLock("huawei_modifyNatGatewaySnatRule" + dbSnatRule.getId())) {
					if (!lock.acquire(10, TimeUnit.SECONDS)) {
						result.setSuccess(false);
						result.setMessage("修改nat网关Snat规则失败，当前存在其他互斥任务正在执行，请稍后再试");
						resourceEventPublisher.send(result);
						return;
					}
					BocloudResult modifyResult = snatRuleDriver.update(natGatewayModel, vendor.getUuid(),
							dbSnatRule.getRegionId());
					if (modifyResult.isFailed()) {
						result.setSuccess(false);
						result.setMessage("修改nat网关Snat规则失败：" + modifyResult.getMessage());
						resourceEventPublisher.send(result);
						return;
					}
					if (CloudProvider.ALIYUN.name().equals(vendor.getType())) {
						BeanUtils.copyProperties(natGatewayModel, dbSnatRule);
						dbSnatRule.setSnatIp(natGatewayModel.getFloatingIpAddress());
					} else {
						NatGatewaySnatRuleModel snatRuleModel = JSONObject.parseObject(
								JSONObject.toJSONString(modifyResult.getData()), NatGatewaySnatRuleModel.class);
						BeanUtils.copyProperties(snatRuleModel, dbSnatRule);
					}
					dbSnatRule.setMenderId(context.getTarget());
					dbSnatRule.setGmtModify(new Date());
					dbSnatRule.setVendorId(vendor.getId());
					dbSnatRule.setRegionId(natGateway.getRegionId());
					snatRuleRepository.update(dbSnatRule);

					// 更新原有关的eip的绑定关系
					if (CloudProvider.HUAWEI.name().equals(vendor.getType())) {
						List<NatGatewaySnatRuleRelation> relationList = relationRepository
								.listBySnatRuleId(snatRule.getId());
						if (CollectionUtils.isNotEmpty(relationList)) {
							for (NatGatewaySnatRuleRelation relation : relationList) {
								ElasticIp eip = elasticIpRepository.query(relation.getElasticIpId());
								if (null != eip) {
									eip.setMenderId(context.getTarget());
									eip.setStatus("DOWN");
									eip.setGmtModify(new Date());
									eip.setInstanceId(null);
									elasticIpRepository.update(eip);
								}
							}

						}
					}
					relationRepository.removeBySnatRuleId(snatRule.getId());

					if (!CloudProvider.ALIYUN.name().equals(vendor.getType())) {
						// 根据natId查询网卡id，建立弹性IP与网卡关系
						Port port = portRepository.listByDeviceUuid(natGateway.getUuid(), vendor.getId(),
								"network:nat_gateway");
						for (Long id : snatRule.getElasticIpIds()) {
							NatGatewaySnatRuleRelation relation = new NatGatewaySnatRuleRelation();
							relation.setSnatRuleId(snatRule.getId());
							relation.setElasticIpId(id);
							relationRepository.save(relation);
							ElasticIp eip = elasticIpRepository.query(id);
							if (null != eip && CloudProvider.HUAWEI.name().equals(vendor.getType())) {
								eip.setInstanceId(port.getPortUuid());
								eip.setMenderId(context.getTarget());
								eip.setStatus("ACTIVE");
								eip.setGmtModify(new Date());
								elasticIpRepository.update(eip);
							}

						}
					}

					result.setSuccess(true);
					result.setMessage("修改nat网关Snat规则成功");
					resourceEventPublisher.send(result);
					return;
				} catch (Exception e) {
					logger.error("修改nat网关Snat规则失败：", e);
					result.setSuccess(false);
					result.setMessage("修改nat网关Snat规则失败：" + e.getMessage());
					resourceEventPublisher.send(result);
					return;
				}
			});

			return new BocloudResult<>(true, "任务已经下发，正在执行...");
		} catch (Exception e) {
			logger.error("modify nat gateway dnat rule failure:" + e.getMessage());
			return new BocloudResult<>(false, "修改失败", null, null);
		}
	}

	@Override
	public BocloudResult<NatGatewaySnatRule> detail(Long id) {
		try {
			NatGatewaySnatRule snatRule = snatRuleRepository.query(id);
			return new BocloudResult<>(true, snatRule, "查询成功");
		} catch (Exception e) {
			logger.error("query natGateway failure:", e);
			return new BocloudResult<>(false, "查询失败", null, null);
		}
	}

	@Override
	public BocloudResult<List<Subnet>> listSubnet(String params) {
		try {
			JSONObject object = JSONTools.isJSONObj(params);
			Long natGatewayId = object.getLong("natGatewayId");
			NatGateway natGateway = natGatewayRepository.query(natGatewayId);
			if (null == natGateway) {
				return new BocloudResult<>(false, "未找到nat网关");
			}
			List<Subnet> subnets = subnetRepository.listSubnet(natGatewayId, natGateway.getVpcId());
			return new BocloudResult<>(true, subnets, "查询成功");
		} catch (Exception e) {
			logger.error("query subnets failure:", e);
			return new BocloudResult<>(false, "查询失败", null, null);
		}
	}

	@Override
	public BocloudResult<List<CloudServer>> listEcs(String params) {
		try {
			JSONObject object = JSONTools.isJSONObj(params);
			Long natGatewayId = object.getLong("natGatewayId");
			NatGateway natGateway = natGatewayRepository.query(natGatewayId);
			if (null == natGateway) {
				return new BocloudResult<>(false, "未找到nat网关");
			}
			List<CloudServer> ecsList = cloudServerRepository.list(natGateway.getVpcUuid(), natGateway.getVendorId());
			List<CloudServer> returnList = new ArrayList<>();
			for (CloudServer ecs : ecsList) {
				List<String> ips = JSONArray.parseArray(ecs.getPrivateIps(), String.class);
				if (null == ips || ips.size() == 0) {
					continue;
				}
				for (String ip : ips) {
					if (StringUtils.isEmpty(ip)) {
						continue;
					}
					if (!IPv4Address.ipv4Validate(ip)) {
						continue;
					}
					CloudServer server = new CloudServer();
					BeanUtils.copyProperties(ecs, server);
					server.setPrivateIps(ip + "/32");
					returnList.add(server);
				}
			}
			return new BocloudResult<>(true, returnList, "查询成功");
		} catch (Exception e) {
			logger.error("query subnets failure:", e);
			return new BocloudResult<>(false, "查询失败", null, null);
		}
	}
}
