package com.ejie.ad74a.dao;

import com.ejie.ad74a.model.DocumentosInfSocial;
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.math.BigDecimal;
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.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * DocumentosInfSocialDaoImpl generated by UDA, 06-nov-2024 13:24:02.
 * 
 * @author UDA
 */
@Repository
@Transactional
public class DocumentosInfSocialDaoImpl implements DocumentosInfSocialDao {

	public static final String[] ORDER_BY_WHITE_LIST = new String[] { "IDEXPEDIENTE00", "OIDDOKUSI18", "NOMBREDOC18",
			"FINFORME02", "SOLA02", "ESTASOLAMANANA02", "ESTASOLATARDE02", "ESTASOLANOCHE02", "RELACIONENTORNO02",
			"FAMILIARFALLECIDO02", "VINCULOFALLECIDO02", "VISITASFAMILIA02", "VISITASAMIGOS02", "FRECUENCIASALIDAS02",
			"PERIODOSINVISITAS02", "TIEMPOSINVISITAS02", "OBSERVACIONES02" };
	private JdbcTemplate jdbcTemplate;
	/*
	 * ROW_MAPPER
	 */
	private RowMapper<DocumentosInfSocial> rwMap = new DocumentosInfSocialRwMap();

	private static class DocumentosInfSocialRwMap implements RowMapper<DocumentosInfSocial> {
		@Override
		public DocumentosInfSocial mapRow(ResultSet resultSet, int rowNum) throws SQLException {
			DocumentosInfSocial documentosinfsocial = new DocumentosInfSocial();
			documentosinfsocial.setIdExpediente00(resultSet.getLong("IDEXPEDIENTE00"));
			documentosinfsocial.setOiddokusi18(resultSet.getString("OIDDOKUSI18"));
			documentosinfsocial.setNombreDoc18(resultSet.getString("NOMBREDOC18"));
			documentosinfsocial.setFInforme02(resultSet.getDate("FINFORME02"));
			documentosinfsocial.setSola02(resultSet.getInt("SOLA02"));
			documentosinfsocial.setEstaSolaManana02(resultSet.getInt("ESTASOLAMANANA02"));
			documentosinfsocial.setEstaSolaTarde02(resultSet.getInt("ESTASOLATARDE02"));
			documentosinfsocial.setEstaSolaNoche02(resultSet.getInt("ESTASOLANOCHE02"));
			documentosinfsocial.setRelacionEntorno02(resultSet.getInt("RELACIONENTORNO02"));
			documentosinfsocial.setFamiliarFallecido02(resultSet.getInt("FAMILIARFALLECIDO02"));
			documentosinfsocial.setVinculoFallecido02(resultSet.getString("VINCULOFALLECIDO02"));
			documentosinfsocial.setVisitasFamilia02(resultSet.getInt("VISITASFAMILIA02"));
			documentosinfsocial.setVisitasAmigos02(resultSet.getInt("VISITASAMIGOS02"));
			documentosinfsocial.setFrecuenciaSalidas02(resultSet.getInt("FRECUENCIASALIDAS02"));
			documentosinfsocial.setPeriodoSinVisitas02(resultSet.getInt("PERIODOSINVISITAS02"));
			documentosinfsocial.setTiempoSinVisitas02(resultSet.getInt("TIEMPOSINVISITAS02"));
			documentosinfsocial.setObservaciones02(resultSet.getString("OBSERVACIONES02"));

			return documentosinfsocial;
		}
	}

	private RowMapper<DocumentosInfSocial> rwMapPK = new RowMapper<DocumentosInfSocial>() {
		public DocumentosInfSocial mapRow(ResultSet resultSet, int rowNum) throws SQLException {
			// El ID tabla/vista importante para el reorder con alguna row seleccionada
			DocumentosInfSocial documentosinfsocial = new DocumentosInfSocial();
			documentosinfsocial.setIdExpediente00(resultSet.getLong("IDEXPEDIENTE00"));
			return documentosinfsocial;
		}
	};

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

