/*
* Copyright 2021 E.J.I.E., S.A.
*
* Licencia con arreglo a la EUPL, Versión 1.1 exclusivamente (la «Licencia»);
* Solo podrá usarse esta obra si se respeta la Licencia.
* Puede obtenerse una copia de la Licencia en
*
* http://ec.europa.eu/idabc/eupl.html
*
* Salvo cuando lo exija la legislación aplicable o se acuerde por escrito,
* el programa distribuido con arreglo a la Licencia se distribuye «TAL CUAL»,
* SIN GARANT�?AS NI CONDICIONES DE NINGÚN TIPO, ni expresas ni implícitas.
* Véase la Licencia en el idioma concreto que rige los permisos y limitaciones
* que establece la Licencia.
*/
package com.ejie.ad74a.dao.ae01b;

import com.ejie.x38.dao.RowNumResultSetExtractor;
import com.ejie.x38.dto.TableManager;
import com.ejie.x38.dto.TableRequestDto;
import com.ejie.x38.dto.TableRowDto;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ejie.ad74a.dao.comun.UtilDAO;
import com.ejie.ad74a.model.ae01b.Cobros;
import com.ejie.ad74a.util.UtilSQL;

/**
 * CobrosDaoImpl generated by UDA, 28-jun-2023 10:59:26.
 * 
 * @author UDA
 */

@Repository
@Transactional
public class CobrosDaoImpl implements CobrosDao {

	/**
	 * StringBuilder initilization value
	 */
	public static final int STRING_BUILDER_INIT = 4096;

	protected static final String[] ORDER_BY_WHITE_LIST = new String[] { "IDLIQUIDACION", "NUMLIQUIDACION", "CONCEPTO",
			"FECEMISION", "IMPORTE", "ESTADO", "IDSOLICITANTE", "MOTANULACION", "REFERENCIA_LIQ_00", "MOTANULACIONES",
			"MOTANULACIONEU" };

	private JdbcTemplate jdbcTemplate;

	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<Cobros> rwMap = new RowMapper<Cobros>() {
		public Cobros mapRow(ResultSet resultSet, int rowNum) throws SQLException {
			Cobros cobros = new Cobros();
			cobros.setIdLiquidacion(UtilSQL.getLong(resultSet, "IDLIQUIDACION"));
			cobros.setNumLiquidacion(resultSet.getString("NUMLIQUIDACION"));
			cobros.setConcepto(resultSet.getString("CONCEPTO"));
			cobros.setFecEmision(resultSet.getDate("FECEMISION"));
			cobros.setImporte(resultSet.getBigDecimal("IMPORTE"));
			cobros.setEstado(UtilSQL.getLong(resultSet, "ESTADO"));
			cobros.setIdSolicitante(UtilSQL.getLong(resultSet, "IDSOLICITANTE"));
			cobros.setMotAnulacionEs(resultSet.getString("MOTANULACIONES"));
			cobros.setMotAnulacionEu(resultSet.getString("MOTANULACIONEU"));

			return cobros;
		}
	};

	private RowMapper<Cobros> rwMapPK = new RowMapper<Cobros>() {
		public Cobros mapRow(ResultSet resultSet, int rowNum) throws SQLException {
			return new Cobros(UtilSQL.getLong(resultSet, "IDLIQUIDACION"));
		}
	};

	/**
	 * Method use to set the datasource.
	 *
	 * @param dataSource DataSource
	 *
	 */
	@Resource
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	/*
	 * OPERACIONES CRUD
	 */

	/**
	 * Finds a list of rows in the Cobros table.
	 *
	 * @param cobros          Cobros
	 * @param tableRequestDto TableRequestDto
	 *
	 * @return List<Cobros>
	 */
	@Transactional(readOnly = true)
	public List<Cobros> findAll(Cobros cobros, TableRequestDto tableRequestDto) {
		// SELECT
		StringBuilder query = new StringBuilder(
				"SELECT t1.IDLIQUIDACION, t1.NUMLIQUIDACION, t1.CONCEPTO, t1.FECEMISION, t1.IMPORTE, t1.ESTADO, t1.IDSOLICITANTE, t1.MOTANULACION ");

		// FROM
		query.append(" FROM COBROS t1 ");

		// WHERE clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(cobros);
		StringBuilder where = new StringBuilder(" WHERE 1=1 ");
		where.append(mapaWhere.get("query"));
		query.append(where);

		List<?> params = (List<?>) mapaWhere.get("params");

		if (tableRequestDto != null) {
			query = TableManager.getPaginationQuery(tableRequestDto, query, CobrosDaoImpl.ORDER_BY_WHITE_LIST);
		}

		return this.jdbcTemplate.query(query.toString(), this.rwMap, params.toArray());
	}

