package com.bocloud.ims.repository.resource;

import com.bocloud.common.model.Pager;
import com.bocloud.common.model.Param;
import com.bocloud.common.model.SimpleBean;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.MapTools;
import com.bocloud.database.core.intf.impl.BasicGenericDao;
import com.bocloud.database.utils.QueryBuilder;
import com.bocloud.ims.entity.resource.FirewallRule;
import com.google.common.collect.Maps;

import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 防火墙规则Repository实现
 *
 * @author wangyu
 * @version 1.0
 * @since 2017年8月29日
 */
@Repository("firewallRuleRepository")
public class FirewallRuleRepository extends BasicGenericDao<FirewallRule, Long> {

	public FirewallRuleRepository(JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate npJdbcTemplate) {
		super(jdbcTemplate, npJdbcTemplate);
	}

	public List<FirewallRule> list(int page, int rows, List<Param> params, Map<String, String> sorter)
			throws Exception {
		String sql = "select a.*,b.name policy_name,v.name vendor_name,t.name tenant_name from firewall_rule a left join tenant t on a.tenant_id = t.id left join firewall_policy b on a.policy_id = b.id left join cloud_vendor v on a.vendor_id = v.id where a.is_deleted = 0";
		sql = QueryBuilder.build(sql, new Pager(page, rows, params, sorter), "a");
		Map<String, Object> paramMap = QueryBuilder.getParam(params);
		return this.list(FirewallRule.class, sql, paramMap);
	}

	public List<SimpleBean> list(List<Param> params, Map<String, String> sorter) throws Exception {
		String sql = "select a.id,a.name,a.rule_uuid from firewall_rule a where a.is_deleted = 0";
		sql = QueryBuilder.build(sql, new Pager(1, Integer.MAX_VALUE, params, sorter), "a");
		Map<String, Object> paramMap = QueryBuilder.getParam(params);
		List<FirewallRule> firewallRules = this.list(FirewallRule.class, sql, paramMap);
		List<SimpleBean> beans = new ArrayList<>();
		for (FirewallRule firewallRule : firewallRules) {
			SimpleBean simpleBean = new SimpleBean(firewallRule.getId(), firewallRule.getName());
			simpleBean.setUuid(firewallRule.getRuleUuid());
			beans.add(simpleBean);
		}
		return beans;
	}

	public int count(List<Param> params) throws Exception {
		String sql = "select count(1) from firewall_rule a where a.is_deleted = 0";
		sql = QueryBuilder.build(sql, params, null, "a");
		Map<String, Object> paramMap = QueryBuilder.getParam(params);
		return this.countQuery(sql, paramMap).intValue();
	}