	/*
	 * OPERACIONES CRUD
	 */

	/**
	 * Finds a single row in the DocumentosInfSocial table.
	 *
	 * @param documentosinfsocial DocumentosInfSocial
	 * @return DocumentosInfSocial
	 */
	@Transactional(readOnly = true)
	public DocumentosInfSocial find(DocumentosInfSocial documentosinfsocial) {
		String query = DocumentosInfSocialDaoSql.SQL_FIND;
		List<DocumentosInfSocial> documentosinfsocialList = this.jdbcTemplate.query(query, this.rwMap,
				documentosinfsocial.getIdExpediente00());
		return DataAccessUtils.uniqueResult(documentosinfsocialList);
	}

	/**
	 * Finds rows in the DocumentosInfSocial table using like.
	 *
	 * @param documentosinfsocial DocumentosInfSocial
	 * @param TableRequestDto     TableRequestDto
	 * @return List<DocumentosInfSocial>
	 */
	@Transactional(readOnly = true)
	public List<DocumentosInfSocial> findAllLike(DocumentosInfSocial documentosinfsocial,
			TableRequestDto tableRequestDto) {

		StringBuilder query = new StringBuilder(DocumentosInfSocialDaoSql.SQL_FIND_ALL);
		List<Object> params = new ArrayList<Object>();

		// Where clause & Params
		query.append(DocumentosInfSocialDaoSql.SQL_WHERE_ALL);
		query.append(this.getWhere(documentosinfsocial, params));

		if (tableRequestDto != null) {
			query = TableManager.getPaginationQuery(tableRequestDto, query,
					DocumentosInfSocialDaoImpl.ORDER_BY_WHITE_LIST);
		}
		return this.jdbcTemplate.query(query.toString(), this.rwMap, params.toArray());
	}

