package com.ejie.ad74a.dao;

import com.ejie.x38.dao.RowNumResultSetExtractor;
import com.ejie.x38.dto.JerarquiaDto;
import com.ejie.x38.dto.TableManager;
import com.ejie.x38.dto.TableManagerJerarquia;
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.dao.support.DataAccessUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ejie.ad74a.model.Direcciones;
import com.ejie.ad74a.model.Protocolos;
import com.ejie.ad74a.model.Solicitantes;
import com.ejie.ad74a.model.comun.Municipio;
import com.ejie.ad74a.model.comun.Provincia;
import com.ejie.ad74a.util.UtilSQL;

/**
 * ProtocolosDaoImpl generated by UDA, 28-jun-2023 17:11:00.
 * 
 * @author UDA
 */

@Repository
@Transactional
public class ProtocolosDaoImpl implements ProtocolosDao {

	public static final String[] ORDER_BY_WHITE_LIST = new String[] { "IDPROTOCOLO26", "IDTIPOPROTOCOLO26",
			"FENTRADA26", "FSALIDA26", "FALTA26", "USUALTA26", "IDSOLICITANTE26", "IDENTIFICADOR01", "NOMBRE01",
			"APELLIDO101", "APELLIDO201", "DSCPROV", "DSOMUN" };

	private JdbcTemplate jdbcTemplate;

	public static final String SEQUENCE_PROTOCOLO = "SEQ_PROTOCOLOS";

	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<Protocolos> rwMap = new RowMapper<Protocolos>() {
		public Protocolos mapRow(ResultSet resultSet, int rowNum) throws SQLException {
			Protocolos protocolos = new Protocolos(UtilSQL.getLong(resultSet, "IDPROTOCOLO26"),
					UtilSQL.getInt(resultSet, "IDTIPOPROTOCOLO26"), UtilSQL.getLong(resultSet, "IDSOLICITANTE26"),
					resultSet.getDate("FENTRADA26"), resultSet.getDate("FSALIDA26"), resultSet.getDate("FALTA26"),
					resultSet.getString("USUALTA26"));

			Solicitantes solicitante = new Solicitantes();
			solicitante.setNombre01(resultSet.getString("NOMBRE01"));
			solicitante.setApellido101(resultSet.getString("APELLIDO101"));
			solicitante.setApellido201(resultSet.getString("APELLIDO201"));
			solicitante.setIdentificador01(resultSet.getString("IDENTIFICADOR01"));
			Direcciones dir = new Direcciones();
			dir.setProvinciaNORA(new Provincia(resultSet.getString("IDPROVINCIA"), resultSet.getString("DSCPROV"),
					resultSet.getString("DSEPROV"), resultSet.getString("AUTONOMIAID")));
			dir.setMunicipioNORA(new Municipio(resultSet.getString("IDMUNICIPIO"), resultSet.getString("DSOMUN"),
					resultSet.getString("IDPROVINCIA")));

			solicitante.setDirecciones(dir);
			protocolos.setSolicitante(solicitante);
			return protocolos;
		}
	};

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

	/**
	 * Rowmapper para Jerarquía
	 *
	 * @param dataSource DataSource
	 * @return
	 */
	private RowMapper<JerarquiaDto<Protocolos>> rwMapJerarquia = new RowMapper<JerarquiaDto<Protocolos>>() {
		public JerarquiaDto<Protocolos> mapRow(ResultSet resultSet, int rowNum) throws SQLException {

			Protocolos protocolos = new Protocolos(UtilSQL.getLong(resultSet, "IDPROTOCOLO26"),
					UtilSQL.getInt(resultSet, "IDTIPOPROTOCOLO26"), UtilSQL.getLong(resultSet, "IDSOLICITANTE26"),
					resultSet.getDate("FENTRADA26"), resultSet.getDate("FSALIDA26"), resultSet.getDate("FALTA26"),
					resultSet.getString("USUALTA26"));

			JerarquiaDto<Protocolos> jerarquia = new JerarquiaDto<Protocolos>();
			jerarquia.setModel(protocolos);
			jerarquia.setLevel(resultSet.getBigDecimal("LEVEL").intValue());
			jerarquia.setParentNodes(resultSet.getString("PARENTNODES"));
			jerarquia.setIsLeaf(Boolean.parseBoolean(resultSet.getString("ISLEAF")));
			jerarquia.setFilter(Boolean.parseBoolean(resultSet.getString("FILTER")));
			return jerarquia;
		}
	};

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

	/*
	 * OPERACIONES CRUD
	 */