	public FirewallRule query(Long id) throws Exception {
		String sql = "select a.*,t.name tenant_name,p.name project_name,v.name vendor_name,fp.name policy_name from firewall_rule a left join firewall_policy fp on fp.id = a.policy_id left join tenant t on a.tenant_id = t.id left join project p on p.id = a.project_id left join cloud_vendor v on v.id = a.vendor_id where a.id = :id and a.is_deleted = 0";
		Map<String, Object> paramMap = MapTools.simpleMap("id", id);
		List<FirewallRule> list = this.list(FirewallRule.class, sql, paramMap);
		if (list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

	public boolean remove(Long id, Long userId) throws Exception {
		String sql = "update firewall_rule set is_deleted = true,gmt_modify = :gmtModify,mender_id = :menderId where is_deleted = 0 and id = :id";
		Map<String, Object> params = MapTools.simpleMap("id", id);
		params.put("menderId", userId);
		params.put("gmtModify", new Date());
		return this.execute(sql, params) > 0;
	}

	public FirewallRule getByName(String name, Long vendorId) throws Exception {
		String sql = "select a.*,t.name tenant_name from firewall_rule a left join tenant t on a.tenant_id = t.id where a.name = :name and a.is_deleted = 0 and a.vendor_id = :vendorId";
		Map<String, Object> paramMap = MapTools.simpleMap("name", name);
		paramMap.put(Common.VENDORID, vendorId);
		List<FirewallRule> list = this.list(FirewallRule.class, sql, paramMap);
		if (list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

	public boolean updatePolicyByRuleId(Long ruleId, Long policyId, String policyUuid, Integer position)
			throws Exception {
		String sql = "update firewall_rule set policy_id = :policyId,policy_uuid = :policyUuid,position = :position where id = :id and is_deleted = 0";
		Map<String, Object> paramMap = MapTools.simpleMap("id", ruleId);
		paramMap.put("policyId", policyId);
		paramMap.put("policyUuid", policyUuid);
		paramMap.put("position", position);
		return this.execute(sql, paramMap) > 0;
	}

	public boolean updatePolicyIdAndUuid(Long policyId) throws Exception {
		String sql = "update firewall_rule set policy_id = null,policy_uuid = null where policy_id = :policyId and is_deleted = 0";
		Map<String, Object> paramMap = MapTools.simpleMap("policyId", policyId);
		return this.execute(sql, paramMap) > 0;
	}

	public boolean removeByVid(Long vendorId, Long userId) throws Exception {
		String sql = "update firewall_rule set is_deleted = 1,gmt_modify = :gmtModify,mender_id = :menderId where is_deleted = 0 and vendor_id = :vendorId";
		Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
		params.put("menderId", userId);
		params.put("gmtModify", new Date());
		return this.execute(sql, params) > 0;
	}

	public List<FirewallRule> listByVid(Long vendorId) throws Exception {
		String sql = "select a.*,t.name tenant_name from firewall_rule a left join tenant t on a.tenant_id = t.id where a.is_deleted = 0 and a.vendor_id = :vendorId ORDER BY a.position";
		Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
		return this.list(FirewallRule.class, sql, params);
	}

	public List<FirewallRule> listRuleByNoBoundPolicy(Long vendorId, Long tenantId) throws Exception {
		String sql = "select a.*,t.name tenant_name from firewall_rule a left join tenant t on a.tenant_id = t.id where a.is_deleted = 0 and a.vendor_id = :vendorId and a.policy_id is null and a.tenant_id = :tenantId ORDER BY a.position";
		Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
		params.put("tenantId", tenantId);
		return this.list(FirewallRule.class, sql, params);
	}

	public List<FirewallRule> listRuleByPolicyId(Long policyId) throws Exception {
		String sql = "select a.*,t.name tenant_name from firewall_rule a left join tenant t on a.tenant_id = t.id where a.is_deleted = 0 and a.policy_id = :policyId ORDER BY a.position";
		Map<String, Object> params = MapTools.simpleMap("policyId", policyId);
		return this.list(FirewallRule.class, sql, params);
	}

	public boolean resetPolicyByVendor(Long vendorId) throws Exception {
		String sql = "update firewall_rule set policy_id = null,policy_uuid = null where vendor_id = :vendorId and is_deleted = 0";
		Map<String, Object> paramMap = MapTools.simpleMap(Common.VENDORID, vendorId);
		return this.execute(sql, paramMap) > 0;
	}

	public int count(List<Param> params, Long userId, Long tenantId, Long projectId) throws Exception {
		String sql = null;
		if (null != userId && null != tenantId) {
			sql = "select count(1) from firewall_rule a,object_relation b where a.is_deleted = 0 and a.id = b.res_id and b.category = 'FirewallRule' and b.catalog = 'USER' and b.target = "
					+ userId + " and a.tenant_id = " + tenantId;
		} else if (null == userId && null != tenantId) {
			sql = "select count(1) from firewall_rule a where a.is_deleted = 0 and a.tenant_id = " + tenantId;
		} else {
			sql = "select count(1) from firewall_rule a where a.is_deleted = 0";
		}
		if (null != projectId && 0L != projectId) {
			sql += " and a.project_id = " + projectId;
		}
		sql = QueryBuilder.buildRaw(sql, params, null, "a");
		Map<String, Object> paramMap = QueryBuilder.getParam(params);
		return this.countQuery(sql, paramMap).intValue();
	}

	public List<FirewallRule> list(int page, int rows, List<Param> params, Map<String, String> sorter, Long userId,
			Long tenantId, Long projectId) throws Exception {
		String sql = null;
		if (null != userId && null != tenantId) {
			sql = "select a.*,v.name vendor_name,v.type vendor_type,t.name tenant_name from firewall_rule a left join tenant t on a.tenant_id = t.id left join cloud_vendor v on a.vendor_id = v.id,object_relation b where a.is_deleted = 0 and a.id = b.res_id and b.category = 'FirewallRule' and b.catalog = 'USER' and b.target = "
					+ userId + " and a.tenant_id = " + tenantId;
		} else if (null == userId && null != tenantId) {
			sql = "select a.*,v.name vendor_name,v.type vendor_type,t.name tenant_name from firewall_rule a left join tenant t on a.tenant_id = t.id left join cloud_vendor v on a.vendor_id = v.id,object_relation b where a.is_deleted = 0 and a.id = b.res_id and b.category = 'FirewallRule' and b.catalog = 'USER' and a.tenant_id = "
					+ tenantId;
		} else {
			sql = "select a.*,t.name tenant_name from firewall_rule a left join tenant t on a.tenant_id = t.id where a.is_deleted = 0";
		}
		if (null != projectId && 0L != projectId) {
			sql += " and a.project_id = " + projectId;
		}
		sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, sorter), "a");
		Map<String, Object> paramMap = QueryBuilder.getParam(params);
		return this.list(FirewallRule.class, sql, paramMap);
	}

	public boolean inUseByTenants(Long vendorId) throws Exception {
		String sql = "select count(1) from firewall_rule a where a.is_deleted = 0 and a.tenant_id is not null and a.tenant_id != 0 and a.vendor_id = :vendorId";
		Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
		return this.countQuery(sql, params).intValue() > 0;
	}

	public boolean tenantCheck(Long tenantId, Long projectId, Long creatorId) throws Exception {
		String sql = "select count(1) from firewall_rule a where a.is_deleted = 0 ";
		Map<String, Object> paramMap = Maps.newHashMap();
		if (null != tenantId && 0L != tenantId) {
			sql += " and a.tenant_id = :tenantId";
			paramMap.put("tenantId", tenantId);
		}
		if (null != projectId && 0L != projectId) {
			sql += " and a.project_id = :projectId";
			paramMap.put("projectId", projectId);
		}
		if (null != creatorId && 0L != creatorId) {
			sql += " and a.creator_id = :creatorId";
			paramMap.put("creatorId", creatorId);
		}
		return this.countQuery(sql, paramMap).intValue() > 0;
	}

	/**
	 * 根据防火墙规则UUID
	 *
	 * @param ruleUuid
	 * @param vendorId
	 * @return
	 * @throws Exception
	 */

	public FirewallRule getByUuid(String ruleUuid, Long vendorId) throws Exception {
		String sql = "select a.*,t.name tenant_name from firewall_rule a left join tenant t on a.tenant_id = t.id where a.rule_uuid = :ruleUuid and a.is_deleted = 0 and a.vendor_id = :vendorId";
		Map<String, Object> paramMap = MapTools.simpleMap("ruleUuid", ruleUuid);
		paramMap.put(Common.VENDORID, vendorId);
		List<FirewallRule> list = this.list(FirewallRule.class, sql, paramMap);
		if (list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

	public boolean removeByFirewallId(Long vendorId, Long firewallId, Long userId) {
		String sql = "update firewall_rule set is_deleted = 1,gmt_modify = :gmtModify,mender_id = :menderId where is_deleted = 0 and vendor_id = :vendorId and firewall_id = :firewallId ";
		Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
		params.put("menderId", userId);
		params.put("firewallId", firewallId);
		params.put("gmtModify", new Date());
		return this.execute(sql, params) > 0;
	}

	public int count(List<Param> params, String vendorType) {
		String sql = "select count(1) from firewall_rule a left join cloud_vendor c on a.vendor_id = c.id and c.is_deleted = 0 where a.is_deleted = 0";
		Map<String, Object> paramMap = QueryBuilder.getParam(params);
		if (!StringUtils.isEmpty(vendorType)) {
			sql += " and c.type = :vendorType ";
			paramMap.put("vendorType", vendorType);
		}
		sql = QueryBuilder.build(sql, params, null, "a");
		return this.countQuery(sql, paramMap).intValue();
	}

	public List<FirewallRule> list(Integer page, Integer rows, List<Param> params, Map<String, String> sorter,
			String vendorType) {
		String sql = "select a.*,b.name policy_name,v.name vendor_name,t.name tenant_name from firewall_rule a left join tenant t on a.tenant_id = t.id left join firewall_policy b on a.policy_id = b.id left join cloud_vendor v on a.vendor_id = v.id where a.is_deleted = 0";
		Map<String, Object> paramMap = QueryBuilder.getParam(params);
		if (!StringUtils.isEmpty(vendorType)) {
			sql += " and v.type = :vendorType ";
			paramMap.put("vendorType", vendorType);
		}
		sql = QueryBuilder.build(sql, new Pager(page, rows, params, sorter), "a");
		return this.list(FirewallRule.class, sql, paramMap);
	}

}