	/**
	 * Counts rows in the DocumentosInfSocial table using like.
	 *
	 * @param documentosinfsocial DocumentosInfSocial
	 * @return Long
	 */
	@Transactional(readOnly = true)
	public Long findAllLikeCount(DocumentosInfSocial documentosinfsocial) {

		StringBuilder query = new StringBuilder(DocumentosInfSocialDaoSql.SQL_FIND_ALL_COUNT);
		List<Object> params = new ArrayList<Object>();

		// Where clause & Params
		query.append(DocumentosInfSocialDaoSql.SQL_WHERE_ALL);
		query.append(this.getWhere(documentosinfsocial, params));

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

	/**
	 * Reorder the data list of DocumentosInfSocial selected for rup_table
	 *
	 * @param documentosinfsocial DocumentosInfSocial
	 * @param tableRequestDto     TableRequestDto
	 * @return List<TableRowDto<DocumentosInfSocial>>
	 */
	@Override
	public List<TableRowDto<DocumentosInfSocial>> reorderSelection(DocumentosInfSocial documentosinfsocial,
			TableRequestDto tableRequestDto) {
		// SELECT
		StringBuilder query = new StringBuilder(DocumentosInfSocialDaoSql.SQL_FIND_ALL);
		List<Object> params = new ArrayList<Object>();

		// FILTRADO
		// Where clause & Params
		query.append(DocumentosInfSocialDaoSql.SQL_WHERE_ALL);
		query.append(this.getWhere(documentosinfsocial, params));

		// SQL para la reordenación
		StringBuilder sbReorderSelectionSQL = TableManager.getReorderQuery(query, tableRequestDto,
				DocumentosInfSocial.class, params, DocumentosInfSocialDaoSql.ALIAS_ID_TABLA);

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

	/**
	 * Search method for rup_table
	 *
	 * @param filterParams    DocumentosInfSocial
	 * @param searchParams    DocumentosInfSocial
	 * @param tableRequestDto TableRequestDto
	 * @param startsWith      Boolean
	 * @return List<TableRowDto<DocumentosInfSocial>>
	 */
	@Override
	public List<TableRowDto<DocumentosInfSocial>> search(DocumentosInfSocial filter, DocumentosInfSocial search,
			TableRequestDto tableRequestDto) {
		StringBuilder query = new StringBuilder(DocumentosInfSocialDaoSql.SQL_FIND_ALL);
		List<Object> params = new ArrayList<Object>();
		List<Object> searchParams = new ArrayList<Object>();

		// TABLAS_ALIAS
		List<String> fromAlias = new ArrayList<String>();
		fromAlias.add(DocumentosInfSocialDaoSql.ALIAS_DOCUMENTOSINFSOCIAL);

		// FILTRADO
		// Where clause & Params
		query.append(DocumentosInfSocialDaoSql.SQL_WHERE_ALL);
		query.append(this.getWhere(filter, params));

		// BUSQUEDA
		String searchSQL = this.getWhere(search, searchParams);

		// SQL
		StringBuilder sbReorderSelectionSQL = TableManager.getSearchQuery(query, tableRequestDto,
				DocumentosInfSocial.class, params, searchSQL, searchParams, fromAlias,
				DocumentosInfSocialDaoSql.ALIAS_ID_TABLA);

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

	/*
	 * MÉTODOS PRIVADOS
	 */

	/**
	 * Returns a map with the needed value to create the conditions to filter by the
	 * DocumentosInfSocial entity
	 *
	 * @param documentosinfsocial DocumentosInfSocial 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 String getWhere(DocumentosInfSocial documentosinfsocial, List<Object> params) {
		StringBuilder where = new StringBuilder(DocumentosInfSocialDaoImpl.STRING_BUILDER_INIT);

		if (documentosinfsocial != null) {
			where.append(UtilsSQL.generarWhereIgual(
					DocumentosInfSocialDaoSql.ALIAS_DOCUMENTOSINFSOCIAL + ".ID_EXPEDIENTE_00",
					documentosinfsocial.getIdExpediente00(), params));
			where.append(
					UtilsSQL.generarWhereLike(DocumentosInfSocialDaoSql.ALIAS_DOCUMENTOSINFSOCIAL + ".OIDDOKUSI_18",
							documentosinfsocial.getOiddokusi18(), params));
			where.append(
					UtilsSQL.generarWhereLike(DocumentosInfSocialDaoSql.ALIAS_DOCUMENTOSINFSOCIAL + ".NOMBRE_DOC_18",
							documentosinfsocial.getNombreDoc18(), params));
			where.append(
					UtilsSQL.generarWhereIgual(DocumentosInfSocialDaoSql.ALIAS_DOCUMENTOSINFSOCIAL + ".F_INFORME_02",
							documentosinfsocial.getFInforme02(), params));
			where.append(UtilsSQL.generarWhereIgual(DocumentosInfSocialDaoSql.ALIAS_DOCUMENTOSINFSOCIAL + ".SOLA_02",
					documentosinfsocial.getSola02(), params));
			where.append(UtilsSQL.generarWhereIgual(
					DocumentosInfSocialDaoSql.ALIAS_DOCUMENTOSINFSOCIAL + ".ESTA_SOLA_MANANA_02",
					documentosinfsocial.getEstaSolaManana02(), params));
			where.append(UtilsSQL.generarWhereIgual(
					DocumentosInfSocialDaoSql.ALIAS_DOCUMENTOSINFSOCIAL + ".ESTA_SOLA_TARDE_02",
					documentosinfsocial.getEstaSolaTarde02(), params));
			where.append(UtilsSQL.generarWhereIgual(
					DocumentosInfSocialDaoSql.ALIAS_DOCUMENTOSINFSOCIAL + ".ESTA_SOLA_NOCHE_02",
					documentosinfsocial.getEstaSolaNoche02(), params));
			where.append(UtilsSQL.generarWhereIgual(
					DocumentosInfSocialDaoSql.ALIAS_DOCUMENTOSINFSOCIAL + ".RELACION_ENTORNO_02",
					documentosinfsocial.getRelacionEntorno02(), params));
			where.append(UtilsSQL.generarWhereIgual(
					DocumentosInfSocialDaoSql.ALIAS_DOCUMENTOSINFSOCIAL + ".FAMILIAR_FALLECIDO_02",
					documentosinfsocial.getFamiliarFallecido02(), params));
			where.append(UtilsSQL.generarWhereLike(
					DocumentosInfSocialDaoSql.ALIAS_DOCUMENTOSINFSOCIAL + ".VINCULO_FALLECIDO_02",
					documentosinfsocial.getVinculoFallecido02(), params));
			where.append(UtilsSQL.generarWhereIgual(
					DocumentosInfSocialDaoSql.ALIAS_DOCUMENTOSINFSOCIAL + ".VISITAS_FAMILIA_02",
					documentosinfsocial.getVisitasFamilia02(), params));
			where.append(UtilsSQL.generarWhereIgual(
					DocumentosInfSocialDaoSql.ALIAS_DOCUMENTOSINFSOCIAL + ".VISITAS_AMIGOS_02",
					documentosinfsocial.getVisitasAmigos02(), params));
			where.append(UtilsSQL.generarWhereIgual(
					DocumentosInfSocialDaoSql.ALIAS_DOCUMENTOSINFSOCIAL + ".FRECUENCIA_SALIDAS_02",
					documentosinfsocial.getFrecuenciaSalidas02(), params));
			where.append(UtilsSQL.generarWhereIgual(
					DocumentosInfSocialDaoSql.ALIAS_DOCUMENTOSINFSOCIAL + ".PERIODO_SIN_VISITAS_02",
					documentosinfsocial.getPeriodoSinVisitas02(), params));
			where.append(UtilsSQL.generarWhereIgual(
					DocumentosInfSocialDaoSql.ALIAS_DOCUMENTOSINFSOCIAL + ".TIEMPO_SIN_VISITAS_02",
					documentosinfsocial.getTiempoSinVisitas02(), params));
			where.append(
					UtilsSQL.generarWhereLike(DocumentosInfSocialDaoSql.ALIAS_DOCUMENTOSINFSOCIAL + ".OBSERVACIONES_02",
							documentosinfsocial.getObservaciones02(), params));

			// Dentro de este if añadiremos los filtros añadidos en el
			// DocumentosInfSocialFilter
			// El DocumentosInfSocialFilter tiene que ser un extends de DocumentosInfSocial
			// El controller --> filter y en getExcel se sutituira DocumentosInfSocial por
			// DocumentosInfSocialFilter
			// Tambien en el Controller se añadira en el model donde se añade el
			// "documentosinfsocial" model.addAttribute( new DocumentosInfSocialFilter() ,
			// "documentosinfsocialFilter" )
			// Y por último se sustituira en el jsp del filter --> modelAttribute
			// "documentosinfsocialFilter"
			// if( documentosinfsocial instanceof DocumentosInfSocialFilter) {
			// DocumentosInfSocialFilter filter = ( DocumentosInfSocialFilter )
			// documentosinfsocial;
			//
			// }
		}

		return where.toString();
	}

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

	private static class UtilsSQL {
		public static String generarWhereIgual(String campo, Object valor, List<Object> params) {
			StringBuilder query = new StringBuilder(DocumentosInfSocialDaoImpl.STRING_BUILDER_INIT);
			if (null != valor) {
				query.append(" AND ").append(campo).append(" = ? ");
				params.add(valor);
			}

			return query.toString();
		}

		public static String generarWhereLike(String campo, String valor, List<Object> params) {
			StringBuilder query = new StringBuilder(DocumentosInfSocialDaoImpl.STRING_BUILDER_INIT);
			if (null != valor) {
				query.append(" AND UPPER(").append(campo).append(") LIKE ? ESCAPE  '\\'");
				params.add("%" + valor.toUpperCase() + "%");
				query.append(" AND ").append(campo).append(" IS NOT NULL ");
			}

			return query.toString();
		}
	}
}