	/**
	 * Finds rows in the Cobros table using like.
	 *
	 * @param cobros          Cobros
	 * @param tableRequestDto TableRequestDto
	 * @param startsWith      Boolean
	 *
	 * @return List<Cobros>
	 */
	@Transactional(readOnly = true)
	public List<Cobros> findAllLike(Cobros cobros, TableRequestDto tableRequestDto, Boolean startsWith) {
		// SELECT
		StringBuilder query = new StringBuilder(
				"SELECT DISTINCT t1.IDLIQUIDACION, t1.NUMLIQUIDACION, t1.CONCEPTO, t1.FECEMISION, t1.IMPORTE, t1.ESTADO, t1.IDSOLICITANTE, t1.MOTANULACIONES, t1.MOTANULACIONEU ");
		// FROM
		query.append(" FROM COBROS t1 ");

		// WHERE clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(cobros, startsWith);
		StringBuilder where = new StringBuilder(" WHERE 1=1 ");
		where.append(mapaWhere.get("query"));
		query.append(where);

		List<?> params = (List<?>) mapaWhere.get("params");

		if (tableRequestDto != null) {
			query = TableManager.getPaginationQuery(tableRequestDto, query, CobrosDaoImpl.ORDER_BY_WHITE_LIST);
		}

		return this.jdbcTemplate.query(query.toString(), this.rwMap, params.toArray());
	}

	/*
	 * OPERACIONES RUP_TABLE
	 */

	/**
	 * Counts rows in the Cobros table.
	 *
	 * @param cobros Cobros
	 *
	 * @return Long
	 */
	@Transactional(readOnly = true)
	public Long findAllCount(Cobros cobros) {
		// SELECT
		StringBuilder query = new StringBuilder("SELECT COUNT(1) FROM COBROS t1 ");

		// WHERE clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(cobros);
		StringBuilder where = new StringBuilder(" WHERE 1=1 ");
		where.append(mapaWhere.get("query"));
		query.append(where);

		List<?> params = (List<?>) mapaWhere.get("params");

		return this.jdbcTemplate.queryForObject(query.toString(), params.toArray(), Long.class);
	}

	/**
	 * Counts rows in the Cobros table using like.
	 *
	 * @param cobros     Cobros
	 * @param startsWith Boolean
	 *
	 * @return Long
	 */
	@Transactional(readOnly = true)
	public Long findAllLikeCount(Cobros cobros, Boolean startsWith) {
		// SELECT
		StringBuilder query = new StringBuilder(
				"SELECT COUNT(1) FROM (SELECT DISTINCT t1.IDLIQUIDACION, t1.NUMLIQUIDACION, t1.CONCEPTO, t1.FECEMISION, t1.IMPORTE, t1.ESTADO, t1.IDSOLICITANTE, t1.MOTANULACIONES, t1.MOTANULACIONEU FROM COBROS t1 ");

		// WHERE clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(cobros, startsWith);
		StringBuilder where = new StringBuilder(" WHERE 1=1 ");
		where.append(mapaWhere.get("query"));
		query.append(where);
		query.append(")");

		List<?> params = (List<?>) mapaWhere.get("params");

		return this.jdbcTemplate.queryForObject(query.toString(), params.toArray(), Long.class);
	}

	/**
	 * Reorder the data list of Cobros selected for rup_table
	 *
	 * @param cobros          Cobros
	 * @param tableRequestDto TableRequestDto
	 * @param startsWith      Boolean
	 *
	 * @return List<TableRowDto<Cobros>>
	 */
	@Override
	public List<TableRowDto<Cobros>> reorderSelection(Cobros cobros, TableRequestDto tableRequestDto,
			Boolean startsWith) {
		// SELECT
		StringBuilder query = new StringBuilder(
				"SELECT t1.IDLIQUIDACION, t1.NUMLIQUIDACION, t1.CONCEPTO, t1.FECEMISION, t1.IMPORTE, t1.ESTADO, t1.IDSOLICITANTE, t1.MOTANULACION ");

		// FROM
		query.append(" FROM COBROS t1 ");

		// FILTRADO
		// WHERE clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(cobros, startsWith);
		StringBuilder where = new StringBuilder(" WHERE 1=1 ");
		where.append(mapaWhere.get("query"));
		query.append(where);

		// Parámetros de filtrado
		@SuppressWarnings("unchecked")
		List<Object> filterParamList = (List<Object>) mapaWhere.get("params");

		// SQL para la reordenación
		StringBuilder sbReorderSelectionSQL = TableManager.getReorderQuery(query, tableRequestDto, Cobros.class,
				filterParamList, "IDLIQUIDACION");

		return this.jdbcTemplate.query(sbReorderSelectionSQL.toString(),
				new RowNumResultSetExtractor<Cobros>(this.rwMapPK, tableRequestDto), filterParamList.toArray());
	}

	/*
	 * MÉTODOS PRIVADOS
	 */

