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.Router;
import com.google.common.collect.Lists;
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.Date;
import java.util.List;
import java.util.Map;

/**
 * 路由Repository接口实现
 *
 * @author dongkai
 */
@Repository("routerRepository")
public class RouterRepository extends BasicGenericDao<Router, Long> {

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

	@Override
	public void save(Router router) throws BoCloudDBException {
		router.setGuid(IDFactory.instance().uuid());
		super.save(router);
	}

	public List<Router> list(int page, int rows, List<Param> params, Map<String, String> sorter) {
		String sql = "select a.*,b.name network_name,p.visibility project_visibility, v.name vendor_name,t.name tenant_name, r.name region_name from router a "
				+ " left join region r on a.vendor_id = r.vendor_id and a.region_id = r.region_id "
				+ " left join project p on a.project_id = p.id "
				+ " left join tenant t on a.tenant_id = t.id left join network b on a.network_id = b.id left join cloud_vendor v on a.vendor_id = v.id 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(Router.class, sql, paramMap);
	}

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

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

	public int count(List<Param> params) {
		String sql = "select count(1) from router a where a.is_deleted = 0";
		sql = QueryBuilder.buildRaw(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 router 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 boolean remove(Long id) {
		String sql = "update router set is_deleted = true,gmt_modify = :gmtModify where is_deleted = 0 and id = :id";
		Map<String, Object> params = MapTools.simpleMap("id", id);
		params.put("gmtModify", new Date());
		return this.execute(sql, params) > 0;

	}

	public boolean removeByVid(Long vendorId, Long userId) {
		String sql = "update router 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 Router query(Long id) {
		String sql = "select a.*,b.name network_name,t.name tenant_name, p.visibility project_visibility,p.name project_name,u.name target_name, r.`name` region_name from router a "
				+ " left join region r on a.vendor_id = r.vendor_id and a.region_id = r.region_id "
				+ " left join tenant t on a.tenant_id = t.id left join network b on a.network_id = b.id "
				+ " left join project p on p.id = a.project_id left join object_relation o on o.res_id = a.id and o.category = 'Router' left join user u on u.id = o.target and o.catalog = 'USER' where a.is_deleted = 0 and a.id = :id";
		Map<String, Object> params = MapTools.simpleMap(Common.ID, id);
		List<Router> list = this.list(Router.class, sql, params);
		if (list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

	public Router query(String routerUuid, Long vendorId) {
		String sql = "select a.*,t.name tenant_name,p.name project_name,u.name target_name from router a left join tenant t on a.tenant_id = t.id left join project p on p.id = a.project_id left join object_relation o on o.res_id = a.id and o.category = 'Router' left join user u on u.id = o.target and o.catalog = 'USER' where a.is_deleted = 0 and a.vendor_id = :vendorId and a.router_uuid = :routerUuid";
		Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
		params.put("routerUuid", routerUuid);
		List<Router> list = this.list(Router.class, sql, params);
		if (list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

	public boolean updateFirewallByRouterId(Long routerId, Long firewallId, String firewallUuid) {
		String sql = "update router set firewall_id = :firewallId,firewall_uuid = :firewallUuid where id = :id and is_deleted = 0";
		Map<String, Object> paramMap = MapTools.simpleMap("id", routerId);
		paramMap.put("firewallId", firewallId);
		paramMap.put("firewallUuid", firewallUuid);
		return this.execute(sql, paramMap) > 0;
	}

	public boolean updateFirewallByRouterId(String routerUuid, Long firewallId, String firewallUuid) {
		String sql = "update router set firewall_id = :firewallId,firewall_uuid = :firewallUuid where router_uuid = :routerUuid and is_deleted = 0";
		Map<String, Object> paramMap = MapTools.simpleMap("routerUuid", routerUuid);
		paramMap.put("firewallId", firewallId);
		paramMap.put("firewallUuid", firewallUuid);
		return this.execute(sql, paramMap) > 0;
	}

	public boolean updateFirewallIdAndUuid(Long firewallId) {
		String sql = "update router set firewall_id = null,firewall_uuid = null where firewall_id = :firewallId and is_deleted = 0";
		Map<String, Object> paramMap = MapTools.simpleMap("firewallId", firewallId);
		return this.execute(sql, paramMap) > 0;
	}

	public boolean resetFirewallByVendor(Long vendorId) {
		String sql = "update router set firewall_id = null,firewall_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 List<Router> listRouterByNoBoundFirewall(Long vendorId, Long tenantId, String tenantUuid) {
		String sql = "select a.*,t.name tenant_name from router a left join tenant t on a.tenant_id = t.id where a.firewall_id is null and a.vendor_id = :vendorId and a.is_deleted = 0";
		Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
		if (0L != tenantId) {
			sql += " and a.tenant_id = :tenantId";
			params.put("tenantId", tenantId);
		} else {
			sql += " and a.tenant_id = 0";
		}
		if (!StringUtils.isEmpty(tenantUuid)) {
			sql += " and a.tenant_uuid = :tenantUuid";
			params.put("tenantUuid", tenantUuid);
		}
		return this.list(Router.class, sql, params);
	}

	public List<Router> listByFirewallId(Long firewallId) {
		String sql = "select a.*,t.name tenant_name from router a left join tenant t on a.tenant_id = t.id where a.firewall_id = :firewallId and a.is_deleted = 0";
		Map<String, Object> params = MapTools.simpleMap("firewallId", firewallId);
		return this.list(Router.class, sql, params);
	}

	public List<Router> listByFirewallId(Long firewallId, Long vendorId) {
		String sql = "select a.*,t.name tenant_name from router a left join tenant t on a.tenant_id = t.id where a.firewall_id = :firewallId and a.is_deleted = 0 and a.vendor_id = :vendorId ";
		Map<String, Object> params = MapTools.simpleMap("firewallId", firewallId);
		params.put("vendorId", vendorId);
		return this.list(Router.class, sql, params);
	}

	public List<Router> listByNetworkId(Long networkId) {
		String sql = "select a.*,t.name tenant_name from router a left join tenant t on a.tenant_id = t.id where a.is_deleted = 0 and a.network_id = :networkId ";
		Map<String, Object> params = MapTools.simpleMap("networkId", networkId);
		return this.list(Router.class, sql, params);
	}

	public int count(List<Param> params, Long tenantId, List<Long> projectIds) {
		String sql = "select count(a.id) from router a left join tenant t on a.tenant_id = t.id left join network n on a.network_id = n.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 (null != tenantId && 0L != tenantId) {
			sql += " and a.tenant_id = :tenantId";
			paramMap.put("tenantId", tenantId);
		}
		if (!ListTool.isEmpty(projectIds)) {
			sql += " and a.project_id in (:projectIds) ";
			paramMap.put("projectIds", projectIds);
		}
		sql = QueryBuilder.buildRaw(sql, params, null, "a");
		return this.countQuery(sql, paramMap).intValue();
	}

	public int count(List<Param> params, Long tenantId, List<Long> projectIds, String type) {
		String sql = "select count(a.id) from router a left join tenant t on a.tenant_id = t.id left join network n on a.network_id = n.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 (null != tenantId && 0L != tenantId) {
			sql += " and a.tenant_id = :tenantId";
			paramMap.put("tenantId", tenantId);
		}
		if (!StringUtils.isEmpty(type)) {
			sql += " and v.type = :type ";
			paramMap.put("type", type);
		}
		if (!ListTool.isEmpty(projectIds)) {
			sql += " and a.project_id in (:projectIds) ";
			paramMap.put("projectIds", projectIds);
		}
		sql = QueryBuilder.buildRaw(sql, params, null, "a");
		return this.countQuery(sql, paramMap).intValue();
	}

	public List<Router> list(int page, int rows, List<Param> params, Map<String, String> sorter, Long tenantId,
			List<Long> projectIds) {
		String sql = "select a.*,n.name network_name,v.name vendor_name, project.visibility project_visibility,v.type vendor_type,t.name tenant_name from router a "
				+ " left join tenant t on a.tenant_id = t.id "
				+ " left join project project on a.project_id = project.id "
				+ " left join network n on a.network_id = n.id "
				+ " left join cloud_vendor v on a.vendor_id = v.id  where a.is_deleted = 0 and v.type = 'OPENSTACK'";
		Map<String, Object> paramMap = QueryBuilder.getParam(params);
		if (null != tenantId && 0L != tenantId) {
			sql += " and a.tenant_id = :tenantId";
			paramMap.put("tenantId", tenantId);
		}
		if (!ListTool.isEmpty(projectIds)) {
			sql += " and a.project_id in (:projectIds) ";
			paramMap.put("projectIds", projectIds);
		}
		sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, sorter), "a");
		return this.list(Router.class, sql, paramMap);
	}

	public List<Router> list(int page, int rows, List<Param> params, Map<String, String> sorter, Long tenantId,
			List<Long> projectIds, String type) {
		String sql = "select a.*,n.name network_name,v.name vendor_name, project.visibility project_visibility,v.type vendor_type,t.name tenant_name from router a "
				+ " left join tenant t on a.tenant_id = t.id "
				+ " left join project project on a.project_id = project.id "
				+ " left join network n on a.network_id = n.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 (null != tenantId && 0L != tenantId) {
			sql += " and a.tenant_id = :tenantId";
			paramMap.put("tenantId", tenantId);
		}
		if (!StringUtils.isEmpty(type)) {
			sql += " and v.type = :type ";
			paramMap.put("type", type);
		}
		if (!ListTool.isEmpty(projectIds)) {
			sql += " and a.project_id in (:projectIds) ";
			paramMap.put("projectIds", projectIds);
		}
		sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, sorter), "a");
		return this.list(Router.class, sql, paramMap);
	}

	public boolean inUseByTenants(Long vendorId) {
		String sql = "select count(1) from router 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) {
		String sql = "select count(1) from router 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 List<Router> listByVid(Long vendorId, String regionId) {
		String sql = "select a.*,t.name tenant_name from router a left join tenant t on a.tenant_id = t.id where a.is_deleted = 0 and a.vendor_id = :vendorId"
				+ " and a.region_id = :regionId ";
		Map<String, Object> params = MapTools.simpleMap(Common.VENDORID, vendorId);
		params.put(Common.REGIONID, regionId);
		return this.list(Router.class, sql, params);
	}

	public boolean removeByVid(Long vendorId, String regionId, Long userId) {
		String sql = "update router 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 Router getByName(Long vendorId, String name) {
		String sql = "select a.* from router a where a.is_deleted = 0 and a.vendor_id = :vendorId and a.name = :name";
		Map<String, Object> paramMap = MapTools.simpleMap(Common.VENDORID, vendorId);
		paramMap.put("name", name);
		List<Router> list = this.list(Router.class, sql, paramMap);
		if (list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

	public List<Router> listByRouterIds(List<Long> routerIds) {
		String sql = "select a.* from router a where a.is_deleted = 0 and a.id in (:routerIds)";
		Map<String, Object> params = MapTools.simpleMap("routerIds", routerIds);
		return this.list(Router.class, sql, params);
	}

	public List<Router> listUnBingFirewall(Long vendorId, List<Long> projectIds) {
		String sql = "select a.* from router a where a.is_deleted = 0 and a.project_id in (:projectIds) and a.vendor_id = :vendorId and a.firewall_id  IS NULL";
		Map<String, Object> params = MapTools.simpleMap("projectIds", projectIds);
		params.put("vendorId", vendorId);
		return this.list(Router.class, sql, params);
	}

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

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

}
