package com.ejie.ab04b.dao;

import com.ejie.x38.dao.RowNumResultSetExtractor;
import com.ejie.x38.dto.JQGridManager;
import com.ejie.x38.dto.JQGridRequestDto;
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.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.ejie.ab04b.model.RequerimientoAperturas;
import com.ejie.ab04b.model.TareaAperturas;

/**
 * Ab0458s00DaoImpl generated by UDA, 31-may-2017 9:30:50.
 * 
 * @author UDA
 */

@Repository
@Transactional
public class RequerimientoAperturasDaoImpl implements RequerimientoAperturasDao {

	private static final String QUERY_SELECT = "SELECT t1.ID_TAREA_058 IDTAREA058, t1.MOTIVO_058 MOTIVO058, t1.DESC_OTROS_ES_058 DESCOTROSES058, t1.DESC_OTROS_EU_058 DESCOTROSEU058 FROM AB0458S00 t1 ";

	private JdbcTemplate jdbcTemplate;

	/*
	 * ROW_MAPPERS
	 */
	private RowMapper<RequerimientoAperturas> rwMap = new RowMapper<RequerimientoAperturas>() {
		public RequerimientoAperturas mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			return new RequerimientoAperturas(new TareaAperturas(
					resultSet.getLong("IDTAREA058")),
					resultSet.getString("MOTIVO058"),
					resultSet.getString("DESCOTROSES058"),
					resultSet.getString("DESCOTROSEU058"));
		}
	};

	private RowMapper<RequerimientoAperturas> rwMapPK = new RowMapper<RequerimientoAperturas>() {
		public RequerimientoAperturas mapRow(ResultSet resultSet, int rowNum)
				throws SQLException {
			return new RequerimientoAperturas(new TareaAperturas(
					resultSet.getLong("IDTAREA058")),
					resultSet.getString("MOTIVO058"));
		}
	};

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

	/*
	 * OPERACIONES CRUD
	 */

	/**
	 * Inserts a single row in the Ab0458s00 table.
	 * 
	 * ab0458s00 Ab0458s00 Ab0458s00
	 * 
	 * @param ab0458s00
	 *            the ab 0458 s 00
	 * @return the requerimiento aperturas
	 */
	public RequerimientoAperturas add(RequerimientoAperturas ab0458s00) {
		String query = "INSERT INTO AB0458S00 (ID_TAREA_058, MOTIVO_058, DESC_OTROS_ES_058, DESC_OTROS_EU_058) VALUES (?,?,?,?)";
		this.jdbcTemplate.update(query, ab0458s00.getTareaAperturas()
				.getIdTarea063(), ab0458s00.getMotivo058(), ab0458s00
				.getDescOtrosEs058(), ab0458s00.getDescOtrosEu058());
		return ab0458s00;
	}

	/**
	 * Updates a single row in the Ab0458s00 table.
	 * 
	 * ab0458s00 Ab0458s00 Ab0458s00
	 * 
	 * @param ab0458s00
	 *            the ab 0458 s 00
	 * @return the requerimiento aperturas
	 */
	public RequerimientoAperturas update(RequerimientoAperturas ab0458s00) {
		String query = "UPDATE AB0458S00 SET DESC_OTROS_ES_058=?, DESC_OTROS_EU_058=? WHERE ID_TAREA_058=? AND MOTIVO_058=?";
		this.jdbcTemplate.update(query, ab0458s00.getDescOtrosEs058(),
				ab0458s00.getDescOtrosEu058(), ab0458s00.getTareaAperturas()
						.getIdTarea063(), ab0458s00.getMotivo058());
		return ab0458s00;
	}

	/**
	 * Finds a single row in the Ab0458s00 table.
	 * 
	 * ab0458s00 Ab0458s00 Ab0458s00
	 * 
	 * @param ab0458s00
	 *            the ab 0458 s 00
	 * @return the requerimiento aperturas
	 */
	@Transactional(readOnly = true)
	public RequerimientoAperturas find(RequerimientoAperturas ab0458s00) {

		StringBuilder query = new StringBuilder(
				RequerimientoAperturasDaoImpl.QUERY_SELECT);
		query.append(" WHERE t1.ID_TAREA_058 = ?   AND t1.MOTIVO_058 = ? ");

		List<RequerimientoAperturas> ab0458s00List = this.jdbcTemplate.query(
				query.toString(), this.rwMap, ab0458s00.getTareaAperturas()
						.getIdTarea063(), ab0458s00.getMotivo058());

		return (RequerimientoAperturas) DataAccessUtils
				.uniqueResult(ab0458s00List);
	}

	/**
	 * Removes a single row in the Ab0458s00 table.
	 * 
	 * ab0458s00 Ab0458s00
	 * 
	 * @param ab0458s00
	 *            the ab 0458 s 00
	 */
	public void remove(RequerimientoAperturas ab0458s00) {
		String query = "DELETE FROM AB0458S00 WHERE ID_TAREA_058=? AND MOTIVO_058=?";
		this.jdbcTemplate.update(query, ab0458s00.getTareaAperturas()
				.getIdTarea063(), ab0458s00.getMotivo058());
	}

	/**
	 * removePorTarea
	 * 
	 * @param idTarea
	 *            Long
	 */
	@Override
	public void removePorTarea(Long idTarea) {
		String query = "DELETE FROM AB0458S00 WHERE ID_TAREA_058=?";
		this.jdbcTemplate.update(query, idTarea);
	}

	/**
	 * Finds a list of rows in the Ab0458s00 table.
	 * 
	 * ab0458s00 Ab0458s00 jqGridRequestDto JQGridRequestDto List<Ab0458s00>
	 * 
	 * @param ab0458s00
	 *            the ab 0458 s 00
	 * @param jqGridRequestDto
	 *            the jq grid request dto
	 * @return the list
	 */
	@Transactional(readOnly = true)
	public List<RequerimientoAperturas> findAll(
			RequerimientoAperturas ab0458s00, JQGridRequestDto jqGridRequestDto) {

		StringBuilder query = new StringBuilder(
				RequerimientoAperturasDaoImpl.QUERY_SELECT);

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

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

		if (jqGridRequestDto != null) {
			query = JQGridManager.getPaginationQuery(jqGridRequestDto, query);
		}

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

	/**
	 * Finds rows in the Ab0458s00 table using like.
	 * 
	 * ab0458s00 Ab0458s00 jqGridRequestDto JQGridRequestDto startsWith Boolean
	 * List<Ab0458s00>
	 * 
	 * @param ab0458s00
	 *            the ab 0458 s 00
	 * @param jqGridRequestDto
	 *            the jq grid request dto
	 * @param startsWith
	 *            the starts with
	 * @return the list
	 */
	@Transactional(readOnly = true)
	public List<RequerimientoAperturas> findAllLike(
			RequerimientoAperturas ab0458s00,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {

		StringBuilder query = new StringBuilder(
				RequerimientoAperturasDaoImpl.QUERY_SELECT);

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

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

		if (jqGridRequestDto != null) {
			query = JQGridManager.getPaginationQuery(jqGridRequestDto, query);
		}

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

	/*
	 * OPERACIONES RUP_TABLE
	 */

	/**
	 * Counts rows in the Ab0458s00 table.
	 * 
	 * ab0458s00 Ab0458s00 Long
	 * 
	 * @param ab0458s00
	 *            the ab 0458 s 00
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long findAllCount(RequerimientoAperturas ab0458s00) {
		StringBuilder query = new StringBuilder(
				"SELECT COUNT(1) FROM AB0458S00 t1 ");

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

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

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

	/**
	 * Counts rows in the Ab0458s00 table using like.
	 * 
	 * ab0458s00 Ab0458s00 startsWith Boolean Long
	 * 
	 * @param ab0458s00
	 *            the ab 0458 s 00
	 * @param startsWith
	 *            the starts with
	 * @return the long
	 */
	@Transactional(readOnly = true)
	public Long findAllLikeCount(RequerimientoAperturas ab0458s00,
			Boolean startsWith) {
		StringBuilder query = new StringBuilder(
				"SELECT COUNT(1) FROM AB0458S00 t1 ");

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

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

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

	/**
	 * Reorder the data list of Ab0458s00 selected for rup_table.
	 * 
	 * ab0458s00 Ab0458s00 jqGridRequestDto JQGridRequestDto startsWith Boolean
	 * List<TableRowDto<Ab0458s00>>
	 * 
	 * @param ab0458s00
	 *            the ab 0458 s 00
	 * @param jqGridRequestDto
	 *            the jq grid request dto
	 * @param startsWith
	 *            the starts with
	 * @return the list
	 */
	@Override
	public List<TableRowDto<RequerimientoAperturas>> reorderSelection(
			RequerimientoAperturas ab0458s00,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {

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

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

		// SQL para la reordenación
		StringBuilder sbReorderSelectionSQL = JQGridManager.getReorderQuery(
				query, jqGridRequestDto, RequerimientoAperturas.class,
				filterParamList, "ID_TAREA_058,MOTIVO_058");

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

	/**
	 * Search method for rup_table.
	 * 
	 * filterParams Ab0458s00 searchParams Ab0458s00 jqGridRequestDto
	 * JQGridRequestDto startsWith Boolean List<TableRowDto<Ab0458s00>>
	 * 
	 * @param filterParams
	 *            the filter params
	 * @param searchParams
	 *            the search params
	 * @param jqGridRequestDto
	 *            the jq grid request dto
	 * @param startsWith
	 *            the starts with
	 * @return the list
	 */
	@Override
	public List<TableRowDto<RequerimientoAperturas>> search(
			RequerimientoAperturas filterParams,
			RequerimientoAperturas searchParams,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {

		StringBuilder query = new StringBuilder(
				RequerimientoAperturasDaoImpl.QUERY_SELECT);
		// 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 ");
		where.append(mapaWhereFilter.get("query"));
		query.append(where);
		// Filter params
		@SuppressWarnings(value = "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(value = "unchecked")
		List<Object> searchParamList = (List<Object>) mapaWhereSearch
				.get("params");

		// SQL
		StringBuilder sbReorderSelectionSQL = JQGridManager.getSearchQuery(
				query, jqGridRequestDto, RequerimientoAperturas.class,
				filterParamList, searchSQL, searchParamList, from_alias,
				"ID_TAREA_058,MOTIVO_058");

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

	/**
	 * Remove multiple method for rup_table.
	 * 
	 * filterab0458s00 Ab0458s00 jqGridRequestDto JQGridRequestDto startsWith
	 * Boolean
	 * 
	 * @param filterab0458s00
	 *            the filterab 0458 s 00
	 * @param jqGridRequestDto
	 *            the jq grid request dto
	 * @param startsWith
	 *            the starts with
	 */
	@Override
	public void removeMultiple(RequerimientoAperturas filterab0458s00,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		// SELECT
		/** TODO: select por clave */
		StringBuilder query = new StringBuilder(
				"SELECT t1.ID_TAREA_058 IDTAREA058,t1.MOTIVO_058 MOTIVO058,t1.DESC_OTROS_058 DESCOTROS058 ");
		// FROM
		query.append("FROM AB0458S00 t1 ");

		// WHERE
		Map<String, Object> mapaWhere = this.getWhereLikeMap(filterab0458s00,
				startsWith);
		StringBuilder where = new StringBuilder(" WHERE 1=1 ");
		where.append(mapaWhere.get("query"));
		query.append(where);

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

		StringBuilder sbRemoveMultipleSQL = JQGridManager
				.getRemoveMultipleQuery(jqGridRequestDto,
						RequerimientoAperturas.class, query, params,
						"ID_TAREA_058,MOTIVO_058");
		this.jdbcTemplate.update(sbRemoveMultipleSQL.toString(),
				params.toArray());
	}

	/*
	 * MÉTODOS PRIVADOS
	 */

	/**
	 * Returns a map with the needed value to create the conditions to filter by
	 * the Ab0458s00 entity .
	 * 
	 * ab0458s00 Ab0458s00 Bean with the criteria values to filter by. 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.
	 * 
	 * @param ab0458s00
	 *            the ab 0458 s 00
	 * @return the where map
	 */
	// CHECKSTYLE:OFF CyclomaticComplexity - Generación de código de UDA
	private Map<String, ?> getWhereMap(RequerimientoAperturas ab0458s00) {

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

		if (ab0458s00 != null && ab0458s00.getTareaAperturas() != null
				&& ab0458s00.getTareaAperturas().getIdTarea063() != null) {
			where.append(" AND t1.ID_TAREA_058 = ?");
			params.add(ab0458s00.getTareaAperturas().getIdTarea063());
		}
		if (ab0458s00 != null && ab0458s00.getMotivo058() != null) {
			where.append(" AND t1.MOTIVO_058 = ?");
			params.add(ab0458s00.getMotivo058());
		}
		if (ab0458s00 != null && ab0458s00.getDescOtrosEs058() != null) {
			where.append(" AND t1.DESC_OTROS_ES_058 = ?");
			params.add(ab0458s00.getDescOtrosEs058());
		}
		if (ab0458s00 != null && ab0458s00.getDescOtrosEu058() != null) {
			where.append(" AND t1.DESC_OTROS_EU_058 = ?");
			params.add(ab0458s00.getDescOtrosEu058());
		}

		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 Ab0458s00 entity .
	 * 
	 * ab0458s00 Ab0458s00 Bean with the criteria values to filter by.
	 * startsWith Boolean 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.
	 * 
	 * @param ab0458s00
	 *            the ab 0458 s 00
	 * @param startsWith
	 *            the starts with
	 * @return the where like map
	 */
	// CHECKSTYLE:OFF CyclomaticComplexity - Generación de código de UDA
	private Map<String, Object> getWhereLikeMap(
			RequerimientoAperturas ab0458s00, Boolean startsWith) {

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

		if (ab0458s00 != null && ab0458s00.getTareaAperturas() != null
				&& ab0458s00.getTareaAperturas().getIdTarea063() != null) {
			where.append(" AND t1.ID_TAREA_058 = ?");
			params.add(ab0458s00.getTareaAperturas().getIdTarea063());
		}
		if (ab0458s00 != null && ab0458s00.getMotivo058() != null) {
			where.append(" AND UPPER(t1.MOTIVO_058) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0458s00.getMotivo058().toUpperCase() + "%");
			} else {
				params.add("%" + ab0458s00.getMotivo058().toUpperCase() + "%");
			}
			where.append(" AND t1.MOTIVO_058 IS NOT NULL");
		}
		if (ab0458s00 != null && ab0458s00.getDescOtrosEs058() != null) {
			where.append(" AND UPPER(t1.DESC_OTROS_ES_058) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0458s00.getDescOtrosEs058().toUpperCase() + "%");
			} else {
				params.add("%" + ab0458s00.getDescOtrosEs058().toUpperCase()
						+ "%");
			}
			where.append(" AND t1.DESC_OTROS_ES_058 IS NOT NULL");
		}
		if (ab0458s00 != null && ab0458s00.getDescOtrosEu058() != null) {
			where.append(" AND UPPER(t1.DESC_OTROS_EU_058) like ? ESCAPE  '\\'");
			if (startsWith) {
				params.add(ab0458s00.getDescOtrosEu058().toUpperCase() + "%");
			} else {
				params.add("%" + ab0458s00.getDescOtrosEu058().toUpperCase()
						+ "%");
			}
			where.append(" AND t1.DESC_OTROS_EU_058 IS NOT NULL");
		}

		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;

}
