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.ListTool;
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.Keypair;
import com.bocloud.ims.entity.resource.SecurityGroup;
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年10月12日
 */
@Repository("keypairRepository")
public class KeypairRepository extends BasicGenericDao<Keypair, Long> {

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

	public List<Keypair> list(int page, int rows, List<Param> params, Map<String, String> sorter) throws Exception {
		String sql = "select a.*,t.name tenant_name,v.name vendor_name, r.name region_name, project.visibility project_visibility, rg.name resource_group_name from keypair a "
				+ " left join region r on a.region_id = r.region_id and a.vendor_id = r.vendor_id "
				+ " left join resource_group rg on a.resource_group_uuid = rg.resource_group_uuid and a.vendor_id = rg.vendor_id "
				+ " left join project project on a.project_id = project.id "
				+ " left join tenant t on a.tenant_id = t.id left join cloud_vendor v on v.id = a.vendor_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(Keypair.class, sql, paramMap);
	}

	public List<SimpleBean> list(List<Param> params, Map<String, String> sorter) throws Exception {
		String sql = "select a.id,a.name from keypair a left join tenant t on a.tenant_id = t.id 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<Keypair> keypairs = this.list(Keypair.class, sql, paramMap);
		List<SimpleBean> beans = new ArrayList<>();
		for (Keypair keypair : keypairs) {
			beans.add(new SimpleBean(keypair.getId(), keypair.getName()));
		}
		return beans;
	}

	public int count(List<Param> params) throws Exception {
		String sql = "select count(1) from keypair 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 Boolean remove(Long id, Long userId) throws Exception {
		String sql = "update keypair 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 Keypair query(Long id) throws Exception {
		String sql = "select a.*,t.name tenant_name,p.name project_name,v.name vendor_name, r.`name` region_name, rg.name resource_group_name, p.visibility project_visibility from keypair a "
				+ " left join region r on a.vendor_id = r.vendor_id and a.region_id = r.region_id "
				+ " left join resource_group rg on a.resource_group_uuid = rg.resource_group_uuid and a.vendor_id = rg.vendor_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<Keypair> list = this.list(Keypair.class, sql, paramMap);
		if (list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

	public Keypair getPrivateKey(Long id) throws Exception {
		String sql = " select a.name, a.private_key private_key_content from keypair a where a.id = :id and a.is_deleted = 0 ";
		Map<String, Object> paramMap = MapTools.simpleMap("id", id);
		List<Keypair> list = this.list(Keypair.class, sql, paramMap);
		if (list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

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

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

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

	public List<Keypair> listByVid(Long vendorId) throws Exception {
		String sql = "select a.*,t.name tenant_name,v.name vendor_name from keypair a left join tenant t on a.tenant_id = t.id  left join cloud_vendor v on v.id = a.vendor_id where a.is_deleted = 0 and a.vendor_id = :vendorId";
		Map<String, Object> paramMap = MapTools.simpleMap(Common.VENDORID, vendorId);
		List<Keypair> list = this.list(Keypair.class, sql, paramMap);
		if (list.isEmpty()) {
			return new ArrayList<>();
		}
		return list;
	}

	public Boolean removeByVid(Long vendorId, Long userId) throws Exception {
		String sql = "update keypair set is_deleted = true,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 boolean tenantCheck(Long tenantId, Long projectId, Long creatorId) throws Exception {
		String sql = "select count(1) from keypair 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;
	}

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

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

	public List<Keypair> listByVid(Long vendorId, String regionId) throws Exception {
		String sql = "select a.*,t.name tenant_name,v.name vendor_name from keypair a left join tenant t on a.tenant_id = t.id  left join cloud_vendor v on v.id = a.vendor_id where a.is_deleted = 0 and a.vendor_id = :vendorId"
				+ " and a.region_id =:regionId ";
		Map<String, Object> paramMap = MapTools.simpleMap(Common.VENDORID, vendorId);
		paramMap.put(Common.REGIONID, regionId);
		List<Keypair> list = this.list(Keypair.class, sql, paramMap);
		if (list.isEmpty()) {
			return new ArrayList<>();
		}
		return list;
	}

	public List<Keypair> listByInstanceId(Long serverId) throws Exception {
		String sql = "SELECT k.* FROM keypair k WHERE k.id IN ( SELECT s.keypair_id FROM server_keypair s WHERE s.server_id = :serverId )";
		Map<String, Object> paramMap = MapTools.simpleMap("serverId", serverId);
		List<Keypair> list = this.list(Keypair.class, sql, paramMap);
		if (list.isEmpty()) {
			return new ArrayList<>();
		}
		return list;
	}

	public List<Keypair> listunBindKeyPair(Long serverId, Long vendorId, Long tenantId, String region)
			throws Exception {
		String sql = "SELECT k.* FROM keypair k WHERE k.vendor_id = :vendorId and k.is_deleted = 0 and  "
				+ " k.id not IN ( SELECT s.keypair_id FROM server_keypair s WHERE s.server_id = :serverId ) ";
		Map<String, Object> paramMap = MapTools.simpleMap("serverId", serverId);
		paramMap.put(Common.VENDORID, vendorId);
		if(null != tenantId && 0 != tenantId) {
			sql += " and k.tenant_id = :tenantId ";
			paramMap.put("tenantId", tenantId);
		}
		if (StringUtils.isNoneEmpty(region)) {
			sql += " and k.region_id = :region ";
			paramMap.put("region", region);
		}
		List<Keypair> list = this.list(Keypair.class, sql, paramMap);
		if (list.isEmpty()) {
			return new ArrayList<>();
		}
		return list;
	}

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

	public int count(List<Param> params, List<Long> tenantVendorIds) {
		String sql = "select count(1) from keypair a where a.is_deleted = 0";
		Map<String, Object> paramMap = QueryBuilder.getParam(params);
		if (!ListTool.isEmpty(tenantVendorIds)) {
			sql += " and a.vendor_id in (:tenantVendorIds) ";
			paramMap.put("tenantVendorIds", tenantVendorIds);
		}
		sql = QueryBuilder.build(sql, params, null, "a");
		return this.countQuery(sql, paramMap).intValue();
	}

	public List<Keypair> list(Integer page, Integer rows, List<Param> params, Map<String, String> sorter,
			List<Long> tenantVendorIds) {
		String sql = "select a.*,t.name tenant_name,v.name vendor_name, r.name region_name, project.visibility project_visibility, rg.name resource_group_name from keypair a "
				+ " left join region r on a.region_id = r.region_id and a.vendor_id = r.vendor_id "
				+ " left join resource_group rg on a.resource_group_uuid = rg.resource_group_uuid and a.vendor_id = rg.vendor_id "
				+ " left join project project on a.project_id = project.id "
				+ " left join tenant t on a.tenant_id = t.id left join cloud_vendor v on v.id = a.vendor_id where a.is_deleted = 0";
		Map<String, Object> paramMap = QueryBuilder.getParam(params);
		if (!ListTool.isEmpty(tenantVendorIds)) {
			sql += " and a.vendor_id in (:tenantVendorIds) ";
			paramMap.put("tenantVendorIds", tenantVendorIds);
		}
		sql = QueryBuilder.build(sql, new Pager(page, rows, params, sorter), "a");
		return this.list(Keypair.class, sql, paramMap);
	}

}