	/**
	 * Returns a map with the needed value to create the conditions to filter by the
	 * Cobros entity
	 *
	 * @param cobros Cobros Bean with the criteria values to filter by.
	 *
	 * @return Map created with two keys key query stores the sql query syntax key
	 *         params stores the parameter values to be used in the condition
	 *         sentence.
	 */
	private Map<String, ?> getWhereMap(Cobros cobros) {
		StringBuilder where = new StringBuilder(CobrosDaoImpl.STRING_BUILDER_INIT);
		List<Object> params = new ArrayList<Object>();

		if (cobros != null && cobros.getIdLiquidacion() != null) {
			where.append(" AND t1.IDLIQUIDACION = ?");
			params.add(cobros.getIdLiquidacion());
		}
		if (cobros != null && cobros.getNumLiquidacion() != null) {
			where.append(" AND t1.NUMLIQUIDACION = ?");
			params.add(cobros.getNumLiquidacion());
		}
		if (cobros != null && cobros.getConcepto() != null) {
			where.append(" AND t1.CONCEPTO = ?");
			params.add(cobros.getConcepto());
		}
		if (cobros != null && cobros.getFecEmision() != null) {
			where.append(" AND t1.FECEMISION = ?");
			params.add(cobros.getFecEmision());
		}
		if (cobros != null && cobros.getImporte() != null) {
			where.append(" AND t1.IMPORTE = ?");
			params.add(cobros.getImporte());
		}
		if (cobros != null && cobros.getEstado() != null) {
			where.append(" AND t1.ESTADOLIQ = ?");
			params.add(cobros.getEstado());
		}
		if (cobros != null && cobros.getIdSolicitante() != null) {
			where.append(" AND t1.IDSOLICITANTE = ?");
			params.add(cobros.getIdSolicitante());
		}
		if (cobros != null && cobros.getMotAnulacion() != null) {
			where.append(" AND t1.MOTANULACION = ?");
			params.add(cobros.getMotAnulacion());
		}
		if (cobros != null && cobros.getfEmisionDesde() != null) {
			where.append(" AND t1.FEMISION > ?");
			params.add(cobros.getfEmisionDesde());
		}
		if (cobros != null && cobros.getfEmisionHasta() != null) {
			where.append(" AND TRUNC(t1.FEMISION) <= ?");
			params.add(cobros.getfEmisionHasta());
		}

		Map<String, Object> mapWhere = new HashMap<String, Object>();
		mapWhere.put("query", where);
		mapWhere.put("params", params);

		return mapWhere;
	}

	/**
	 * Returns a map with the needed value to create the conditions to filter by the
	 * Cobros entity
	 *
	 * @param cobros     Cobros Bean with the criteria values to filter by.
	 * @param startsWith Boolean
	 *
	 * @return Map created with two keys key query stores the sql query syntax key
	 *         params stores the parameter values to be used in the condition
	 *         sentence.
	 */
	private Map<String, Object> getWhereLikeMap(Cobros cobros, Boolean startsWith) {
		StringBuilder where = new StringBuilder(CobrosDaoImpl.STRING_BUILDER_INIT);
		List<Object> params = new ArrayList<Object>();

		if (cobros != null && cobros.getIdLiquidacion() != null) {
			where.append(" AND t1.IDLIQUIDACION = ?");
			params.add(cobros.getIdLiquidacion());
		}
		if (cobros != null && cobros.getNumLiquidacion() != null) {
			where.append(" AND t1.NUMLIQUIDACION = ?");
			params.add(cobros.getNumLiquidacion());
		}
		if (cobros != null && cobros.getConcepto() != null) {
			where.append(" AND UPPER(t1.CONCEPTO) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(cobros.getConcepto().toUpperCase() + "%");
			} else {
				params.add("%" + cobros.getConcepto().toUpperCase() + "%");
			}
			where.append(" AND t1.CONCEPTO IS NOT NULL");
		}
		if (cobros != null && cobros.getFecEmision() != null) {
			where.append(" AND t1.FECEMISION = ?");
			params.add(cobros.getFecEmision());
		}
		if (cobros != null && cobros.getImporte() != null) {
			where.append(" AND t1.IMPORTE = ?");
			params.add(cobros.getImporte());
		}
		if (cobros != null && cobros.getEstado() != null) {
			where.append(" AND t1.ESTADO = ?");
			params.add(cobros.getEstado());
		}
		if (cobros != null && cobros.getIdSolicitante() != null) {
			where.append(" AND t1.IDSOLICITANTE = ?");
			params.add(cobros.getIdSolicitante());
		}
		if (cobros != null && cobros.getMotAnulacion() != null) {
			where.append(" AND UPPER(t1.MOTANULACION) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(cobros.getMotAnulacion().toUpperCase() + "%");
			} else {
				params.add("%" + cobros.getMotAnulacion().toUpperCase() + "%");
			}
			where.append(" AND t1.MOTANULACION IS NOT NULL");
		}
		if (cobros != null && cobros.getfEmisionDesde() != null) {
			where.append(" AND t1.FECEMISION >= ?");
			params.add(cobros.getfEmisionDesde());
		}
		if (cobros != null && cobros.getfEmisionHasta() != null) {
			where.append(" AND TRUNC(t1.FECEMISION) <= ?");
			params.add(cobros.getfEmisionHasta());
		}
		if (cobros != null && cobros.getUltimaLiquidacion() != null) {
			where.append(
					" and (IDLIQUIDACION = (SELECT MAX(tmax.idliquidacion) FROM cobros tmax WHERE tmax.idmensualidad = t1.idmensualidad ))");
		}

		Map<String, Object> mapWhere = new HashMap<String, Object>();
		mapWhere.put("query", where);
		mapWhere.put("params", params);

		return mapWhere;
	}
}