	/**
	 * Inserts a single row in the Protocolos table.
	 *
	 * @param protocolos Protocolos
	 * @return Protocolos
	 */
	public Protocolos add(Protocolos protocolos) {
//		String query = "INSERT INTO PROTOCOLOS (ID_PROTOCOLO_26, ID_TIPO_PROTOCOLO_26, F_ENTRADA_26, F_SALIDA_26, F_ALTA_26, USU_ALTA_26) VALUES (?,?,?,?,?,?)";
//		this.jdbcTemplate.update(query, protocolos.getIdProtocolo26(), protocolos.getIdTipoProtocolo26(),
//				protocolos.getfEntrada26(), protocolos.getfSalida26(), protocolos.getfAlta26(),
//				protocolos.getUsuAlta26());
//		return protocolos;

		GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();

		String query = "INSERT INTO PROTOCOLOS (ID_PROTOCOLO_26, ID_TIPO_PROTOCOLO_26, ID_SOLICITANTE_26, F_ENTRADA_26, F_SALIDA_26, F_ALTA_26, USU_ALTA_26) "
				+ "VALUES (" + SEQUENCE_PROTOCOLO
				+ ".NEXTVAL,:idTipoProtocolo, :idSolicitante,:fEntrada,:fSalida,:fAlta,:usuAlta)";

		Object solicitantesAux = null;
		if (protocolos.getSolicitante() != null && protocolos.getSolicitante().getIdSolicitante01() != null) {
			solicitantesAux = protocolos.getSolicitante().getIdSolicitante01();
		}

		MapSqlParameterSource parameters = new MapSqlParameterSource()
				.addValue("idTipoProtocolo", protocolos.getIdTipoProtocolo26())
				.addValue("idSolicitante", solicitantesAux).addValue("fEntrada", protocolos.getfEntrada26())
				.addValue("fSalida", protocolos.getfSalida26()).addValue("fAlta", protocolos.getfAlta26())
				.addValue("usuAlta", protocolos.getUsuAlta26());

		NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
		namedParameterJdbcTemplate.update(query, parameters, generatedKeyHolder, new String[] { "ID_PROTOCOLO_26" });
		protocolos.setIdProtocolo26(generatedKeyHolder.getKey().longValue());

		return protocolos;
	}

	/**
	 * Updates a single row in the Protocolos table.
	 *
	 * @param protocolos Protocolos
	 * @return Protocolos
	 */
	public Protocolos update(Protocolos protocolos) {
		String query = "UPDATE PROTOCOLOS SET ID_TIPO_PROTOCOLO_26=?, F_ENTRADA_26=?, F_SALIDA_26=?, F_ALTA_26=?, USU_ALTA_26=? WHERE ID_PROTOCOLO_26=?";
		this.jdbcTemplate.update(query, protocolos.getIdTipoProtocolo26(), protocolos.getfEntrada26(),
				protocolos.getfSalida26(), protocolos.getfAlta26(), protocolos.getUsuAlta26(),
				protocolos.getIdProtocolo26());
		return protocolos;
	}

	/**
	 * Finds a single row in the Protocolos table.
	 *
	 * @param protocolos Protocolos
	 * @return Protocolos
	 */
	@Transactional(readOnly = true)
	public Protocolos find(Protocolos protocolos) {
		String query = "SELECT  t1.ID_PROTOCOLO_26 IDPROTOCOLO26,t1.ID_TIPO_PROTOCOLO_26 IDTIPOPROTOCOLO26,t1.ID_SOLICITANTE_26 IDSOLICITANTE26, "
				+ "t2.IDENTIFICADOR_01 IDENTIFICADOR01, t2.NOMBRE_01 NOMBRE01,t2.APELLIDO1_01 APELLIDO101, t2.APELLIDO2_01 APELLIDO201, "
				+ "t1.F_ENTRADA_26 FENTRADA26,t1.F_SALIDA_26 FSALIDA26,t1.F_ALTA_26 FALTA26,t1.USU_ALTA_26 USUALTA26  FROM PROTOCOLOS t1, SOLICITANTES t2  WHERE 1=1 AND t1.ID_SOLICITANTE_26 = t2.ID_SOLICITANTE_01 AND t1.ID_PROTOCOLO_26 = ?  ";

		List<Protocolos> protocolosList = this.jdbcTemplate.query(query, this.rwMap, protocolos.getIdProtocolo26());
		return (Protocolos) DataAccessUtils.uniqueResult(protocolosList);
	}

