package com.bocloud.ims.repository.kubernetes;

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.JdbcGenericDao;
import com.bocloud.database.utils.QueryBuilder;
import com.bocloud.ims.entity.resource.kubernetes.KubeDeployment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;

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

/**
 * @author weiwei
 */
@Component("kubeDeploymentRepository")
public class KubeDeploymentRepository extends JdbcGenericDao<KubeDeployment, Long> {

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

	public List<KubeDeployment> list(int page, int rows, List<Param> params, Map<String, String> sorter)
			throws Exception {
		return this.list(page, rows, params, sorter, null);
	}

	public List<SimpleBean> list(List<Param> params, Map<String, String> sorter) throws Exception {
		String sql = "select a.id,a.name from kube_deployment a where a.is_deleted = 0";
		sql = QueryBuilder.buildRaw(sql, new Pager(1, Integer.MAX_VALUE, params, sorter), "a");
		Map<String, Object> paramMap = QueryBuilder.getParam(params);
		List<KubeDeployment> contracts = this.list(KubeDeployment.class, sql, paramMap);
		List<SimpleBean> beans = new ArrayList<SimpleBean>();
		for (KubeDeployment contract : contracts) {
			beans.add(new SimpleBean(contract.getId(), contract.getName()));
		}
		return beans;
	}

	public int count(List<Param> params) throws Exception {
		return this.count(params, null);
	}

