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.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.stereotype.Service;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.secuirty.FirewallDriver;
import com.bocloud.cmp.model.FirewallPolicyModel;
import com.bocloud.cmp.model.FirewallRuleModel;
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.model.Sign;
import com.bocloud.common.model.SimpleBean;
import com.bocloud.common.model.RequestContext.Catalog;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.GridHelper;
import com.bocloud.common.utils.ListTool;
import com.bocloud.common.utils.MapTools;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.FirewallPolicy;
import com.bocloud.ims.entity.resource.FirewallRule;
import com.bocloud.ims.entity.resource.OSTenant;
import com.bocloud.ims.entity.resource.TenantProvider;
import com.bocloud.ims.interfaces.resource.FirewallPolicyService;
import com.bocloud.ims.interfaces.resource.VendorProjectService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.FirewallPolicyRepository;
import com.bocloud.ims.repository.resource.FirewallRepository;
import com.bocloud.ims.repository.resource.FirewallRuleRepository;
import com.bocloud.ims.repository.resource.OSTenantRepository;
import com.bocloud.ims.service.utils.ResourceEventPublisher;
import com.bocloud.service.lock.BocloudACLock;
import com.bocloud.service.lock.LockFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 防火墙策略service实现
 *
 * @author wangyu
 * @version 1.0
 * @since 2017年8月31日
 */
@Service("firewallPolicyService")
public class FirewallPolicyServiceImpl implements FirewallPolicyService {

	private static Logger logger = LoggerFactory.getLogger(FirewallPolicyServiceImpl.class);
	@Autowired
	private FirewallDriver firewallDriver;
	@Autowired
	private FirewallRepository firewallRepository;
	@Autowired
	private FirewallRuleRepository firewallRuleRepository;
	@Autowired
	private FirewallPolicyRepository firewallPolicyRepository;
	@Autowired
	private CloudVendorRepository cloudVendorRepository;
	@Autowired
	private OSTenantRepository osTenantRepository;
	@Autowired
	private VendorProjectService vendorProjectService;
	@Autowired
	private ResourceEventPublisher resourceEventPublisher;
	@Autowired
	private LockFactory lockFactory;

	/**
	 * 查询防火墙可绑定的策略
	 *
	 * @param vendorId
	 * @param tenantUuid
	 * @param user
	 * @return
	 */
	private BocloudResult listPolicies(Long vendorId, String tenantUuid, RequestContext context) throws Exception {
		List<FirewallPolicy> policies = firewallPolicyRepository.listByVid(vendorId, context.getTenant());
		if (StringUtils.isEmpty(tenantUuid)) {
			return new BocloudResult<>(true, policies, "查询成功");
		}
		List<FirewallPolicy> results = new ArrayList<>();
		for (FirewallPolicy policy : policies) {
			if ((null != policy.getShared() && policy.getShared())
					|| tenantUuid.equalsIgnoreCase(policy.getTenantUuid())) {
				results.add(policy);
			}
		}
		return new BocloudResult<>(true, results, "查询成功");
	}