	/**
	 * Removes a single row in the Protocolos table.
	 *
	 * @param protocolos Protocolos
	 * @return
	 */
	public void remove(Protocolos protocolos) {
		String query = "DELETE FROM PROTOCOLOS WHERE ID_PROTOCOLO_26=?";
		this.jdbcTemplate.update(query, protocolos.getIdProtocolo26());
	}

	/**
	 * Exporta Datos al clipBoard
	 *
	 */
	public List<Protocolos> getMultiple(Protocolos filterProtocolos, TableRequestDto tableRequestDto,
			Boolean startsWith) {

		StringBuilder query = new StringBuilder(
				"SELECT  t1.ID_PROTOCOLO_26 IDPROTOCOLO26,t1.ID_TIPO_PROTOCOLO_26 IDTIPOPROTOCOLO26,t1.ID_SOLICITANTE_26 IDSOLICITANTE26, "
						+ " t2.IDENTIFICADOR_01 IDENTIFICADOR01, t2.NOMBRE_01 NOMBRE01,t2.APELLIDO1_01 APELLIDO101, t2.APELLIDO2_01 APELLIDO201, "
						+ " t1.F_ENTRADA_26 FENTRADA26,t1.F_SALIDA_26 FSALIDA26,t1.F_ALTA_26 FALTA26,t1.USU_ALTA_26 USUALTA26  ");
		query.append(" FROM PROTOCOLOS t1, SOLICITANTES t2 ");
		// Where clause & Params
		Map<String, Object> mapaWhere = this.getWhereLikeMap(filterProtocolos, startsWith);
		StringBuilder where = new StringBuilder(query + " WHERE 1=1 AND t1.ID_SOLICITANTE_26 = t2.ID_SOLICITANTE_01 ");
		where.append(mapaWhere.get("query"));

		@SuppressWarnings("unchecked")
		List<Object> params = (List<Object>) mapaWhere.get("params");

		StringBuilder sbMultipleSQL = TableManager.getSelectMultipleQuery(tableRequestDto, Protocolos.class, params,
				"ID_PROTOCOLO_26");
		where.append(sbMultipleSQL);

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

	/**
	 * Finds a list of rows in the Protocolos table.
	 *
	 * @param protocolos      Protocolos
	 * @param tableRequestDto TableRequestDto
	 * @return List<Protocolos>
	 */
	@Transactional(readOnly = true)
	public List<Protocolos> findAll(Protocolos protocolos, TableRequestDto tableRequestDto) {
		StringBuilder query = new StringBuilder(
				"SELECT  t1.ID_PROTOCOLO_26 IDPROTOCOLO26,t1.ID_TIPO_PROTOCOLO_26 IDTIPOPROTOCOLO26,t1.ID_SOLICITANTE_26 IDSOLICITANTE26, "
						+ " t2.IDENTIFICADOR_01 IDENTIFICADOR01, t2.NOMBRE_01 NOMBRE01,t2.APELLIDO1_01 APELLIDO101, t2.APELLIDO2_01 APELLIDO201, "
						+ " t1.F_ENTRADA_26 FENTRADA26,t1.F_SALIDA_26 FSALIDA26,t1.F_ALTA_26 FALTA26,t1.USU_ALTA_26 USUALTA26   ");
		query.append(" FROM PROTOCOLOS t1, SOLICITANTES t2 ");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(protocolos);
		StringBuilder where = new StringBuilder(" WHERE 1=1 AND t1.ID_SOLICITANTE_26 = t2.ID_SOLICITANTE_01 ");
		where.append(mapaWhere.get("query"));
		query.append(where);

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

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

		return (List<Protocolos>) this.jdbcTemplate.query(query.toString(), this.rwMap, params.toArray());
	}

	/**
	 * Finds rows in the Protocolos table using like.
	 *
	 * @param protocolos      Protocolos
	 * @param tableRequestDto TableRequestDto
	 * @param startsWith      Boolean
	 * @return List<Protocolos>
	 */
	@Transactional(readOnly = true)
	public List<Protocolos> findAllLike(Protocolos protocolos, TableRequestDto tableRequestDto, Boolean startsWith) {
		StringBuilder query = new StringBuilder(
				"SELECT  t1.ID_PROTOCOLO_26 IDPROTOCOLO26,t1.ID_TIPO_PROTOCOLO_26 IDTIPOPROTOCOLO26,t1.ID_SOLICITANTE_26 IDSOLICITANTE26, "
						+ " t2.IDENTIFICADOR_01 IDENTIFICADOR01, t2.NOMBRE_01 NOMBRE01,t2.APELLIDO1_01 APELLIDO101, t2.APELLIDO2_01 APELLIDO201, "
						+ " t1.F_ENTRADA_26 FENTRADA26,t1.F_SALIDA_26 FSALIDA26,t1.F_ALTA_26 FALTA26,t1.USU_ALTA_26 USUALTA26, t5.id_localidad_06, t7.ID IDPROVINCIA, t7.AUTONOMIA_ID AUTONOMIAID, t7.ds_c DSCPROV,t7.ds_e DSEPROV, t7.ds_o DSPROV, t6.ID IDMUNICIPIO, t6.DS_O DSOMUN  ");
		query.append("FROM PROTOCOLOS t1, SOLICITANTES t2, direcciones t5, T17_MUNICIPIO t6, T17_PROVINCIA t7");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(protocolos, startsWith);
		StringBuilder where = new StringBuilder(
				" WHERE 1=1 AND t1.ID_SOLICITANTE_26 = t2.ID_SOLICITANTE_01 AND t2.id_direccion_01=t5.id_direccion_06 AND t7.id=t5.id_provincia_06 AND t6.provincia_id=t5.id_provincia_06 AND t6.id = t5.id_municipio_06");
		where.append(mapaWhere.get("query"));
		query.append(where);

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

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

		return (List<Protocolos>) this.jdbcTemplate.query(query.toString(), this.rwMap, params.toArray());
	}

	/*
	 * OPERACIONES RUP_TABLE
	 */

	/**
	 * Counts rows in the Protocolos table.
	 *
	 * @param protocolos Protocolos
	 * @return Long
	 */
	@Transactional(readOnly = true)
	public Long findAllCount(Protocolos protocolos) {
		StringBuilder query = new StringBuilder("SELECT COUNT(1) FROM PROTOCOLOS t1, SOLICITANTES t2 ");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereMap(protocolos);
		StringBuilder where = new StringBuilder(" WHERE 1=1 AND t1.ID_SOLICITANTE_26 = t2.ID_SOLICITANTE_01 ");
		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 Protocolos table using like.
	 *
	 * @param protocolos Protocolos
	 * @param startsWith Boolean
	 * @return Long
	 */
	@Transactional(readOnly = true)
	public Long findAllLikeCount(Protocolos protocolos, Boolean startsWith) {
		StringBuilder query = new StringBuilder(
				"SELECT COUNT(1) FROM PROTOCOLOS t1, SOLICITANTES t2, direcciones t5, T17_MUNICIPIO t6, T17_PROVINCIA t7 ");

		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(protocolos, startsWith);
		StringBuilder where = new StringBuilder(
				" WHERE 1=1 AND t1.ID_SOLICITANTE_26 = t2.ID_SOLICITANTE_01 AND t2.id_direccion_01=t5.id_direccion_06 AND t7.id=t5.id_provincia_06 AND t6.provincia_id=t5.id_provincia_06 AND t6.id = t5.id_municipio_06 ");
		where.append(mapaWhere.get("query"));
		query.append(where);

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

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

	/**
	 * Reorder the data list of Protocolos selected for rup_table
	 *
	 * @param protocolos      Protocolos
	 * @param tableRequestDto TableRequestDto
	 * @param startsWith      Boolean
	 * @return List<TableRowDto<Protocolos>>
	 */
	@Override
	public List<TableRowDto<Protocolos>> reorderSelection(Protocolos protocolos, TableRequestDto tableRequestDto,
			Boolean startsWith) {
		// SELECT
		StringBuilder query = new StringBuilder(
				"SELECT  t1.ID_PROTOCOLO_26 IDPROTOCOLO26,t1.ID_TIPO_PROTOCOLO_26 IDTIPOPROTOCOLO26,t1.ID_SOLICITANTE_26 IDSOLICITANTE26, "
						+ " t2.IDENTIFICADOR_01 IDENTIFICADOR01, t2.NOMBRE_01 NOMBRE01,t2.APELLIDO1_01 APELLIDO101, t2.APELLIDO2_01 APELLIDO201, "
						+ " t1.F_ENTRADA_26 FENTRADA26,t1.F_SALIDA_26 FSALIDA26,t1.F_ALTA_26 FALTA26,t1.USU_ALTA_26 USUALTA26   ");
		// FROM
		query.append("FROM PROTOCOLOS t1, SOLICITANTES t2 ");
		// FILTRADO
		// Where clause & Params
		Map<String, ?> mapaWhere = this.getWhereLikeMap(protocolos, startsWith);
		StringBuilder where = new StringBuilder(" WHERE 1=1 AND t1.ID_SOLICITANTE_26 = t2.ID_SOLICITANTE_01 ");
		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, Protocolos.class,
				filterParamList, "IDPROTOCOLO26");

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

	/**
	 * Search method for rup_table
	 *
	 * @param filterParams    Protocolos
	 * @param searchParams    Protocolos
	 * @param tableRequestDto TableRequestDto
	 * @param startsWith      Boolean
	 * @return List<TableRowDto<Protocolos>>
	 */
	@Override
	public List<TableRowDto<Protocolos>> search(Protocolos filterParams, Protocolos searchParams,
			TableRequestDto tableRequestDto, Boolean startsWith) {
		// SELECT
		StringBuilder query = new StringBuilder(
				"SELECT  t1.ID_PROTOCOLO_26 IDPROTOCOLO26,t1.ID_TIPO_PROTOCOLO_26 IDTIPOPROTOCOLO26,t1.ID_SOLICITANTE_26 IDSOLICITANTE26, "
						+ " t2.IDENTIFICADOR_01 IDENTIFICADOR01, t2.NOMBRE_01 NOMBRE01,t2.APELLIDO1_01 APELLIDO101, t2.APELLIDO2_01 APELLIDO201, "
						+ " t1.F_ENTRADA_26 FENTRADA26,t1.F_SALIDA_26 FSALIDA26,t1.F_ALTA_26 FALTA26,t1.USU_ALTA_26 USUALTA26  ");
		// FROM
		query.append("FROM PROTOCOLOS t1, SOLICITANTES t2 ");
		// TABLAS_ALIAS
		List<String> from_alias = new ArrayList<String>();
		from_alias.add(" t1 ");

		// FILTRADO
		Map<String, ?> mapaWhereFilter = this.getWhereLikeMap(filterParams, startsWith);
		StringBuilder where = new StringBuilder(" WHERE 1=1 AND t1.ID_SOLICITANTE_26 = t2.ID_SOLICITANTE_01 ");
		where.append(mapaWhereFilter.get("query"));
		query.append(where);
		// Filter params
		@SuppressWarnings("unchecked")
		List<Object> filterParamList = (List<Object>) mapaWhereFilter.get("params");

		// BUSQUEDA
		Map<String, Object> mapaWhereSearch = this.getWhereLikeMap(searchParams, startsWith);
		String searchSQL = ((StringBuilder) mapaWhereSearch.get("query")).toString();
		// Search params
		@SuppressWarnings("unchecked")
		List<Object> searchParamList = (List<Object>) mapaWhereSearch.get("params");

		// SQL
		StringBuilder sbReorderSelectionSQL = TableManager.getSearchQuery(query, tableRequestDto, Protocolos.class,
				filterParamList, searchSQL, searchParamList, from_alias, "IDPROTOCOLO26");

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

	/**
	 * Remove multiple method for rup_table
	 *
	 * @param tableRequestDto TableRequestDto
	 */
	@Override
	public void removeMultiple(TableRequestDto tableRequestDto) {
		StringBuilder sbRemoveMultipleSQL = TableManager.getRemoveMultipleQuery(tableRequestDto, Protocolos.class,
				"PROTOCOLOS", new String[] { "IDPROTOCOLO26" });

		List<String> params = tableRequestDto.getMultiselection().getSelectedIds();

		this.jdbcTemplate.update(sbRemoveMultipleSQL.toString(), params.toArray());
	}

	/**
	 * Filter in the hierarchical Protocolos table.
	 *
	 * @param filterProtocolos Protocolos
	 * @param tableRequestDto  TableRequestDto
	 * @return List<JerarquiaDto<Protocolos>>
	 */
	@Override
	public List<JerarquiaDto<Protocolos>> findAllLikeJerarquia(Protocolos filterProtocolos,
			TableRequestDto tableRequestDto) {
		// SELECT
		StringBuilder query = new StringBuilder(
				"SELECT t1.ID_PROTOCOLO_26 IDPROTOCOLO26,t1.ID_TIPO_PROTOCOLO_26 IDTIPOPROTOCOLO26,t1.ID_SOLICITANTE_26 IDSOLICITANTE26,t1.F_ENTRADA_26 FENTRADA26,t1.F_SALIDA_26 FSALIDA26,t1.F_ALTA_26 FALTA26,t1.USU_ALTA_26 USUALTA26 ");
		// FROM
		// StringBuilder from = new StringBuilder("FROM PROTOCOLOS t1 ");
		List<String> from = new ArrayList<String>();
		from.add("PROTOCOLOS");
		// TABLAS_ALIAS
		List<String> from_alias = new ArrayList<String>();
		from_alias.add(" t1 ");

		// JOINS TABLAS
		/*
		 * Ejemplo de como indicar joins entre las tablas de la query
		 */
		/*
		 * StringBuilder joins = new StringBuilder("");
		 * joins.append("AND T1.ID=T2.ID_T1");
		 */

		// CONDICIONES (negocio)
		/*
		 * Ejemplo de como incluir condiciones de negocio en la consulta de la jerarquía
		 */
		/*
		 * StringBuilder businessFilters = new StringBuilder(); List<Object>
		 * businessParams = new ArrayList<Object>();
		 * businessFilters.append("   AND t1.EJIE = ?  "); businessParams.add("1");
		 */

		// FILTRO
		Map<String, ?> mapaWhere = this.getWhereLikeMap(filterProtocolos, false);

		// JERARQUIA
		// Especificar la columna padre correspondiente en lugar de la generada por
		// defecto (ID_PADRE)
		query = TableManagerJerarquia.getQuery(tableRequestDto, query, mapaWhere, "IDPROTOCOLO26", "ID_PADRE", "NOMBRE",
				from, from_alias);

		/*
		 * Ejemplo de llamada en caso de indicar joins entre tablas y condiciones de
		 * negocio
		 */
//		query = TableManagerJerarquia.getQuery(tableRequestDto, query, mapaWhere, "ID", "ID_PADRE", "NOMBRE", from, from_alias, joins, businessFilters, businessParams);

		// PAGINACION
		if (tableRequestDto != null) {
			query = TableManagerJerarquia.getPaginationQuery(tableRequestDto, query,
					ProtocolosDaoImpl.ORDER_BY_WHITE_LIST);
		}

		List<?> params = (List<?>) mapaWhere.get("params");
		return this.jdbcTemplate.query(query.toString(), this.rwMapJerarquia, params.toArray());
	}

	/**
	 * Count rows in hierarchy
	 *
	 * @param filterProtocolos Protocolos
	 * @param tableRequestDto  TableRequestDto
	 * @return Long
	 */
	@Override
	public Long findAllLikeCountJerarquia(Protocolos filterProtocolos, TableRequestDto tableRequestDto) {
		// FROM
		// StringBuilder from = new StringBuilder("FROM PROTOCOLOS t1 ");
		List<String> from = new ArrayList<String>();
		from.add("PROTOCOLOS");

		// TABLAS_ALIAS
		List<String> from_alias = new ArrayList<String>();
		from_alias.add(" t1 ");

		// JOINS TABLAS
		/*
		 * Ejemplo de como indicar joins entre las tablas de la query
		 */
		/*
		 * StringBuilder joins = new StringBuilder("");
		 * joins.append("AND T1.ID=T2.ID_T1");
		 */

		// CONDICIONES (negocio)
		/*
		 * Ejemplo de como incluir condiciones de negocio en la consulta de la jerarquía
		 */
		/*
		 * StringBuilder businessFilters = new StringBuilder(); List<Object>
		 * businessParams = new ArrayList<Object>();
		 * businessFilters.append("   AND t1.EJIE = ?  "); businessParams.add("1");
		 */

		// FILTRO
		Map<String, ?> mapaWhere = this.getWhereLikeMap(filterProtocolos, false);

		// JERARQUIA
		// Especificar la columna padre correspondiente en lugar de la generada por
		// defecto (ID_PADRE)
		StringBuilder query = TableManagerJerarquia.getQueryCount(tableRequestDto, mapaWhere, "IDPROTOCOLO26",
				"ID_PADRE", from, from_alias);

		/*
		 * Ejemplo de llamada en caso de indicar joins entre tablas y condiciones de
		 * negocio
		 */
//		StringBuilder query = TableManagerJerarquia.getQueryCount(tableRequestDto, mapaWhere, "ID", "ID_PADRE", from, from_alias, joins, businessFilters, businessParams);

		List<?> params = (List<?>) mapaWhere.get("params");
		return this.jdbcTemplate.queryForObject(query.toString(), params.toArray(), Long.class);
	}

	/**
	 * Find dependent hierarchical rows
	 *
	 * @param filterProtocolos Protocolos
	 * @param tableRequestDto  TableRequestDto
	 * @return List<TableRowDto<Protocolos>>
	 */
	@Override
	public List<TableRowDto<Protocolos>> findAllChild(Protocolos filterProtocolos, TableRequestDto tableRequestDto) {

		// FROM
		// StringBuilder from = new StringBuilder("FROM PROTOCOLOS t1 ");
		List<String> from = new ArrayList<String>();
		from.add("PROTOCOLOS");

		// TABLAS_ALIAS
		List<String> from_alias = new ArrayList<String>();
		from_alias.add(" t1 ");

		// JOINS TABLAS
		/*
		 * Ejemplo de como indicar joins entre las tablas de la query
		 */
		/*
		 * StringBuilder joins = new StringBuilder("");
		 * joins.append("AND T1.ID=T2.ID_T1");
		 */

		// CONDICIONES (negocio)
		/*
		 * Ejemplo de como incluir condiciones de negocio en la consulta de la jerarquía
		 */
		/*
		 * StringBuilder businessFilters = new StringBuilder(); List<Object>
		 * businessParams = new ArrayList<Object>();
		 * businessFilters.append("   AND t1.EJIE = ?  "); businessParams.add("1");
		 */

		// FILTRO
		Map<String, ?> mapaWhere = this.getWhereLikeMap(filterProtocolos, false);

		// MULTISELECCION
		// Especificar la columna padre correspondiente en lugar de la generada por
		// defecto (ID_PADRE)
		StringBuilder query = TableManagerJerarquia.getQueryChildren(tableRequestDto, mapaWhere, "IDPROTOCOLO26",
				"ID_PADRE", from, from_alias);

		/*
		 * Ejemplo de llamada en caso de indicar joins entre tablas y condiciones de
		 * negocio
		 */
//		StringBuilder query = TableManagerJerarquia.getQueryChildren(tableRequestDto, mapaWhere, "ID", "ID_PADRE", from, from_alias, joins, businessFilters, businessParams);

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

		return this.jdbcTemplate.query(query.toString(),
				new RowNumResultSetExtractor<Protocolos>(this.rwMapPK, "IDPROTOCOLO26"), params.toArray());
	}

	/*
	 * MÉTODOS PRIVADOS
	 */

	/**
	 * Returns a map with the needed value to create the conditions to filter by the
	 * Protocolos entity
	 *
	 * @param protocolos Protocolos 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.
	 */
	// CHECKSTYLE:OFF CyclomaticComplexity - Generación de código de UDA
	private Map<String, ?> getWhereMap(Protocolos protocolos) {

		StringBuilder where = new StringBuilder(ProtocolosDaoImpl.STRING_BUILDER_INIT);
		List<Object> params = new ArrayList<Object>();

		if (protocolos != null && protocolos.getIdProtocolo26() != null) {
			where.append(" AND t1.ID_PROTOCOLO_26 = ?");
			params.add(protocolos.getIdProtocolo26());
		}
		if (protocolos != null && protocolos.getIdTipoProtocolo26() != null) {
			where.append(" AND t1.ID_TIPO_PROTOCOLO_26 = ?");
			params.add(protocolos.getIdTipoProtocolo26());
		}
		if (protocolos != null && protocolos.getfEntrada26() != null) {
			where.append(" AND t1.F_ENTRADA_26 = ?");
			params.add(protocolos.getfEntrada26());
		}
		if (protocolos != null && protocolos.getfSalida26() != null) {
			where.append(" AND t1.F_SALIDA_26 = ?");
			params.add(protocolos.getfSalida26());
		}
		if (protocolos != null && protocolos.getfAlta26() != null) {
			where.append(" AND t1.F_ALTA_26 = ?");
			params.add(protocolos.getfAlta26());
		}
		if (protocolos != null && protocolos.getUsuAlta26() != null) {
			where.append(" AND t1.USU_ALTA_26 = ?");
			params.add(protocolos.getUsuAlta26());
		}

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

		return mapWhere;
	}
	// CHECKSTYLE:ON CyclomaticComplexity - Generación de código de UDA

	/**
	 * Returns a map with the needed value to create the conditions to filter by the
	 * Protocolos entity
	 *
	 * @param protocolos Protocolos 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.
	 */
	// CHECKSTYLE:OFF CyclomaticComplexity - Generación de código de UDA
	private Map<String, Object> getWhereLikeMap(Protocolos protocolos, Boolean startsWith) {

		StringBuilder where = new StringBuilder(ProtocolosDaoImpl.STRING_BUILDER_INIT);
		List<Object> params = new ArrayList<Object>();

		if (protocolos != null && protocolos.getIdProtocolo26() != null) {
			where.append(" AND t1.ID_PROTOCOLO_26 = ?");
			params.add(protocolos.getIdProtocolo26());
		}
		if (protocolos != null && protocolos.getIdSolicitante26() != null) {
			where.append(" AND t1.ID_SOLICITANTE_26 = ?");
			params.add(protocolos.getIdSolicitante26());
		}
		if (protocolos != null && protocolos.getSolicitante() != null
				&& protocolos.getSolicitante().getIdentificador01() != null) {
			where.append(" AND t2.IDENTIFICADOR_01 LIKE ?");
			params.add(protocolos.getSolicitante().getIdentificador01());
		}
		if (protocolos != null && protocolos.getSolicitante() != null
				&& protocolos.getSolicitante().getNombre01() != null) {
			where.append(" AND UPPER(t2.NOMBRE_01) LIKE ? ESCAPE  '\\'");
			params.add("%" + protocolos.getSolicitante().getNombre01().toUpperCase() + "%");
		}
		if (protocolos != null && protocolos.getSolicitante() != null
				&& protocolos.getSolicitante().getApellido101() != null) {
			where.append(" AND UPPER(t2.APELLIDO1_01) LIKE ? ESCAPE  '\\'");
			params.add("%" + protocolos.getSolicitante().getApellido101().toUpperCase() + "%");
		}
		if (protocolos != null && protocolos.getSolicitante() != null
				&& protocolos.getSolicitante().getApellido201() != null) {
			where.append(" AND UPPER(t2.APELLIDO2_01) LIKE ? ESCAPE  '\\'");
			params.add("%" + protocolos.getSolicitante().getApellido201().toUpperCase() + "%");
		}
		if (protocolos != null && protocolos.getIdTipoProtocolo26() != null) {
			where.append(" AND t1.ID_TIPO_PROTOCOLO_26 = ?");
			params.add(protocolos.getIdTipoProtocolo26());
		}
		if (protocolos != null && protocolos.getfEntrada26() != null) {
			where.append(" AND t1.F_ENTRADA_26 = ?");
			params.add(protocolos.getfEntrada26());
		}
		if (protocolos != null && protocolos.getfSalida26() != null) {
			where.append(" AND t1.F_SALIDA_26 = ?");
			params.add(protocolos.getfSalida26());
		}
		if (protocolos != null && protocolos.getfAlta26() != null) {
			where.append(" AND t1.F_ALTA_26 = ?");
			params.add(protocolos.getfAlta26());
		}

		if (protocolos != null && protocolos.getfEntradaDesde() != null) {
			where.append(" AND t1.F_ENTRADA_26 >= ?");
			params.add(protocolos.getfEntradaDesde());
		}
		if (protocolos != null && protocolos.getfEntradaHasta() != null) {
			where.append(" AND TRUNC(t1.f_entrada_26) <= ?");
			params.add(protocolos.getfEntradaHasta());
		}

		if (protocolos != null && protocolos.getfSalidaDesde() != null) {
			where.append(" AND t1.F_SALIDA_26 >= ?");
			params.add(protocolos.getfSalidaDesde());
		}
		if (protocolos != null && protocolos.getfSalidaHasta() != null) {
			where.append(" AND TRUNC(t1.f_salida_26) <= ?");
			params.add(protocolos.getfSalidaHasta());
		}
		if (protocolos != null && protocolos.getUsuAlta26() != null) {
			where.append(" AND UPPER(t1.USU_ALTA_26) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(protocolos.getUsuAlta26().toUpperCase() + "%");
			} else {
				params.add("%" + protocolos.getUsuAlta26().toUpperCase() + "%");
			}
			where.append(" AND t1.USU_ALTA_26 IS NOT NULL");
		}
		if (protocolos != null && protocolos.getDirecciones() != null
				&& protocolos.getDirecciones().getProvinciaNORA() != null
				&& protocolos.getDirecciones().getProvinciaNORA().getCodProvincia() != null) {
			where.append(" AND t7.ID = ?");
			params.add(protocolos.getDirecciones().getProvinciaNORA().getCodProvincia());
		}
		if (protocolos != null && protocolos.getDirecciones() != null
				&& protocolos.getDirecciones().getMunicipioNORA() != null
				&& protocolos.getDirecciones().getMunicipioNORA().getCodMunicipio() != null) {
			where.append(" AND t6.ID = ?");
			params.add(protocolos.getDirecciones().getMunicipioNORA().getCodMunicipio());
		}

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

		return mapWhere;
	}
	// CHECKSTYLE:ON CyclomaticComplexity - Generación de código de UDA

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