	public boolean remove(Long id, Long userId) throws Exception {
		String sql = "update kube_deployment 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 KubeDeployment query(Long id) throws Exception {
		String sql = "select a.* from kube_deployment a where a.is_deleted = 0 and a.id = :id";
		Map<String, Object> param = MapTools.simpleMap(Common.ID, id);
		List<KubeDeployment> list = this.list(KubeDeployment.class, sql, param);
		if (list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

	public boolean removeByVendor(Long vendorId, Long userId) throws Exception {
		String sql = "update kube_deployment 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 List<KubeDeployment> listByVendor(Long vendorId) throws Exception {
		String sql = "select a.* from kube_deployment a where a.is_deleted = 0 and a.vendor_id = :vendorId";
		Map<String, Object> param = MapTools.simpleMap(Common.VENDORID, vendorId);
		List<KubeDeployment> list = this.list(KubeDeployment.class, sql, param);
		return list;
	}

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

	public List<KubeDeployment> list(int page, int rows, List<Param> params, Map<String, String> sorter,
			List<Long> projectIds) {
		String sql = "select a.*, t.`name` tenant_name, project.visibility project_visibility from kube_deployment a left join tenant t on a.tenant_id = t.id"
				+ " left join project project on a.project_id = project.id " + " where a.is_deleted = 0";
		Map<String, Object> paramMap = QueryBuilder.getParam(params);
		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(KubeDeployment.class, sql, paramMap);
	}

	public KubeDeployment getByName(String name, Long vendorId) {
		String sql = "select a.* from kube_deployment a where a.is_deleted = 0 and a.vendor_id = :vendorId and a.name = :name ";
		Map<String, Object> param = MapTools.simpleMap(Common.VENDORID, vendorId);
		param.put("name", name);
		List<KubeDeployment> list = this.list(KubeDeployment.class, sql, param);
		if (list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

	public List<KubeDeployment> listByNsId(Long nsId, Long vendorId, Long tenantId) {
		String sql = "select a.* from kube_deployment a where a.is_deleted = 0 and a.vendor_id = :vendorId and a.app_id = :appId ";
		Map<String, Object> param = MapTools.simpleMap(Common.VENDORID, vendorId);
		param.put("appId", nsId);
		if (null != tenantId && 0 != tenantId) {
			sql += " and a.tenant_id = :tenantId ";
			param.put("tenantId", tenantId);
		}
		return this.list(KubeDeployment.class, sql, param);
	}

	public int serviceCount(Long tenantId) {
		String sql = " select count(1) from ( select dep.* from kube_deployment dep where dep.is_deleted = 0 and dep.tenant_id = "
				+ tenantId
				+ " and dep.app_id  in  (select ns.id from kube_namespace ns where ns.is_deleted = 0 and ns.tenant_id = "
				+ tenantId
				+ ")  union all select dae.* from kube_daemonset dae where dae.is_deleted = 0 and dae.tenant_id = "
				+ tenantId
				+ " and dae.app_id in (select ns.id from kube_namespace ns where ns.is_deleted = 0 and ns.tenant_id = "
				+ tenantId + ") ) a  ";
		List<Param> params = new ArrayList<>();
		sql = QueryBuilder.buildRaw(sql, params, null, "a");
		Map<String, Object> paramMap = QueryBuilder.getParam(params);
		return this.countQuery(sql, paramMap).intValue();
	}

	public List<KubeDeployment> serviceList(Integer page, Integer rows, List<Param> params, Map<String, String> sorter,
			Long tenantId) {
		String sql = "select dep.* from kube_deployment dep where dep.is_deleted = 0 and dep.tenant_id = "
				+ tenantId
				+ " and dep.app_id  in  (select ns.id from kube_namespace ns where ns.is_deleted = 0 and ns.tenant_id = "
				+ tenantId
				+ ")  union all select dae.* from kube_daemonset dae where dae.is_deleted = 0 and dae.tenant_id = "
				+ tenantId
				+ "  and dae.app_id in (select ns.id from kube_namespace ns where ns.is_deleted = 0 and ns.tenant_id = "
				+ tenantId + ") ";
		Map<String, Object> param = new HashMap<String, Object>();
		List<KubeDeployment> list = this.list(KubeDeployment.class, sql, param);
		return list;
	}

	public int count(Long tenantId, Long userId, List<Long> poolIds, List<Long> vdcIds) {
		String sql = " select count(1) from ( select dep.* from kube_deployment dep where dep.is_deleted = 0 and dep.tenant_id = "
				+ tenantId
				+ " and dep.app_id  in  (select ns.id from kube_namespace ns where ns.is_deleted = 0 and ns.tenant_id = "
				+ tenantId + ")  ";
		if (null != tenantId && 0L != tenantId) {
			if (!ListTool.isEmpty(poolIds) && !ListTool.isEmpty(vdcIds)) {
				sql += "  and dep.vdc_id in (" + generateIds(vdcIds) + ")  and dep.poolgroup_id in ("
						+ generateIds(poolIds) + ")  ";
			}
		}
		sql += " union all select dae.* from kube_daemonset dae where dae.is_deleted = 0 and dae.tenant_id = "
				+ tenantId
				+ " and dae.app_id in (select ns.id from kube_namespace ns where ns.is_deleted = 0 and ns.tenant_id = "
				+ tenantId + ") ";
		if (null != tenantId && 0L != tenantId) {
			if (!ListTool.isEmpty(poolIds) && !ListTool.isEmpty(vdcIds)) {
				sql += "  and dae.vdc_id in (" + generateIds(vdcIds) + ")  and dae.poolgroup_id in ("
						+ generateIds(poolIds) + ") ";
			}
		}
		sql += " ) a  ";
		List<Param> params = new ArrayList<>();
		sql = QueryBuilder.buildRaw(sql, params, null, "a");
		Map<String, Object> paramMap = QueryBuilder.getParam(params);
		return this.countQuery(sql, paramMap).intValue();
	}

	public List<KubeDeployment> list(Integer page, Integer rows, List<Param> params, Map<String, String> sorter,
			Long tenantId, Long userId, List<Long> poolIds, List<Long> vdcIds) {
		String sql = "select dep.* from kube_deployment dep where dep.is_deleted = 0 and dep.tenant_id = "
				+ tenantId
				+ " and dep.app_id  in  (select ns.id from kube_namespace ns where ns.is_deleted = 0 and ns.tenant_id = "
				+ tenantId + ") ";
		if (null != tenantId && 0L != tenantId) {
			if (!ListTool.isEmpty(poolIds) && !ListTool.isEmpty(vdcIds)) {
				sql += "  and dep.vdc_id in (" + generateIds(vdcIds) + ")  and dep.poolgroup_id in ("
						+ generateIds(poolIds) + ")  ";
			}
		}
		sql += " union all select dae.* from kube_daemonset dae where dae.is_deleted = 0 and dae.tenant_id = "
				+ tenantId
				+ "  and dae.app_id in (select ns.id from kube_namespace ns where ns.is_deleted = 0 and ns.tenant_id = "
				+ tenantId + ") ";
		if (null != tenantId && 0L != tenantId) {
			if (!ListTool.isEmpty(poolIds) && !ListTool.isEmpty(vdcIds)) {
				sql += "  and dae.vdc_id in (" + generateIds(vdcIds) + ")  and dae.poolgroup_id in ("
						+ generateIds(poolIds) + ")  ";
			}
		}
		Map<String, Object> param = new HashMap<String, Object>();
		List<KubeDeployment> list = this.list(KubeDeployment.class, sql, param);
		return list;
	}

	private <T> String generateIds(List<T> ipPoolIds) {
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < ipPoolIds.size(); i++) {
			builder.append("'" + ipPoolIds.get(i) + "'").append(",");
		}
		builder.append(" -1 ");
		return builder.toString();
	}

}