	@Override
	public BocloudResult<GridBean<FirewallPolicy>> list(Pager pager, RequestContext context) {
		try {
			GridBean gridBean = null;
			List<Param> params = Optional.ofNullable(pager.getParams()).orElse(new ArrayList<>());
			Map<String, String> sorter = Optional.ofNullable(pager.getSorter()).orElse(Maps.newHashMap());
			Boolean simple = Optional.ofNullable(pager.getSimple()).orElse(false);
			sorter.put("gmtCreate", Common.ONE);
			Integer page = Optional.ofNullable(pager.getPage()).orElse(1);
			Integer rows = Optional.ofNullable(pager.getRows()).orElse(10);
			if (0 != context.getTenant()) {
				params.add(new Param(MapTools.simpleMap(Common.TENANTID, context.getTenant()), Sign.EQ));
			}
			Catalog catalog = context.getCatalog();
			String vendorType = null;
			if (Catalog.Tenant == catalog || Catalog.User == catalog) {
				for (Param param : params) {
					Map<String, Object> paramMap = param.getParam();
					if (paramMap.containsKey("vendorType")) {
						vendorType = String.valueOf(paramMap.get("vendorType"));
						paramMap.remove("vendorType");
					}
				}
			}
			int total = firewallPolicyRepository.count(params, vendorType);
			if (simple) {
				if (0 == context.getTenant()) {
					params.add(new Param(MapTools.simpleMap(Common.TENANTID, 0), Sign.EQ));
				}
				List<SimpleBean> beans = firewallPolicyRepository.list(params, sorter);
				gridBean = new GridBean(1, 1, total, beans);
			} else {
				List<FirewallPolicy> list = firewallPolicyRepository.list(page, rows, params, sorter, vendorType);
				// 设置绑定的规则名称
				for (FirewallPolicy policy : list) {
					// 查询所有绑定规则
					List<FirewallRule> rules = firewallRuleRepository.listRuleByPolicyId(policy.getId());
					if (!ListTool.isEmpty(rules)) {
						String ruleNames = "";
						for (FirewallRule rule : rules) {
							ruleNames += rule.getName() + ",";
						}
						policy.setRuleNames(ruleNames.substring(0, ruleNames.length() - 1));
					}
				}
				gridBean = GridHelper.getBean(page, rows, total, list);
			}
			return new BocloudResult<>(true, gridBean, "查询成功");
		} catch (Exception e) {
			logger.error("list firewall policy failure:", e);
			return new BocloudResult<>(false, "查询失败");
		}
	}

