package com.bocloud.ims.repository.resource;

import com.bocloud.common.exception.BoCloudDBException;
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.IDFactory;
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.Port;
import com.bocloud.ims.entity.resource.PortGroup;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import org.apache.commons.lang3.StringUtils;

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

/**
 * 端口Repository接口实现
 *
 * @author dongkai
 */
@Repository("portRepository")
public class PortRepository extends BasicGenericDao<Port, Long> {

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

	@Override

	public void save(Port port) throws BoCloudDBException {
		port.setGuid(IDFactory.instance().uuid());
		super.save(port);
	}

	public List<Port> list(int page, int rows, List<Param> params, Map<String, String> sorter) {
		String sql = "select a.*, b.name as device_name "
				+ "from port a left join cloud_server b on a.device_uuid = b.instance_id and a.vendor_id = b.vendor_id and b.is_deleted = 0 "
				+ "where a.is_deleted = 0";
		sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, sorter), "a");
		Map<String, Object> paramMap = QueryBuilder.getParam(params);
		return this.list(Port.class, sql, paramMap);
	}

	public List<SimpleBean> list(List<Param> params, Map<String, String> sorter) {
		String sql = "select a.id,a.name,a.port_uuid from port 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<Port> ports = this.list(Port.class, sql, paramMap);
		List<SimpleBean> beans = Lists.newArrayList();
		for (Port port : ports) {
			beans.add(new SimpleBean(port.getId(), port.getName(), port.getPortUuid()));
		}
		return beans;
	}

	public int portCount(List<Param> params, Long vendorId){
		String sql = "select count(1) from port a  where a.is_deleted=0";
		if (vendorId !=null){
			sql += " and a.vendor_id = '" + vendorId + "'  ";
		}
		sql = QueryBuilder.build(sql,params,null,"a");
		Map<String,Object> param = QueryBuilder.getParam(params);
		return this.countQuery(sql,param).intValue();
	}

	public List<Port> portList(int page, int rows, List<Param> params, Map<String, String> sorter, Long vendorId) throws BoCloudDBException {
		String sql = "select * from port a  where a.is_deleted=0";
		if (vendorId !=null){
			sql += " and a.vendor_id = '" + vendorId + "'  ";
		}
		sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, sorter), "a");
		return this.list(Port.class, sql);
	}

	public List<Port> list(Long vendorId, Long subnetId) {
		String sql = "select a.* from port a where a.is_deleted = 0 and a.vendor_id = :vendorId and  exists(select 1 from port_fixedip b where a.id = b.port_id and b.subnet_id = :subnetId)";
		Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
		params.put("subnetId", subnetId);
		return this.list(Port.class, sql, params);
	}

	public List<Port> listByVid(Long vendorId) {
		String sql = "select a.* from port a where a.is_deleted = 0 and a.vendor_id = :vendorId";
		Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
		return this.list(Port.class, sql, params);
	}

	public List<Port> listByVid(Long vendorId, String regionId) throws Exception {
		String sql = "select a.*,v.name vendor_name from port a 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<Port> list = this.list(Port.class, sql, paramMap);
		if (list.isEmpty()) {
			return new ArrayList<>();
		}
		return list;
	}

	public int count(List<Param> params) {
		String sql = "select count(1) from port 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) {
		String sql = "update port set is_deleted = 1,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 Boolean removeByNetworkId(Long networkId, Long userId) {
		String sql = "update port set is_deleted = true,gmt_modify = :gmtModify,mender_id = :menderId where is_deleted = 0 and network_id = :networkId";
		Map<String, Object> params = MapTools.simpleMap("networkId", networkId);
		params.put("menderId", userId);
		params.put("gmtModify", new Date());
		return this.execute(sql, params) > 0;

	}

	public Boolean removeBySubnetId(Long subnetId, Long userId) {
		String sql = "update port a set is_deleted = true,gmt_modify = :gmtModify,mender_id = :menderId where is_deleted = 0 and exists(select 1 from port_fixedip b where a.id=b.port_id and b.subnet_id=:subnetId)";
		Map<String, Object> params = MapTools.simpleMap("subnetId", subnetId);
		params.put("menderId", userId);
		params.put("gmtModify", new Date());
		return this.execute(sql, params) > 0;

	}

	public Boolean deleteBySubnetIdAndIp(Long subnetId, String Ip) {
		String sql = "delete from port where  exists(select 1 from port_fixedip b where port.id=b.port_id and b.subnet_id=:subnetId and b.ip_address=:ipAddress) ";
		Map<String, Object> params = MapTools.simpleMap("subnetId", subnetId);
		params.put("ipAddress", Ip);
		return this.execute(sql, params) > 0;
	}

	public boolean removeByVid(Long vendorId, Long userId) {
		String sql = "update port 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 Port query(Long id) {
		String sql = "select a.* , n.name network_name from port a left join network n on a.vendor_id = n.vendor_id and a.network_uuid = n.network_uuid where a.id = :id";
		Map<String, Object> params = MapTools.simpleMap(Common.ID, id);
		List<Port> list = this.list(Port.class, sql, params);
		if (list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

	public List<Port> listPortIsNotExternal(Long vendorId) {
		String sql = "select a.* from port a,router b,network c where a.is_deleted = 0 and b.is_deleted = 0 and c.is_deleted = 0 and a.device_uuid = b.router_uuid and a.network_id = c.id and c.is_router_external = 0 and a.vendor_id = :vendorId";
		Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
		return this.list(Port.class, sql, params);
	}

	public List<Port> listBySubnetId(Long subnetId) {
		String sql = "select a.* from port a where a.is_deleted = 0 and exists(select 1 from port_fixedip b where a.id=b.port_id and b.subnet_id = :subnetId)";
		Map<String, Object> params = MapTools.simpleMap("subnetId", subnetId);
		return this.list(Port.class, sql, params);
	}

	public List<Port> listByDeviceId(String deviceUuid, Long vendorId) {
		String sql = "select a.*, n.name network_name " + "from port a left join network n on "
				+ "      a.vendor_id = n.vendor_id and a.network_uuid = n.network_uuid and n.is_deleted = 0 "
				+ "where a.is_deleted = 0 and a.device_uuid = :deviceUuid and a.vendor_id = :vendorId";
		Map<String, Object> params = MapTools.simpleMap("deviceUuid", deviceUuid);
		params.put(Common.VENDORID, vendorId);
		List<Port> list = this.list(Port.class, sql, params);
		if (list.isEmpty()) {
			return new ArrayList<>();
		}
		return list;
	}

	public List<Port> listExtranetByDeviceId(String deviceUuid, Long vendorId) {
		String sql = "select a.*,b.ip_address from port a left join port_fixedip b on a.id = b.port_id left join subnet c on b.subnet_id = c.id left join router_subnet e on e.subnet_id = c.id left join router d on d.id = e.router_id where d.network_id is not null and a.is_deleted = 0 and c.is_deleted = 0 and d.is_deleted = 0 and a.vendor_id = :vendorId and a.device_uuid = :deviceUuid ";
		Map<String, Object> params = MapTools.simpleMap("deviceUuid", deviceUuid);
		params.put(Common.VENDORID, vendorId);
		List<Port> list = this.list(Port.class, sql, params);
		if (list.isEmpty()) {
			return new ArrayList<>();
		}
		return list;
	}

	public List<Port> listBySubnetUuid(String subnetUuid) {
		String sql = "select a.* from port a where exists(select 1 from port_fixedip b where a.id=b.port_id and b.subnet_uuid=:subnetUuid)";
		Map<String, Object> params = MapTools.simpleMap("subnetUuid", subnetUuid);
		return this.list(Port.class, sql, params);
	}

	public List<Port> listByNetworkUuid(String networkUuid, Long vendorId) {
		String sql = "select a.* from port a where a.is_deleted = 0 and a.network_uuid = :networkUuid and vendor_id = :vendorId";
		Map<String, Object> params = MapTools.simpleMap("networkUuid", networkUuid);
		params.put(Common.VENDORID, vendorId);
		return this.list(Port.class, sql, params);
	}

	public List<Port> listByNetworkId(Long networkId) {
		String sql = "select a.* from port a where a.is_deleted = 0 and a.network_id = :networkId and (a.device_owner = '' or a.device_owner is null)";
		Map<String, Object> params = MapTools.simpleMap("networkId", networkId);
		return this.list(Port.class, sql, params);
	}

	public List<Port> listAllByNetworkId(Long networkId) {
		String sql = "select a.* from port a where a.is_deleted = 0 and a.network_id = :networkId ";
		Map<String, Object> params = MapTools.simpleMap("networkId", networkId);
		return this.list(Port.class, sql, params);
	}

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

	public Port getByPortUuid(String portUuid, Long vendorId) {
		String sql = "select a.* from port a where a.port_uuid = :portUuid and a.vendor_id = :vendorId";
		Map<String, Object> params = MapTools.simpleMap("portUuid", portUuid);
		params.put(Common.VENDORID, vendorId);
		List<Port> list = this.list(Port.class, sql, params);
		if (list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

	public List<Port> listBySubnetId(Long subnetId, String deviceOwner) {
		String sql = "select a.* from port a left join port_fixedip b on a.id = b.port_id where b.subnet_id = :subnetId and a.device_owner = :deviceOwner";
		Map<String, Object> params = MapTools.simpleMap("subnetId", subnetId);
		params.put("deviceOwner", deviceOwner);
		return this.list(Port.class, sql, params);
	}

	public List<Port> listByVmId(long vmId) {
		String sql = "SELECT a.*, b.ip_address, d.name as network_name, IFNULL(s.subnet_count, 0) as subnet_count FROM port a "
				+ "       LEFT JOIN port_fixedip b ON a.id = b.port_id "
				+ "       LEFT JOIN cloud_server c ON a.device_uuid = c.instance_id and a.vendor_id = c.vendor_id"
				+ "       LEFT JOIN network d ON a.network_id = d.id "
				+ "       LEFT JOIN (select network_id, count(1) as subnet_count "
				+ "                    from subnet group by network_id) s ON a.network_id = s.network_id "
				+ "WHERE a.is_deleted = 0 AND c.id = :vmId ";
		Map<String, Object> params = MapTools.simpleMap("vmId", vmId);
		return this.list(Port.class, sql, params);
	}

	public boolean removeByVid(Long vendorId, String regionId, Long userId) throws Exception {
		String sql = "update port 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<Port> listAvailablePortByDeviceId(String deviceUuid, Long vendorId) {
		String sql = "select a.*, n.name network_name, pf.ip_address as ip_address "
				+ "from port a left join network n on "
				+ "      a.vendor_id = n.vendor_id and a.network_uuid = n.network_uuid and n.is_deleted = 0 "
				+ "left join port_fixedip pf on pf.port_id = a.id "
				+ "where a.is_deleted = 0 and a.device_uuid = :deviceUuid and a.vendor_id = :vendorId "
				+ "and a.id not in (select port_id from nat_gateway_dnat_rule where vendor_id = :vendorId and is_deleted = 0) ";
		Map<String, Object> params = MapTools.simpleMap("deviceUuid", deviceUuid);
		params.put(Common.VENDORID, vendorId);
		List<Port> list = this.list(Port.class, sql, params);
		if (list.isEmpty()) {
			return new ArrayList<>();
		}
		return list;
	}

	public Port listByDeviceUuid(String deviceUuid, Long vendorId, String deviceOwner) {

		String sql = "select * from port p where 1=1 and p.is_deleted=0  and p.vendor_id=:vendorId and p.device_uuid=:deviceUuid";
		Map<String, Object> params = MapTools.simpleMap("vendorId", vendorId);
		params.put("deviceUuid", deviceUuid);
		if (!StringUtils.isEmpty(deviceOwner)) {
			sql += " and p.device_owner = :deviceOwner";
			params.put("deviceOwner", deviceOwner);
		}
		List<Port> list = this.list(Port.class, sql, params);
		if (list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

	public List<Port> listAssociatePort(Long vendorId, List<Long> projectIds, Long userId, Long tenantId) {
		String subquerySql = "select a.*,b.name device_name,d.ip_address,b.project_id from port a,cloud_server b,subnet c,network n,port_fixedip d,router_subnet e where n.id = a.network_id and a.is_deleted = 0 and b.is_deleted = 0 and "
				+ " c.is_deleted = 0 and a.id=d.port_id and a.device_uuid = b.instance_id and d.subnet_id = c.id and d.subnet_id = e.subnet_id and a.vendor_id = "
				+ vendorId;
		Map<String, Object> paramMap = QueryBuilder.getParam(null);
		subquerySql += " and (1=-1  ";
		if (null != userId && 0L != userId) {
			subquerySql += " or b.owner_id =:userId or b.mender_id = :userId ";
			paramMap.put("userId", userId);
		}
		if (null != tenantId && 0L != tenantId) {
			subquerySql += " or b.tenant_id = :tenantId";
			paramMap.put("tenantId", tenantId);
		}
		if (null != projectIds && !projectIds.isEmpty()) {
			subquerySql += " or b.project_id in (:projectIds) ";
			paramMap.put("projectIds", projectIds);
		}
		subquerySql += " )";
		subquerySql += " union all "
				+ " select a.*,b.name device_name,d.ip_address,b.project_id from port a,load_balancer b,subnet c,network n,port_fixedip d,router_subnet e where n.id = a.network_id and a.is_deleted = 0 and b.is_deleted = 0 and "
				+ " c.is_deleted = 0 and a.id=d.port_id and a.device_uuid = b.lb_uuid and d.subnet_id = c.id and d.subnet_id = e.subnet_id and a.vendor_id = "
				+ vendorId;
		subquerySql += " and (1=-1  ";
		if (null != userId && 0L != userId) {
			subquerySql += " or b.owner_id =:userId or b.mender_id = :userId ";
			paramMap.put("userId", userId);
		}
		if (null != tenantId && 0L != tenantId) {
			subquerySql += " or b.tenant_id = :tenantId";
			paramMap.put("tenantId", tenantId);
		}
		if (null != projectIds && !projectIds.isEmpty()) {
			subquerySql += " or b.project_id in (:projectIds) ";
			paramMap.put("projectIds", projectIds);
		}
		subquerySql += " )";
		return this.list(Port.class, subquerySql, paramMap);
	}

	public List<Port> listAssociatePort(Long vendorId, List<Long> projectIds, String tenantUuid) {
		Map<String, Object> params = Maps.newHashMap();
		params.put(Common.VENDORID, vendorId);
		String sql = "select a.*,b.name device_name,d.ip_address,b.project_id from port a,cloud_server b,subnet c,network n,port_fixedip d,router_subnet e where n.id = a.network_id and a.is_deleted = 0 and b.is_deleted = 0 and "
				+ " c.is_deleted = 0 and a.id=d.port_id and a.device_uuid = b.instance_id and d.subnet_id = c.id and d.subnet_id = e.subnet_id and a.vendor_id =:vendorId ";
		if (!ListTool.isEmpty(projectIds)) {
			sql += " and b.project_id in (:projectIds)";
			params.put("projectIds", projectIds);
		} else {
			sql += " and b.project_id = 0";
		}
		if (!StringUtils.isEmpty(tenantUuid)) {
			sql += " and b.tenant_uuid = :tenantUuid";
			params.put("tenantUuid", tenantUuid);
		}
		sql += " union all "
				+ " select a.*,b.name device_name,d.ip_address,b.project_id from port a,load_balancer b,subnet c,network n,port_fixedip d,router_subnet e where n.id = a.network_id and a.is_deleted = 0 and b.is_deleted = 0 and "
				+ " c.is_deleted = 0 and a.id=d.port_id and a.device_uuid = b.lb_uuid and d.subnet_id = c.id and d.subnet_id = e.subnet_id and a.vendor_id = :vendorId ";
		if (!ListTool.isEmpty(projectIds)) {
			sql += " and b.project_id in (:projectIds)";
			params.put("projectIds", projectIds);
		} else {
			sql += " and b.project_id = 0";
		}
		if (!StringUtils.isEmpty(tenantUuid)) {
			sql += " and b.tenant_uuid = :tenantUuid";
			params.put("tenantUuid", tenantUuid);
		}
		return this.list(Port.class, sql, params);
	}

}