	@Override
	public BocloudResult<FirewallPolicy> create(FirewallPolicy policy, RequestContext context) {
		try {
			FirewallPolicy exist = firewallPolicyRepository.getByName(policy.getName(), policy.getVendorId());
			if (null != exist) {
				return new BocloudResult<>(false, "防火墙策略名称已存在");
			}
			CloudVendor vendor = cloudVendorRepository.query(policy.getVendorId());
			if (null == vendor) {
				return new BocloudResult<>(false, "云平台不存在");
			}
			List<Long> ruleIds = policy.getRuleIds();
			List<String> ruleUuids = Lists.newArrayList();
			if (!ListTool.isEmpty(ruleIds)) {
				for (Long ruleId : ruleIds) {
					ruleUuids.add(firewallRuleRepository.query(ruleId).getRuleUuid());
				}
			}
			FirewallPolicyModel model = JSONObject.parseObject(JSONObject.toJSONString(policy),
					FirewallPolicyModel.class);
			model.setRuleUuids(ruleUuids);
			TenantProvider provider = vendorProjectService.getAncestorProject(vendor.getId(), context.getTenant());
			BocloudResult result = null;
			if (null == provider) {
				result = firewallDriver.createPolicy(vendor.getUuid(), policy.getOsTenantName(), model);
			} else {
				result = firewallDriver.createPolicy(vendor.getUuid(), provider.getProjectName(), model);
			}
			if (result.isFailed()) {
				return new BocloudResult<FirewallPolicy>(false, result.getMessage());
			}
			model = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), FirewallPolicyModel.class);
			BeanUtils.copyProperties(model, policy);
			// 保存防火墙策略信息
			policy.preSave(context.getTarget(), context.getTarget(), policy.getVendorId(), context.getTenant(),
					context.getProject());
			policy.setId(null);
			firewallPolicyRepository.save(policy);
			if (!ListTool.isEmpty(ruleIds)) {
				for (Long ruleId : ruleIds) {
					// 更新防火墙规则策略ID
					Integer position = null;
					FirewallRule rule = firewallRuleRepository.query(ruleId);
					if (null != rule) {
						// 更新防火墙规则位置
						BocloudResult bocloudResult = firewallDriver.detailRule(rule.getRuleUuid(), vendor.getUuid());
						if (bocloudResult.isSuccess()) {
							FirewallRuleModel ruleModel = JSONObject.parseObject(
									JSONObject.toJSONString(bocloudResult.getData()), FirewallRuleModel.class);
							position = ruleModel.getPosition();
						}
					}
					firewallRuleRepository.updatePolicyByRuleId(ruleId, policy.getId(), policy.getPolicyUuid(),
							position);
				}
			}
			return new BocloudResult<FirewallPolicy>(true, policy, "创建成功!");
		} catch (Exception e) {
			logger.error("create firewall policy fail:", e);
			return new BocloudResult<FirewallPolicy>(false, "创建防火墙策略失败");
		}
	}

	@Override
	public BocloudResult<FirewallPolicy> modify(FirewallPolicy bean, Long userId) {
		String path = FirewallPolicy.class.getSimpleName() + "_" + bean.getId();
		try (BocloudACLock lock = lockFactory.getACLock(path)) {
			Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
			FirewallPolicy policy = firewallPolicyRepository.query(bean.getId());
			if (null == policy) {
				return new BocloudResult<FirewallPolicy>(false, "数据不存在");
			}
			CloudVendor vendor = cloudVendorRepository.query(policy.getVendorId());
			if (null == vendor) {
				return new BocloudResult<FirewallPolicy>(false, "云平台不存在");
			}
			// 修改防火墙策略时名称不能与已有名称重复
			if (!bean.getName().equals(policy.getName())) {
				FirewallPolicy exist = firewallPolicyRepository.getByName(bean.getName(), vendor.getId());
				if (null != exist) {
					return new BocloudResult<FirewallPolicy>(false, "防火墙策略名称已存在");
				}
			}
			FirewallPolicyModel model = JSONObject.parseObject(JSONObject.toJSONString(bean),
					FirewallPolicyModel.class);
			model.setPolicyUuid(policy.getPolicyUuid());
			BocloudResult result = firewallDriver.updatePolicy(model, vendor.getUuid());
			if (result.isFailed()) {
				return result;
			}
			model = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), FirewallPolicyModel.class);
			BeanUtils.copyProperties(model, policy);
			policy.setMenderId(userId);
			firewallPolicyRepository.update(policy);
			return new BocloudResult<FirewallPolicy>(true, policy, "修改成功");
		} catch (Exception e) {
			logger.error("modify firewall fail:", e);
			return new BocloudResult<FirewallPolicy>(false, "修改防火墙策略失败");
		}
	}

	@Override
	public BocloudResult<FirewallPolicy> detail(Long id) {
		try {
			FirewallPolicy firewallPolicy = firewallPolicyRepository.query(id);
			// 查询所有绑定规则
			List<FirewallRule> rules = firewallRuleRepository.listRuleByPolicyId(firewallPolicy.getId());
			if (!ListTool.isEmpty(rules)) {
				String ruleNames = "";
				for (FirewallRule rule : rules) {
					ruleNames += rule.getName() + ",";
				}
				firewallPolicy.setRuleNames(ruleNames.substring(0, ruleNames.length() - 1));
			}
			if (!StringUtils.isEmpty(firewallPolicy.getTenantUuid())) {
				OSTenant osTenant = osTenantRepository.getByTenantUuid(firewallPolicy.getTenantUuid(),
						firewallPolicy.getVendorId());
				if (null != osTenant) {
					firewallPolicy.setOsTenantName(osTenant.getName());
				}
			}
			return new BocloudResult<FirewallPolicy>(true, firewallPolicy, "查询成功");
		} catch (Exception e) {
			logger.error("query firewall policy fail:", e);
			return new BocloudResult<FirewallPolicy>(false, "查询防火墙策略失败");
		}
	}

	@Override
	public BocloudResult remove(Long id, RequestContext context) {
		String path = FirewallPolicy.class.getSimpleName() + "_" + id;
		try (BocloudACLock lock = lockFactory.getACLock(path)) {
			Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
			// 策略正在使用中不能删除
			boolean useFlag = firewallRepository.isUsed(id);
			if (useFlag) {
				return new BocloudResult<>(false, "该防火墙策略正在使用,不能删除");
			}
			FirewallPolicy policy = firewallPolicyRepository.query(id);
			if (null == policy) {
				return new BocloudResult<>(false, "数据不存在");
			}
			if (0L == context.getTenant() && 0L != policy.getTenantId()) {
				return new BocloudResult<>(false, "不能删除租户下的防火墙策略");
			}
			CloudVendor vendor = cloudVendorRepository.query(policy.getVendorId());
			if (null == vendor) {
				return new BocloudResult<>(false, "云平台不存在");
			}
			// 删除防火墙策略
			BocloudResult result = firewallDriver.removePolicy(vendor.getUuid(), policy.getPolicyUuid());
			if (result.isFailed()) {
				return new BocloudResult<>(false, result.getMessage());
			}
			// 删除本地防火墙策略数据
			firewallPolicyRepository.remove(id, context.getTarget());
			// 更新绑定的防火墙规则
			firewallRuleRepository.updatePolicyIdAndUuid(id);
			return new BocloudResult<>(true, "删除成功");
		} catch (Exception e) {
			logger.error("remove firewall policy fail:", e);
			return new BocloudResult<>(false, "删除防火墙策略失败");
		}
	}

	@Override
	public BocloudResult insertRule(FirewallPolicy bean, Long userId) {
		String path = FirewallPolicy.class.getSimpleName() + "_" + bean.getId();
		try (BocloudACLock lock = lockFactory.getACLock(path)) {
			Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
			FirewallPolicy policy = firewallPolicyRepository.query(bean.getId());
			if (null == policy) {
				return new BocloudResult<>(false, "防火墙策略不存在");
			}
			FirewallRule rule = firewallRuleRepository.query(bean.getRuleId());
			if (null == rule) {
				return new BocloudResult<>(false, "插入的规则不存在");
			}
			CloudVendor vendor = cloudVendorRepository.query(policy.getVendorId());
			if (null == vendor) {
				return new BocloudResult<>(false, "云平台不存在");
			}
			String policyUuid = policy.getPolicyUuid();
			String ruleUuid = rule.getRuleUuid();
			String beforeRuleUuid = null;
			if (null != bean.getBeforeRuleId()) {
				FirewallRule beforeRule = firewallRuleRepository.query(bean.getBeforeRuleId());
				if (null == beforeRule) {
					return new BocloudResult<>(false, "前一条规则不存在");
				}
				beforeRuleUuid = beforeRule.getRuleUuid();
			}
			String afterRuleUuid = null;
			if (null != bean.getAfterRuleId()) {
				FirewallRule afterRule = firewallRuleRepository.query(bean.getAfterRuleId());
				if (null == afterRule) {
					return new BocloudResult<>(false, "后一条规则不存在");
				}
				afterRuleUuid = afterRule.getRuleUuid();
			}
			BocloudResult result = null;
			// beforeRuleId之前插入新规则
			if (null != beforeRuleUuid && null == afterRuleUuid) {
				result = firewallDriver.insertRule(vendor.getUuid(), policyUuid, ruleUuid, "BEFORE", beforeRuleUuid);
			}
			// afterRuleId之前插入新规则
			if (null != afterRuleUuid && null == beforeRuleUuid) {
				result = firewallDriver.insertRule(vendor.getUuid(), policyUuid, ruleUuid, "AFTER", afterRuleUuid);
			}
			// 如果beforeRuleId和afterRuleId均被指定，beforeRuleId优先级更高。
			if (null != beforeRuleUuid && null != afterRuleUuid) {
				result = firewallDriver.insertRule(vendor.getUuid(), policyUuid, ruleUuid, "BEFORE", beforeRuleUuid);
			}
			// 直接插入规则(未指定前一条规则和后一条规则)
			if (null == beforeRuleUuid && null == afterRuleUuid) {
				result = firewallDriver.insertRule(vendor.getUuid(), policyUuid, ruleUuid, "BEFORE", null);
			}
			if (result.isFailed()) {
				return new BocloudResult<>(false, result.getMessage());
			}
			Integer position = null;
			// 更新防火墙规则位置
			BocloudResult bocloudResult = firewallDriver.detailRule(ruleUuid, vendor.getUuid());
			if (bocloudResult.isSuccess()) {
				FirewallRuleModel ruleModel = JSONObject.parseObject(JSONObject.toJSONString(bocloudResult.getData()),
						FirewallRuleModel.class);
				position = ruleModel.getPosition();
			}
			// 更新策略规则绑定
			firewallRuleRepository.updatePolicyByRuleId(bean.getRuleId(), bean.getId(), policyUuid, position);
			// 如果该规则已被策略绑定，则绑定策略审计状态需要更新为否
			policy.setAudited(false);// 未审计状态
			firewallPolicyRepository.update(policy);
			// 处理防火墙策略下规则的位置
			processRulePosition(policy.getId(), vendor, userId);
			return new BocloudResult<>(true, "操作成功");
		} catch (Exception e) {
			logger.error("insert firewall policy fail:", e);
			return new BocloudResult<>(false, "插入规则失败");
		}
	}

	/**
	 * 处理防火墙策略下规则的位置
	 *
	 * @param policyId
	 * @param vendor
	 * @param userId
	 * @throws Exception
	 */
	private void processRulePosition(Long policyId, CloudVendor vendor, Long userId) throws Exception {
		List<FirewallRule> rules = firewallRuleRepository.listRuleByPolicyId(policyId);
		for (FirewallRule rule : rules) {
			BocloudResult bocloudResult = firewallDriver.detailRule(rule.getRuleUuid(), vendor.getUuid());
			if (bocloudResult.isSuccess()) {
				FirewallRuleModel ruleModel = JSONObject.parseObject(JSONObject.toJSONString(bocloudResult.getData()),
						FirewallRuleModel.class);
				FirewallRule firewallRule = firewallRuleRepository.getByUuid(rule.getRuleUuid(), vendor.getId());
				if (null != firewallRule) {
					firewallRule.setPosition(ruleModel.getPosition());
					firewallRule.setMenderId(userId);
					firewallRule.setGmtModify(new Date());
					firewallRuleRepository.update(firewallRule);
				}
			}
		}
	}

	@Override
	public BocloudResult removeRule(FirewallPolicy bean, Long userId) {
		String path = FirewallPolicy.class.getSimpleName() + "_" + bean.getId();
		try (BocloudACLock lock = lockFactory.getACLock(path)) {
			Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
			List<Long> ruleIds = bean.getRuleIds();
			FirewallPolicy firewallPolicy = firewallPolicyRepository.query(bean.getId());
			if (null == firewallPolicy) {
				return new BocloudResult<>(false, "防火墙策略数据不存在");
			}
			CloudVendor vendor = cloudVendorRepository.query(firewallPolicy.getVendorId());
			if (null == vendor) {
				return new BocloudResult<>(false, "云平台不存在");
			}
			String policyUuid = firewallPolicy.getPolicyUuid();
			List<BocloudResult> succResults = new ArrayList<>();
			List<BocloudResult> failResults = new ArrayList<>();
			// 移除规则绑定策略
			for (Long ruleId : ruleIds) {
				FirewallRule rule = firewallRuleRepository.query(ruleId);
				if (null == rule) {
					failResults.add(new BocloudResult<>(false, "id为【" + ruleId + "】的规则不存在"));
					continue;
				}
				BocloudResult result = firewallDriver.removeRule(vendor.getUuid(), policyUuid, rule.getRuleUuid());
				if (result.isFailed()) {
					failResults.add(result);
				} else {
					succResults.add(result);
					// 更新规则策略ID和UUID
					firewallRuleRepository.updatePolicyByRuleId(ruleId, null, null, null);
				}
			}
			String content = null;
			if (failResults.size() == ruleIds.size()) {
				content = "移除防火墙规则失败，详情如下：\n";
				for (BocloudResult bocloudResult : failResults) {
					content += bocloudResult.getMessage() + "\n";
				}
				return new BocloudResult<>(false, content);
			} else {
				content = "移除防火墙规则成功【" + succResults.size() + "】个,失败【" + failResults.size() + "】个，详情如下：\n";
				for (BocloudResult bocloudResult : succResults) {
					content += bocloudResult.getMessage() + "\n";
				}
				for (BocloudResult bocloudResult : failResults) {
					content += bocloudResult.getMessage() + "\n";
				}
				return new BocloudResult<>(true, content);
			}
		} catch (Exception e) {
			logger.error("remove firewall rule from policy fail:", e);
			return new BocloudResult<>(false, "移除防火墙规则失败");
		}
	}

	@Override
	public BocloudResult<List<FirewallRule>> listRule(Long vendorId, String tenantUuid, RequestContext context) {
		try {
			List<FirewallRule> list = firewallRuleRepository.listRuleByNoBoundPolicy(vendorId, context.getTenant());
			List<FirewallRule> result = new ArrayList<>();
			if (StringUtils.isEmpty(tenantUuid)) {
				result = list;
			} else {
				for (FirewallRule rule : list) {
					// 过滤共享和本项目下的规则
					if ((null != rule.getShared() && rule.getShared())
							|| tenantUuid.equalsIgnoreCase(rule.getTenantUuid())) {
						result.add(rule);
					}
				}
			}
			return new BocloudResult<>(true, result, "查询成功");
		} catch (Exception e) {
			logger.error("list firewall rule fail:", e);
			return new BocloudResult<>(false, "查询防火墙规则失败");
		}
	}

	@Override
	public BocloudResult<List<FirewallRule>> listRuleByPolicyId(Long policyId) {
		try {
			List<FirewallRule> list = firewallRuleRepository.listRuleByPolicyId(policyId);
			return new BocloudResult<>(true, list, "查询成功");
		} catch (Exception e) {
			logger.error("list firewall rule fail:", e);
			return new BocloudResult<>(false, "查询防火墙规则失败");
		}
	}

	@Override
	public BocloudResult batchRemove(List<Long> idArray, RequestContext context) {
		if (ListTool.isEmpty(idArray)) {
			return new BocloudResult<>(false, "没有需要删除的防火墙策略！");
		}
		try {
			List<BocloudResult> succList = Lists.newArrayList();
			List<BocloudResult> failList = Lists.newArrayList();
			Long vendorId = null;
			for (Long id : idArray) {
				FirewallPolicy policy = firewallPolicyRepository.query(id);
				if (null != policy) {
					if (null == vendorId) {
						vendorId = policy.getVendorId();
					}
					BocloudResult result = remove(id, context);
					if (result.isSuccess()) {
						succList.add(new BocloudResult<>(true, "【" + policy.getName() + "】删除成功"));
					} else {
						failList.add(
								new BocloudResult<>(false, "【" + policy.getName() + "】删除失败：" + result.getMessage()));
					}
				}
			}
			CloudVendor vendor = cloudVendorRepository.query(vendorId);
			String operate = vendor.getType().toLowerCase() + ".policy";
			// 删除成功的数量
			int success = succList.size();
			// 删除失败的数量
			int fail = failList.size();
			String content = null;
			if (fail == idArray.size()) {
				content = "防火墙策略批量删除失败，详情如下：\n";
				for (BocloudResult bocloudResult : failList) {
					content += bocloudResult.getMessage() + "\n";
				}
				resourceEventPublisher
						.send(new OperateResult(false, content, operate, MapTools.simpleMap("vendorId", vendor.getId()),
								OperateResult.OperateCategory.ResourceEvent, context));
			} else {
				content = "防火墙策略批量删除成功【" + success + "】个,失败【" + fail + "】个，详情如下：\n";
				for (BocloudResult bocloudResult : succList) {
					content += bocloudResult.getMessage() + "\n";
				}
				for (BocloudResult bocloudResult : failList) {
					content += bocloudResult.getMessage() + "\n";
				}
				resourceEventPublisher
						.send(new OperateResult(true, content, operate, MapTools.simpleMap("vendorId", vendor.getId()),
								OperateResult.OperateCategory.ResourceEvent, context));
			}
		} catch (Exception e) {
			logger.error("batch remove firewall policy fail:", e);
			return new BocloudResult<>(false, "批量删除任务下发失败");
		}
		return new BocloudResult<>(true, "批量删除任务已下发，正在执行...");
	}

	@Override
	public BocloudResult condition(String condition, RequestContext context) {
		try {
			condition = Optional.ofNullable(condition).orElse("");
			JSONObject object = JSONObject.parseObject(condition);
			if ("listRule".equalsIgnoreCase(object.getString("condition"))) {
				return this.listRule(object.getLong("vendorId"), object.getString("tenantUuid"), context);
			} else if ("listPolicies".equalsIgnoreCase(object.getString("condition"))) {
				return this.listPolicies(object.getLong("vendorId"), object.getString("tenantUuid"), context);
			}
			return new BocloudResult<>(false, "参数格式错误");
		} catch (Exception e) {
			logger.error("查询失败：" + e.getMessage());
			return new BocloudResult<>(false, "查询失败：" + e.getMessage());
		}
	}
}
