package com.dacrt.SBIABackend.controler;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.dacrt.SBIABackend.dto.BcpdrpparDto;
import com.dacrt.SBIABackend.dto.StateDto;
import com.dacrt.SBIABackend.dto.StatusDto;
import com.dacrt.SBIABackend.dto.StatusDto2;
import com.dacrt.SBIABackend.dto.TypeUnitDto;
import com.dacrt.SBIABackend.dto.TypesUnitDto;
import com.dacrt.SBIABackend.dto.ViceEntryDto;
import com.dacrt.SBIABackend.dto.VicepresResponseDto;
import com.dacrt.SBIABackend.dto.VicepresResponseDto2;
import com.dacrt.SBIABackend.dto.VicepresResponseDto3;
import com.dacrt.SBIABackend.dto.VicepresidenciesListDto;
import com.dacrt.SBIABackend.dto.VicepresidenciesResponseDto;
import com.dacrt.SBIABackend.dto.VicepresidenciesResponseDto2;
import com.dacrt.SBIABackend.dto.VicepresidenciesResponseDto3;
import com.dacrt.SBIABackend.dto.VicepresidencyDto;
import com.dacrt.SBIABackend.dto.WorkersDto;
import com.dacrt.SBIABackend.dto.requestDto.WorkersRequestBodyDto;
import com.dacrt.SBIABackend.dto.requestDto.WorkersRequestDto;
import com.dacrt.SBIABackend.dto.responseDto.VicepresidenciaResponseDto;
import com.dacrt.SBIABackend.dto.responseDto.VicepresidenciesEntryResponseDto;
import com.dacrt.SBIABackend.dto.responseDto.WorkerEntryResponseDto;
import com.dacrt.SBIABackend.entity.Positions;
import com.dacrt.SBIABackend.entity.Vicepresidencies;
import com.dacrt.SBIABackend.entity.Workers;
import com.dacrt.SBIABackend.repository.VicepresidenciesRepository;
import com.dacrt.SBIABackend.security.controler.PrivilegesController;
import com.dacrt.SBIABackend.security.dto.AuditRequestDto;
import com.dacrt.SBIABackend.security.dto.ParamsDto;
import com.dacrt.SBIABackend.security.dto.ParamsResponseDto;
import com.dacrt.SBIABackend.security.dto.PrivileResponseDto;
import com.dacrt.SBIABackend.security.dto.PrivilegeUniqueResponseDto;
import com.dacrt.SBIABackend.security.dto.PrivilegesAllDto;
import com.dacrt.SBIABackend.security.dto.PrivilegesDto;
import com.dacrt.SBIABackend.security.dto.PrivilegesListDto;
import com.dacrt.SBIABackend.security.dto.PrivilegesResponseDto;
import com.dacrt.SBIABackend.security.dto.RespuestaDto;
import com.dacrt.SBIABackend.security.dto.RespuestaMsgDto;
import com.dacrt.SBIABackend.security.dto.RespuestaValueDto;
import com.dacrt.SBIABackend.security.dto.RoleDto;
import com.dacrt.SBIABackend.security.dto.RolesAssignedResponseDto;
import com.dacrt.SBIABackend.security.entity.Params;
import com.dacrt.SBIABackend.security.entity.Privileges;
import com.dacrt.SBIABackend.security.entity.Roles;
import com.dacrt.SBIABackend.security.entity.Rolesprivileges;
import com.dacrt.SBIABackend.security.entity.Users;
import com.dacrt.SBIABackend.security.repository.AuditRepository;
import com.dacrt.SBIABackend.security.repository.ParamsRepository;
import com.dacrt.SBIABackend.security.repository.PrivilegesRepository;
import com.dacrt.SBIABackend.security.repository.RolesPrivilegesRepository;
import com.dacrt.SBIABackend.security.repository.RolesRepository;
import com.dacrt.SBIABackend.security.repository.UsersRepository;
import com.dacrt.SBIABackend.security.service.MenuService;
import com.dacrt.SBIABackend.security.service.SecurityService;
import com.dacrt.SBIABackend.security.service.UsersService;
import com.dacrt.SBIABackend.service.VicepresidenciesService;
import com.dacrt.SBIABackend.utils.HttpReqRespUtils;

@RestController
@CrossOrigin(origins = "*")
public class VicepresidenciesControler {
	@PersistenceContext
	private EntityManager entityManager;

	@Autowired
	private PrivilegesRepository privilegesRepository;

	@Autowired
	private ParamsRepository paramsRepository;

	@Autowired
	private AuditRepository auditRepository;

	@Autowired
	private UsersRepository usersRepository;

	@Autowired
	private RolesPrivilegesRepository rolesPrivilegesRepository;

	@Autowired
	private VicepresidenciesRepository vicepresidenciesRepository;

	@Autowired
	MenuService menuService;

	@Autowired
	VicepresidenciesService vicepresidenciesService;

	@Autowired
	SecurityService securityService;

	@Autowired
	UsersService usersService;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Value("${spring.datasource.url}")
	private String conexion;

	@Value("${spring.datasource.username}")
	private String userbd;

	@Value("${spring.datasource.password}")
	private String passbd;

	Logger logger = LoggerFactory.getLogger(VicepresidenciesControler.class);

	@PostMapping("/vicepresidencies")
	public ResponseEntity<?> listarVicepresidencies(HttpServletRequest request,
			@RequestBody VicepresidenciesListDto tiposfiltros) throws ParseException {

		RespuestaMsgDto respuesta = new RespuestaMsgDto("");
		HttpStatus estatus = HttpStatus.FORBIDDEN;
		long cuantosregistro = 0;

		String sessionid = request.getHeader("Authorization");
		Date fecha = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dataFormattata = formatter.format(fecha);
		BcpdrpparDto detalleTypes;
		List<BcpdrpparDto> listasTypes = new ArrayList<>();
		String searchIn = "";
		String typeIn = "";
		int statusIn = 0;
		String searchModule = "";
		String searchUsr = "";
		String contentIn = "";
		int orderIn = 0;
		int idrol;
		int offsetIn = 0;
		int numofrecordsIn = 0;
		int formatList = tiposfiltros.getFormat();
		Optional<Params> deSessDuration = paramsRepository.findByParamname("SESSION_DURATION");
		String SessionDuration = deSessDuration.get().getValue();
		int duracionSession = Integer.parseInt(SessionDuration);
		Date fecha2 = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(fecha2); // tuFechaBase es un Date;
		// calendar.add(Calendar.MINUTE, minutosASumar); //minutosASumar es int.
		calendar.add(Calendar.MINUTE, duracionSession); // horasASumar es int.
		// lo que más quieras sumar
		Date ValidThrufechaSalida = calendar.getTime(); // Y ya tienes la fecha sumada.
		SimpleDateFormat salida = new SimpleDateFormat("yyyy-MM-dd HH:mm"); // 2024-12-23 23:00
		String fechaComoCadena = salida.format(ValidThrufechaSalida);
		System.out.println(fechaComoCadena);

		// Verifico la session
		if (sessionid == null) {
			respuesta.setMsg("Llamada al servicio malformado");
			estatus = HttpStatus.BAD_REQUEST;
			return new ResponseEntity(respuesta, estatus);
		} else {
			sessionid = sessionid.substring(7);
			// verifico si la sesión del usuario existe.
			Optional<Users> encontreSessionUsuario = usersRepository.getBySessionid(sessionid);
			if (encontreSessionUsuario.isPresent()) { // si la sesión del usuario existe
				Date FechaReg = encontreSessionUsuario.get().getValidthru();
				// Llamada a la funcion que validad el tiempo de Session, retorna la fecha
				// sumandole el tiempo de session activa, y vacio si no esta activa
				fechaComoCadena = securityService.consultarSessionActiva(FechaReg, fecha2,
						encontreSessionUsuario.get().getId());

				if (fechaComoCadena == "") {
					RespuestaMsgDto respuestaDto2;
					String var2 = "";
					boolean bloked2 = false;
					respuestaDto2 = new RespuestaMsgDto(var2);
					respuestaDto2.setMsg("Sesión expirada o inválida");
					return new ResponseEntity(respuestaDto2, HttpStatus.UNAUTHORIZED);
				}

				// Este proceso permite obtener un listado de los procesos. (Priv 120)

				Roles roles = encontreSessionUsuario.get().getRolid();
				// Roles roles = encontreSessionUsuario.get().getRolid();
				idrol = roles.getId();
				int rolisvalid = auditRepository.getCantbyRolAndPrivi(encontreSessionUsuario.get().getRolid().getId(),
						490);
				if (formatList != 2) {
					if (rolisvalid == 0) {
						respuesta.setMsg("No tiene los Privilegios");
						estatus = HttpStatus.FORBIDDEN;
						return new ResponseEntity(respuesta, estatus);
					}
				}

				// Obtengo los datos del Body
				searchIn = tiposfiltros.getFilters().getSearch();// dato de busqueda por nombre
				String Salida = usersService.verificarCaracteresValidosConRegex(searchIn);

				if (Salida == "NOOK") {
					String var = "";
					boolean bloked = false;
					RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
					// respuestaDto.setBlocked(bloked);
					respuestaDto.setMsg("Caracteres no permitidos en la busqueda");
					return new ResponseEntity(respuestaDto, HttpStatus.BAD_REQUEST);
				}

				statusIn = tiposfiltros.getFilters().getStatus();// dato de busqueda por status
				try {
					typeIn = tiposfiltros.getFilters().getType();
					if (typeIn == null) {
						typeIn = "";
					}

				} catch (Exception e) {

					typeIn = "";

				}

				searchModule = tiposfiltros.getFilters().getModule();
				searchUsr = tiposfiltros.getFilters().getUser();
				orderIn = tiposfiltros.getOrder(); // Orden Ascedente o Descendente
				offsetIn = tiposfiltros.getOffset();// Primer registro a mostrar
				numofrecordsIn = tiposfiltros.getNumofrecords();// Número de registros a mostrar
				contentIn = tiposfiltros.getContent();
				// Verifico los Shorcouts
				if (contentIn != null && contentIn != "") {
					menuService.iscontentdiffnull(contentIn, encontreSessionUsuario.get().getId());
				}

			} else { // Si la sesión que viene es inválida
				respuesta.setMsg("Sesión expirada o inválida");
				estatus = HttpStatus.BAD_REQUEST;
				return new ResponseEntity(respuesta, estatus);
			}

			// Aqui empieza la carga de la data de respuesta

			VicepresResponseDto vicepresiden = new VicepresResponseDto();
			VicepresResponseDto3 vicepresiden3 = new VicepresResponseDto3();
			VicepresidenciesResponseDto vicepresidenciesResponseDto = new VicepresidenciesResponseDto();
			VicepresidenciesResponseDto2 vicepresidenciesResponseDto2 = new VicepresidenciesResponseDto2();
			VicepresidenciesResponseDto3 vicepresidenciesResponseDto3 = new VicepresidenciesResponseDto3();
			PrivilegesAllDto detallePrivilege = new PrivilegesAllDto();
			List<VicepresidenciaResponseDto> vicepresidenciesResultado = new ArrayList();
			List<VicepresidenciesResponseDto2> vicepresidenciesResultado2 = new ArrayList();
			List<VicepresidenciesResponseDto3> vicepresidenciesResultado3 = new ArrayList();

			try {
				// Sentencia General
				String SentenciaBase = "";
				if (formatList != 2) {
					SentenciaBase = "SELECT v.id,v.name,v.status AS idStatus,CASE WHEN v.status = 1 THEN 'Activo' ELSE 'Inactivo' END AS decstatus,"
							+ " v.ref,CAST(v.unittypepar AS TEXT) AS unittypepar,v.dsc,pr.descr, CAST(COUNT(u.id) AS INTEGER) AS total_unidades  FROM main.vicepresidencies v"
							+ " LEFT JOIN (SELECT elemento ->> 'dsc' AS descr,elemento ->> 'value' AS valor "
							+ "						   							    FROM main.params p,jsonb_array_elements(CAST(p.value AS jsonb)) AS elemento "
							+ "						   							    WHERE p.paramname = 'UNIT_TYPE') pr ON v.unittypepar = CAST(pr.valor AS INTEGER)"
							+ " LEFT JOIN  main.units u ON u.vicepresidencyid = v.id";
				} else {

					SentenciaBase = "SELECT v.id,v.name,v.status AS idStatus,CASE WHEN v.status = 1 THEN 'Activo' ELSE 'Inactivo' END AS decstatus,v.ref,CAST(v.unittypepar AS TEXT) AS unittypepar,v.dsc,pr.descr FROM main.vicepresidencies v"
							+ " LEFT JOIN (SELECT elemento ->> 'dsc' AS descr,elemento ->> 'value' AS valor "
							+ "						   							    FROM main.params p,jsonb_array_elements(CAST(p.value AS jsonb)) AS elemento "
							+ "						   							    WHERE p.paramname = 'UNIT_TYPE') pr ON v.unittypepar = CAST(pr.valor AS INTEGER)";
				}

				String SetenciaTypes = "";

				SetenciaTypes = "SELECT  elemento ->> 'dsc' AS descr,elemento ->> 'value' AS valor "
						+ " FROM main.params p, jsonb_array_elements(CAST(p.value AS jsonb)) AS elemento WHERE paramname = 'UNIT_TYPE' ORDER BY valor ASC";

				String QueryTotal = "";
				String name = "v.name"; // buscar por nombre
				String status = "v.status"; // buscar por status
				String lowername = "LOWER(v.name)"; // se convierte en minúscula
				String lowerref = "LOWER(v.ref)"; // se convierte en minúscula
				String LowerSearch = searchIn.toLowerCase(); // se convierte en minúscula

				// Se verifica si viene dato en el campo search para efectuar la búsqueda

				switch (searchIn) {
				case "":
					switch (statusIn) {
					case 0:
						// viene sin busqueda por el like
						QueryTotal = SentenciaBase + " WHERE 1 = 1 ";
						break;
					case 1:
						// viene sin busqueda por el like
						QueryTotal = SentenciaBase + " WHERE " + status + " =  " + 1;
						break;
					default:
						QueryTotal = SentenciaBase + " WHERE " + status + " =  " + 0;
						break;
					}
					break;
				default: // viene con el parametro para buscar por el like
					switch (statusIn) {
					case 0:
						// viene sin busqueda por el like
						QueryTotal = SentenciaBase + " WHERE ( " + lowername + " LIKE " + "'%" + LowerSearch + "%'"
								+ " OR " + lowerref + " LIKE " + "'%" + LowerSearch + "%')";
						break;

					case 1:
						// viene sin busqueda por el like
						QueryTotal = SentenciaBase + " WHERE " + status + " =  " + 1 + " AND (" + lowername + " LIKE "
								+ "'%" + LowerSearch + "%'" + " OR " + lowerref + " LIKE " + "'%" + LowerSearch + "%')";
						break;
					default:
						QueryTotal = SentenciaBase + " WHERE " + status + " =  " + 0 + " AND (" + lowername + " LIKE "
								+ "'%" + LowerSearch + "%'" + " OR " + lowerref + " LIKE " + "'%" + LowerSearch + "%')";
						break;
					}
					break;
				}

				switch (typeIn) {
				case "":
					QueryTotal = QueryTotal;
					break;
				default: // viene con el parametro para buscar por el like
					Integer valorint = Integer.parseInt(typeIn);
					QueryTotal = QueryTotal + " and v.unittypepar = " + valorint;
					break;
				}

				String Groupby = " GROUP BY  v.id,v.name,v.status,v.ref, v.dsc,pr.descr ";
				// String Groupby = " GROUP BY v.id,v.name,v.status,pr.descr ";
				// v.id,v.name,v.status,v.ref, v.dsc,pr.descr
				QueryTotal = QueryTotal + Groupby;
				// Busca si es ascendente o descendente
				switch (orderIn) {
				case 1: // ordena por name y status ascendente
					// QueryTotal = QueryTotal + " ORDER BY " + name + " ASC" + "," + status + "
					// ASC";
					QueryTotal = QueryTotal + " ORDER BY " + name + " ASC ";
					break;

				case 2:// ordena por name ascendente
						// QueryTotal = QueryTotal + " ORDER BY " + name + " ASC";
					QueryTotal = QueryTotal + " ORDER BY " + status + " ASC ";
					break;

				case 3: // ordena por status ascendente
					QueryTotal = QueryTotal + " ORDER BY " + 9 + " ASC ";
					break;

				case 4: // ordena por status ascendente
					QueryTotal = QueryTotal + " ORDER BY " + 6 + " ASC ";
					break;

				case 99:// ordena por status descendente
					QueryTotal = QueryTotal + " ORDER BY " + " v.id " + " ASC ";
					break;

				case -1:// ordena por name y status descendente
					// QueryTotal = QueryTotal + " ORDER BY " + name + "DESC" + "," + status + "
					// DESC";
					QueryTotal = QueryTotal + " ORDER BY " + name + " DESC ";
					break;

				case -2:// ordena por name descendente
					// QueryTotal = QueryTotal + " ORDER BY " + name + " ASC";
					QueryTotal = QueryTotal + " ORDER BY " + status + " DESC ";
					break;

				case -3:// ordena por status descendente
					QueryTotal = QueryTotal + " ORDER BY " + 9 + " DESC ";
					break;

				case -4:// ordena por status descendente
					QueryTotal = QueryTotal + " ORDER BY " + 6 + " DESC ";
					break;

				case -99:// ordena por status descendente
					QueryTotal = QueryTotal + " ORDER BY " + " v.id " + " DESC ";
					break;

				default:
					respuesta.setMsg("Error interno del servidor");
					estatus = HttpStatus.INTERNAL_SERVER_ERROR;
					return new ResponseEntity(respuesta, estatus);
				}

				// Se mapea la entidad se le pasa el query y lo bota como un tipo de objeto
				// ParamDto-Buscar en los DTO
				// TypedQuery<VicepresidenciesResponseDto> vicepresidencies;
				Query vicepresidencies;
				Query vicepresidencies2;
				// TypedQuery<VicepresidenciesResponseDto2> vicepresidencies2;
				VicepresidenciaResponseDto vicepresidencia = new VicepresidenciaResponseDto();
				// detalleVice = new VicepresidencyDto();
				List<VicepresidenciesResponseDto> vicepresidenciesList = new ArrayList();
				List<VicepresidenciesResponseDto> VicepresidenciaResponseDto = new ArrayList();
				List<VicepresidenciesResponseDto2> vicepresidenciesList2 = new ArrayList();
				List<VicepresidenciesResponseDto3> vicepresidenciesList3 = new ArrayList();
				System.out.println(QueryTotal);

				Query queryTypes = entityManager.createNativeQuery(SetenciaTypes);
				List<Object[]> listatipos = queryTypes.getResultList();
				for (Object[] types : listatipos) {
					detalleTypes = new BcpdrpparDto();

					detalleTypes.setDsc((String) types[0]);
					detalleTypes.setValue((String) types[1]);
					listasTypes.add(detalleTypes);
				}

				List<Object[]> listatipos1;
				if (formatList != 2) {

					// vicepresidencies = entityManager.createQuery(QueryTotal,
					// VicepresidenciesResponseDto.class);
					vicepresidencies = entityManager.createNativeQuery(QueryTotal);
					// vicepresidenciesList = vicepresidencies.getResultList();

					cuantosregistro = (long) vicepresidencies.getResultList().size();

					vicepresidencies.setFirstResult(offsetIn);
					vicepresidencies.setMaxResults(numofrecordsIn);
					listatipos1 = vicepresidencies.getResultList();
				} else {
					// vicepresidencies2 = entityManager.createQuery(QueryTotal,
					// VicepresidenciesResponseDto2.class);
					vicepresidencies2 = entityManager.createNativeQuery(QueryTotal);
					listatipos1 = vicepresidencies2.getResultList();
					// vicepresidenciesList2 = vicepresidencies2.getResultList();
					cuantosregistro = (long) vicepresidencies2.getResultList().size();
				}

				if (formatList != 2) {

					// 4. Recorrer la lista y procesar los resultados
					// for (VicepresidenciesResponseDto vice : vicepresidenciesList) {
					for (Object[] types1 : listatipos1) {
						StateDto detalleStatus = new StateDto();
						TypeUnitDto detalleType = new TypeUnitDto();
						vicepresidencia = new VicepresidenciaResponseDto();
						// detalleVice = new VicepresidencyDto();

						vicepresidencia.setId((int) types1[0]);
						vicepresidencia.setName((String) types1[1]);
						vicepresidencia.setRef((String) types1[4]);
						vicepresidencia.setDsc((String) types1[6]);
						vicepresidencia.setUnits((int) types1[8]);
						// vicepresidenciesResponseDto.setStatusvice.getStatus());
						detalleStatus.setId((int) types1[2]);
						detalleStatus.setName((String) types1[3]);
						// String idtype = (String) vice.getType();

						detalleType.setId((String) types1[5]);
						detalleType.setDsc((String) types1[7]);

						vicepresidencia.setStatus(detalleStatus);
						vicepresidencia.setType(detalleType);

						vicepresidenciesResultado.add(vicepresidencia);
						vicepresidenciesResponseDto = new VicepresidenciesResponseDto();
					}

					detallePrivilege = new PrivilegesAllDto();

					boolean tieneView = rolesPrivilegesRepository.existsByRolidAndPrivilegeid(idrol, 490);
					boolean tieneUpdate = rolesPrivilegesRepository.existsByRolidAndPrivilegeid(idrol, 491);
					boolean tieneAdd = rolesPrivilegesRepository.existsByRolidAndPrivilegeid(idrol, 492);
					boolean tieneDelete = rolesPrivilegesRepository.existsByRolidAndPrivilegeid(idrol, 493);
					// existsByRolidAndPrivilegeid

					detallePrivilege.setView(tieneView);
					detallePrivilege.setUpdate(tieneUpdate);
					detallePrivilege.setAdd(tieneAdd);
					detallePrivilege.setDelete(tieneDelete);
					// Se construye el Dto de Roles de Respuesta según los privilegios que
					// tenga el usuario
					/*
					 * detallePrivilege = new PrivilegesAllDto(); if
					 * (privilegesRepository.existsById(491)) detallePrivilege.setUpdate(true); else
					 * detallePrivilege.setUpdate(false);
					 * 
					 * if (privilegesRepository.existsById(490)) detallePrivilege.setView(true);
					 * else detallePrivilege.setView(false);
					 * 
					 * if (privilegesRepository.existsById(492)) detallePrivilege.setAdd(true); else
					 * detallePrivilege.setAdd(false);
					 * 
					 * if (privilegesRepository.existsById(493)) detallePrivilege.setDelete(true);
					 * else detallePrivilege.setDelete(false);
					 */

					vicepresiden.setNumofrecords(cuantosregistro);
					vicepresiden.setRecords(vicepresidenciesResultado);
					vicepresiden.setSessionvalidthru(fechaComoCadena);
					vicepresiden.setType(listasTypes);
					vicepresiden.setPrivileges(detallePrivilege);

					return new ResponseEntity(vicepresiden, HttpStatus.OK);
				} else {

					// StatusDto2 statusDto2= new StatusDto2();
					// StateDto detalleStatus = new StateDto();
					// TypeUnitDto detalleType = new TypeUnitDto();
					// 4. Recorrer la lista y procesar los resultados
					// for (VicepresidenciesResponseDto2 vice : vicepresidenciesList2) {
					for (Object[] types1 : listatipos1) {

						StateDto detalleStatus = new StateDto();
						TypeUnitDto detalleType = new TypeUnitDto();
						vicepresidenciesResponseDto3.setId((int) types1[0]);
						vicepresidenciesResponseDto3.setName((String) types1[1]);
						vicepresidenciesResponseDto3.setDsc((String) types1[6]);
						// vicepresidenciesResponseDto3.setRef(vice.getRef());
						// vicepresidenciesResponseDto3.setDsc(vice.getDsc());
						detalleStatus.setId((int) types1[2]);
						detalleStatus.setName((String) types1[3]);
						detalleType.setId((String) types1[5]);
						detalleType.setDsc((String) types1[7]);

						vicepresidenciesResponseDto3.setType(detalleType);
						vicepresidenciesResponseDto3.setStatus(detalleStatus);
						vicepresidenciesResultado3.add(vicepresidenciesResponseDto3);
						vicepresidenciesResponseDto3 = new VicepresidenciesResponseDto3();
					}

					vicepresiden3.setRecords(vicepresidenciesResultado3);
					vicepresiden3.setSessionvalidthru(fechaComoCadena);

					return new ResponseEntity(vicepresiden3, HttpStatus.OK);
				}

			} catch (Exception e) {
				respuesta.setMsg("Error interno del servidor ");
				estatus = HttpStatus.INTERNAL_SERVER_ERROR;
			} finally {
				if (entityManager != null && entityManager.isOpen()) {
					entityManager.close();
				}
			}
		}
		return new ResponseEntity(respuesta, HttpStatus.OK);
	}

	// vicepresidencies/vicepresidencyid
	@GetMapping("/vicepresidencies/{vicepresidencyid}")
	public ResponseEntity<?> getOneVP(HttpServletRequest request,
			@PathVariable("vicepresidencyid") final Integer vicepresidencyid) throws ParseException {
		RespuestaDto respuesta = new RespuestaDto("", false);
		HttpStatus estatus = HttpStatus.FORBIDDEN;
		WorkerEntryResponseDto workersEntryResponseDto = new WorkerEntryResponseDto();
		// ParamsDto detalleParams;
		WorkersDto detalleWorkers;
		StateDto detalleStatus;
		PrivilegesAllDto detallePrivilege;

		Long cuantosregistro = (long) 0;
		List<PrivilegesAllDto> listasPrivelege = new ArrayList<>();

		String sessionid = request.getHeader("Authorization");
		Date fecha = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dataFormattata = formatter.format(fecha);
		Date fechaDate = formatter.parse(dataFormattata);
		AuditRequestDto auditDto = new AuditRequestDto();

		String searchIn = "";
		// String searchModule = "";
		int searchStatus = 0;
		int idrol;
		String contentIn = "";

		String fechaComoCadena;
		int orderIn = 0;
		int offsetIn = 0;
		int numofrecordsIn = 0;
		Optional<Params> deSessDuration = paramsRepository.findByParamname("SESSION_DURATION");
		String SessionDuration = deSessDuration.get().getValue();
		int duracionSession = Integer.parseInt(SessionDuration);
		Date fecha2 = new Date();
		ViceEntryDto viceentryDto = new ViceEntryDto();
		ViceEntryDto detalleEntry = new ViceEntryDto();
		VicepresidenciesEntryResponseDto vicepresidenciesEntryResponseDto = new VicepresidenciesEntryResponseDto();

		if (sessionid == null) {
			String var = "";
			boolean bloked = false;
			RespuestaDto respuestaDto = new RespuestaDto(var, bloked);
			respuestaDto.setBlocked(bloked);
			respuestaDto.setMsg("Sesión expirada o inválida");
			// Error 400
			return new ResponseEntity(respuestaDto, HttpStatus.BAD_REQUEST);
		} else {

			sessionid = sessionid.substring(7);
			Optional<Users> encontreSessionUsuario = usersRepository.getBySessionid(sessionid);
			// String usuarioIN = encontreSessionUsuario.get().getUsr();
			// int position = usuarioIN.indexOf('(');

			if (encontreSessionUsuario.isPresent()) {

				Date FechaReg = encontreSessionUsuario.get().getValidthru();
				// Llamada a la funcion que validad el tiempo de Session, retorna la fecha
				// sumandole el tiempo de session activa, y vacio si no esta activa

				// fechaComoCadena = securityService.consultarSessionActiva(FechaReg,fecha2);
				fechaComoCadena = securityService.consultarSessionActiva(FechaReg, fecha2,
						encontreSessionUsuario.get().getId());

				if (fechaComoCadena == "") {

					String var = "";
					boolean bloked = false;
					RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
					// respuestaDto.setBlocked(bloked);
					respuestaDto.setMsg("Sesión expirada o inválida");
					return new ResponseEntity(respuestaDto, HttpStatus.UNAUTHORIZED);

				}

				// Este proceso permite obtener un listado de los empleados. (Priv 420)
				Roles roles = encontreSessionUsuario.get().getRolid();
				idrol = roles.getId();
				int rolisvalid = auditRepository.getCantbyRolAndPrivi(idrol, 490);

				if (rolisvalid == 0) {

					String var = "";
					boolean bloked = false;
					RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
					// respuestaDto.setBlocked(bloked);
					respuestaDto.setMsg("No tiene los Privilegios");
					return new ResponseEntity(respuestaDto, HttpStatus.FORBIDDEN);

				}

			} else {
				String var = "";
				boolean bloked = false;
				RespuestaDto respuestaDto = new RespuestaDto(var, bloked);
				respuestaDto.setBlocked(bloked);
				respuestaDto.setMsg("Sesión expirada o inválida");
				// Error 400
				return new ResponseEntity(respuestaDto, HttpStatus.UNAUTHORIZED);
			}
		}

		try {

			String SentenciaBase = "SELECT v.id,v.name,v.status AS idStatus,CASE WHEN v.status = 1 THEN 'Activo' ELSE 'Inactivo' END AS decstatus,v.ref,CAST(v.unittypepar AS TEXT) AS unittypepar,v.dsc,pr.descr FROM main.vicepresidencies v"
					+ " LEFT JOIN (SELECT elemento ->> 'dsc' AS descr,elemento ->> 'value' AS valor "
					+ "						   							    FROM main.params p,jsonb_array_elements(CAST(p.value AS jsonb)) AS elemento "
					+ "						   							    WHERE p.paramname = 'UNIT_TYPE') pr ON v.unittypepar = CAST(pr.valor AS INTEGER)"
					+ " WHERE v.id =" + vicepresidencyid;

			String QueryTotal = "";
			String name = "u.name";
			String status = "u.status";
			String lowername = "LOWER(u.name)";
			String LowerSearch = searchIn.toLowerCase();

			Query queryTypes = entityManager.createNativeQuery(SentenciaBase);
			List<Object[]> listatipos = queryTypes.getResultList();

			for (Object[] types : listatipos) {

				detalleEntry = new ViceEntryDto();
				detalleStatus = new StateDto();
				TypeUnitDto detalleType = new TypeUnitDto();

				// ViceEntryDto viceentryDto = new ViceEntryDto();

				detalleEntry.setId((int) types[0]);
				detalleEntry.setName((String) types[1]);
				detalleEntry.setDsc((String) types[6]);
				detalleEntry.setRef((String) types[4]);

				detalleStatus.setId((int) types[2]);
				detalleStatus.setName((String) types[3]);

				detalleType.setId((String) types[5]);
				detalleType.setDsc((String) types[7]);

				detalleEntry.setStatus(detalleStatus);
				detalleEntry.setType(detalleType);

			}

			vicepresidenciesEntryResponseDto.setEntry(detalleEntry);

			return ResponseEntity.ok(vicepresidenciesEntryResponseDto);

		} catch (Exception e) {
			// Manejo de excepciones
			respuesta = new RespuestaDto("Error interno del servidor", false);
			estatus = HttpStatus.INTERNAL_SERVER_ERROR;
		} finally {
			if (entityManager != null && entityManager.isOpen()) {
				entityManager.close();
			}
		}

		return new ResponseEntity(respuesta, estatus);

	}

	@PostMapping("/vicepresidencies/{vicepresidencyid}")
	public ResponseEntity<ParamsResponseDto> vpUpdate(HttpServletRequest request,
			@RequestBody WorkersRequestBodyDto datosvp,
			@PathVariable("vicepresidencyid") final Integer vicepresidencyid) throws ParseException {
		// @GetMapping("/vicepresidencies/{vicepresidencyid}")

		RespuestaValueDto respuestaValueDto;
		RespuestaMsgDto respuesta = new RespuestaMsgDto("");
		HttpStatus estatus = HttpStatus.FORBIDDEN;
		ParamsResponseDto paramsResponseDto = new ParamsResponseDto();
		ParamsDto detalleParams;
		PrivilegesDto detallePrivilege;
		List<ParamsDto> listasParams = new ArrayList<>();
		List<PrivilegesDto> listasPrivelege = new ArrayList<>();

		int idparametro = vicepresidencyid;

		int valor = idparametro;
		String sessionid = request.getHeader("Authorization");
		Date fecha = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dataFormattata = formatter.format(fecha);
		Date fechaDate = formatter.parse(dataFormattata);
		AuditRequestDto auditDto = new AuditRequestDto();
		Optional<Users> encontreSessionUsuario;
		Date fecha2 = new Date();
		Calendar calendar = Calendar.getInstance();

		if (sessionid == null) {
			String var = "";
			boolean bloked = false;
			RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
			// respuestaDto.setBlocked(bloked);
			respuestaDto.setMsg("Llamada al servicio malformado");
			// Error 400
			return new ResponseEntity(respuestaDto, HttpStatus.BAD_REQUEST);
		} else {

			sessionid = sessionid.substring(7);
			encontreSessionUsuario = usersRepository.getBySessionid(sessionid);
			String fechaComoCadena;

			if (encontreSessionUsuario.isPresent()) {

				Date FechaReg = encontreSessionUsuario.get().getValidthru();
				// Llamada a la funcion que validad el tiempo de Session, retorna la fecha
				// sumandole el tiempo de session activa, y vacio si no esta activa

				// fechaComoCadena = securityService.consultarSessionActiva(FechaReg,fecha2);
				fechaComoCadena = securityService.consultarSessionActiva(FechaReg, fecha2,
						encontreSessionUsuario.get().getId());
				if (fechaComoCadena == "") {

					String var = "";
					boolean bloked = false;
					RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
					// respuestaDto.setBlocked(bloked);
					respuestaDto.setMsg("Sesión expirada o inválida");
					return new ResponseEntity(respuestaDto, HttpStatus.UNAUTHORIZED);

				}

				// Actualiza o Incluye un registro de un usuario. (Si el unitid es 0 se
				// incluye). (priv 111 MOD Y 112 INC)
				if (idparametro == 0) {
					// el permiso es el 632
					Roles roles = encontreSessionUsuario.get().getRolid();
					int idrol = roles.getId();
					int rolisvalid = auditRepository.getCantbyRolAndPrivi(idrol, 492);
					// rolisvalid = 3;
					if (rolisvalid == 0) {

						String var = "";
						boolean bloked = false;
						RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
						// respuestaDto.setBlocked(bloked);
						respuestaDto.setMsg("No tiene los Privilegios");
						return new ResponseEntity(respuestaDto, HttpStatus.FORBIDDEN);

					}

				} else {

					Roles roles = encontreSessionUsuario.get().getRolid();
					int idrol = roles.getId();
					int rolisvalid = auditRepository.getCantbyRolAndPrivi(idrol, 491);
					// rolisvalid = 3;
					if (rolisvalid == 0) {

						String var = "";
						boolean bloked = false;
						RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
						// respuestaDto.setBlocked(bloked);
						respuestaDto.setMsg("No tiene los Privilegios");
						return new ResponseEntity(respuestaDto, HttpStatus.FORBIDDEN);

					}

					boolean existevp = vicepresidenciesRepository.existsById(vicepresidencyid);

					if (!existevp) {

						String var = "";
						RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
						// respuestaDto.setBlocked(bloked);
						respuestaDto.setMsg("Registro No encontrado");
						// Error 400
						return new ResponseEntity(respuestaDto, HttpStatus.BAD_REQUEST);

					}
				}

				String Salida1 = usersService.verificarCaracteresValidosConRegex(datosvp.getRef());
				String Salida2 = usersService.verificarCaracteresValidosConRegex(datosvp.getName());
				String Salida3 = usersService.verificarCaracteresValidosConRegex(datosvp.getDsc());

				if (Salida1 == "NOOK" || Salida2 == "NOOK" || Salida3 == "NOOK") {
					String var = "";
					boolean bloked = false;
					RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
					// respuestaDto.setBlocked(bloked);
					respuestaDto.setMsg("Caracteres no permitidos en la busqueda");
					return new ResponseEntity(respuestaDto, HttpStatus.BAD_REQUEST);
				}

				if (idparametro == 0) {

					if (datosvp.getRef() != "") {

						// boolean existeRef = unitsRepository.existsByRef(datosUnidad.getRef());
						String Query1 = "SELECT name FROM main.vicepresidencies WHERE LOWER(ref) = " + "'"
								+ datosvp.getRef().toString().toLowerCase() + "'";
						Long cuantosregistroref = (long) jdbcTemplate.queryForList(Query1).size();

						if (cuantosregistroref > 0) {
							String var = "";
							RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
							// respuestaDto.setBlocked(bloked);
							respuestaDto.setMsg("Registro Duplicado");
							// Error 400
							return new ResponseEntity(respuestaDto, HttpStatus.CONFLICT);
						}
					}

					if (datosvp.getName() != "") {

						// boolean existeName = unitsRepository.existsByName(datosUnidad.getName());
						String Query2 = "SELECT name FROM main.vicepresidencies WHERE LOWER(name) = " + "'"
								+ datosvp.getName().toLowerCase() + "'";

						Long cuantosregistroname = (long) jdbcTemplate.queryForList(Query2).size();

						if (cuantosregistroname > 0) {
							String var = "";
							RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
							// respuestaDto.setBlocked(bloked);
							respuestaDto.setMsg("Registro Duplicado");
							// Error 40
							return new ResponseEntity(respuestaDto, HttpStatus.CONFLICT);
						}
					}

				}

			} else {
				String var = "";
				boolean bloked = false;
				RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
				// respuestaDto.setBlocked(bloked);
				respuestaDto.setMsg("Sesión expirada o inválida");
				// Error 400
				return new ResponseEntity(respuestaDto, HttpStatus.UNAUTHORIZED);
			}
		}

		try {

			// Workers tipoWorkers2=null;
			Vicepresidencies tipovp2 = null;
			// Workers tipoWorker=null;
			Vicepresidencies tipovp = null;
			// Workers tipoWorkerNew2=null;
			Vicepresidencies tipovpNew2 = null;
			// Optional<Workers> nuevoinsertado = null;
			Optional<Vicepresidencies> nuevoinsertado = null;
			// Userunits tipoUsersUnits = new Userunits();
			// Unitprocesses tipoUsersUnits = new Unitprocesses();

			if (idparametro == 0) {
				// Workers tipoWorkersNew = new Workers();
				Vicepresidencies tipovpNew = new Vicepresidencies();

				// Workers
				// datosWorker
				tipovpNew.setStatus(datosvp.getStatus());
				tipovpNew.setModifiedat(fechaDate);
				tipovpNew.setCreatedat(fechaDate);
				tipovpNew.setName(datosvp.getName());
				tipovpNew.setUnittypepar(datosvp.getUnittypepar());
				tipovpNew.setDsc(datosvp.getDsc());
				tipovpNew.setRef(datosvp.getRef());
				// Positions relaposition =
				// positionsRepository.getById(datosWorker.getPositionid());
				// tipoWorkersNew.setPositionid(relaposition);

				tipovpNew2 = vicepresidenciesService.addIdVicepresidencies(tipovpNew);
				tipovp2 = tipovpNew2;
				nuevoinsertado = vicepresidenciesRepository.findByName(datosvp.getName());
				int idInsertado = nuevoinsertado.get().getId();
				int idmensaje = idInsertado;

				////////////////////////// INSERCION BLOQUE DE AUDITORIA///////////////////
				String module = "Vicepresidencia";
				// String Descmodule = "Actualización de parametro del Sistema con id: " +
				// parmid ;
				String Descmodule = "Se agregó la Vicepresidencia: " + datosvp.getName() + " con Id:" + idInsertado;

				auditDto.setIpaddr(HttpReqRespUtils.getClientIpAddressIfServletRequestExist());

				String singo1 = "(";
				String singo2 = ")";
				String usryemail = encontreSessionUsuario.get().getUsr().concat(" ").concat(singo1)
						.concat(encontreSessionUsuario.get().getEmail().concat(singo2));
				auditDto.setUserref(usryemail);
				auditDto.setModule(module);
				auditDto.setDesc(Descmodule);
				auditDto.setCreatedat(fechaDate);
				usersService.registrarAuditSesion(auditDto);

				respuestaValueDto = new RespuestaValueDto(idmensaje);
				estatus = HttpStatus.OK;
				return new ResponseEntity(respuestaValueDto, estatus);

			} else {
				// tipoUsers = usersService.getUsersByid(idparametro);
				/// tipoUnits = workersService.getWorkersByid(idparametro);
				tipovp = vicepresidenciesService.getVicepresidenciesByid(idparametro);
				// Positions relaposition =
				// positionsRepository.getById(datosWorker.getPositionid());

				tipovp.setStatus(datosvp.getStatus());
				tipovp.setDsc(datosvp.getDsc());
				tipovp.setUnittypepar(datosvp.getUnittypepar());
				// tipoUsers.setUsr(datosUsuario.getUsr());

				String vp1 = tipovp.getName();
				String vp2 = datosvp.getName();
				if (vp1.equals(vp2)) {
					String Validausers = "La vp es la misma";

				} else {

					String QueryTotal = "SELECT name FROM main.vicepresidencies WHERE LOWER(name) = " + "'"
							+ datosvp.getName().toString().toLowerCase() + "'";
					Long validavp = (long) jdbcTemplate.queryForList(QueryTotal).size();

					if (validavp > 0) {

						String var = "";
						// boolean bloked = false;
						RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
						// respuestaDto.setBlocked(bloked);
						respuestaDto.setMsg("Registro Duplicado");
						// Error 400
						return new ResponseEntity(respuestaDto, HttpStatus.CONFLICT);

					} else {
						tipovp.setName(datosvp.getName());
					}
				}

				// tipoUnits.setDsc(datosUnidad.getDsc());
				// Positions relaposition =
				// positionsRepository.getById(datosWorker.getPositionid());
				// tipoWorker.setPositionid(relaposition);
				tipovp.setModifiedat(fechaDate);
				String ref1 = tipovp.getRef();
				String ref2 = datosvp.getRef();

				if (ref2 == "") {
					tipovp.setRef(datosvp.getRef());
				} else {

					// if (ref1==null || ref1=="") {
					if (ref1 == null || ref1.isEmpty()) {
						String QueryTotal2 = "SELECT name FROM main.vicepresidencies WHERE LOWER(ref) = " + "'"
								+ datosvp.getRef().toString().toLowerCase() + "'";
						Long validaref = (long) jdbcTemplate.queryForList(QueryTotal2).size();
						if (validaref > 0) {

							String var = "";
							// boolean bloked = false;
							RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
							// respuestaDto.setBlocked(bloked);
							respuestaDto.setMsg("Registro Duplicado");
							// Error 400
							return new ResponseEntity(respuestaDto, HttpStatus.CONFLICT);

						} else {
							tipovp.setRef(datosvp.getRef());
						}

					} else {
						if (ref1.equals(ref2)) {
							String Validacorreo = "La ref es la misma";

						} else {
							// boolean validaref = unitsRepository.existsByRef(datosUnidad.getRef());
							String QueryTotal2 = "SELECT name FROM main.vicepresidencies WHERE LOWER(ref) = " + "'"
									+ datosvp.getRef().toString().toLowerCase() + "'";
							Long validaref = (long) jdbcTemplate.queryForList(QueryTotal2).size();
							if (validaref > 0) {

								String var = "";
								// boolean bloked = false;
								RespuestaMsgDto respuestaDto = new RespuestaMsgDto(var);
								// respuestaDto.setBlocked(bloked);
								respuestaDto.setMsg("Registro Duplicado");
								// Error 400
								return new ResponseEntity(respuestaDto, HttpStatus.CONFLICT);

							} else {
								tipovp.setRef(datosvp.getRef());
							}

						}
					} /// if (ref1=="")
				} /// if (ref2=="") {

				// tipovp2=workersService.addIdWorkers(tipoWorker);
				tipovp2 = vicepresidenciesService.addIdVicepresidencies(tipovp);

				////////////////////////// INSERCION BLOQUE DE AUDITORIA///////////////////
				String module = "Vicepresidencia";
				// String Descmodule = "Actualización de parametro del Sistema con id: " +
				// parmid ;
				String Descmodule = "Se actualizó la Vicepresidencia: " + datosvp.getName() + " con Id:"
						+ vicepresidencyid;

				auditDto.setIpaddr(HttpReqRespUtils.getClientIpAddressIfServletRequestExist());

				String singo1 = "(";
				String singo2 = ")";
				String usryemail = encontreSessionUsuario.get().getUsr().concat(" ").concat(singo1)
						.concat(encontreSessionUsuario.get().getEmail().concat(singo2));
				auditDto.setUserref(usryemail);
				auditDto.setModule(module);
				auditDto.setDesc(Descmodule);
				auditDto.setCreatedat(fechaDate);
				usersService.registrarAuditSesion(auditDto);
				////////////////////////// INSERCION BLOQUE DE AUDITORIA///////////////////
				int idmensaje = vicepresidencyid;
				respuestaValueDto = new RespuestaValueDto(idmensaje);
				estatus = HttpStatus.OK;
				return new ResponseEntity(respuestaValueDto, estatus);

			}

		} catch (Exception e) {
			// Manejo de excepciones
			respuesta = new RespuestaMsgDto("Error interno del servidor");
			estatus = HttpStatus.INTERNAL_SERVER_ERROR;
		} finally {
			if (entityManager != null && entityManager.isOpen()) {
				entityManager.close();
			}
		}

		return new ResponseEntity(respuesta, estatus);

	}

	@DeleteMapping("/vicepresidencies/{vicepresidencyid}")
	public ResponseEntity<?> borrarWorkers(HttpServletRequest request,
			@PathVariable("vicepresidencyid") final Integer vicepresidencyid) throws ParseException {
		RespuestaMsgDto respuesta = new RespuestaMsgDto("");
		HttpStatus estatus = HttpStatus.FORBIDDEN;
		RoleDto detalleRoles;
		PrivilegesAllDto detallePrivilege;

		String var = "";
		boolean bloked = false;
		RespuestaDto respuestaDto = new RespuestaDto(var, bloked);
		String sessionid = request.getHeader("Authorization");
		Date fecha = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dataFormattata = formatter.format(fecha);
		Date fechaDate = formatter.parse(dataFormattata);
		AuditRequestDto auditDto = new AuditRequestDto();
		RespuestaValueDto respuestaValueDto;
		String searchIn = "";

		Optional<Params> deSessDuration = paramsRepository.findByParamname("SESSION_DURATION");
		String SessionDuration = deSessDuration.get().getValue();
		int duracionSession = Integer.parseInt(SessionDuration);
		Date fecha2 = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(fecha2); // tuFechaBase es un Date;
		// calendar.add(Calendar.MINUTE, minutosASumar); //minutosASumar es int.
		calendar.add(Calendar.MINUTE, duracionSession); // horasASumar es int.
		// lo que más quieras sumar
		Date ValidThrufechaSalida = calendar.getTime(); // Y ya tienes la fecha sumada.

		if (sessionid == null) {
			respuesta.setMsg("Llamada al servicio malformado");
			estatus = HttpStatus.BAD_REQUEST;
			return new ResponseEntity(respuesta, estatus);
		} else {
			sessionid = sessionid.substring(7);
			Optional<Users> encontreSessionUsuario = usersRepository.getBySessionid(sessionid);

			if (encontreSessionUsuario.isPresent()) {
				// Eliminar un registro de un usuario. (priv 633)

				String fechaComoCadena;
				Date FechaReg = encontreSessionUsuario.get().getValidthru();
				// Llamada a la funcion que validad el tiempo de Session, retorna la fecha
				// sumandole el tiempo de session activa, y vacio si no esta activa

				// fechaComoCadena = securityService.consultarSessionActiva(FechaReg,fecha2);
				fechaComoCadena = securityService.consultarSessionActiva(FechaReg, fecha2,
						encontreSessionUsuario.get().getId());
				if (fechaComoCadena == "") {

					String var2 = "";
					boolean bloked2 = false;
					RespuestaMsgDto respuestaDto2 = new RespuestaMsgDto(var2);
					// respuestaDto.setBlocked(bloked);
					respuestaDto2.setMsg("Sesión expirada o inválida");
					return new ResponseEntity(respuestaDto, HttpStatus.UNAUTHORIZED);

				}

				Roles roles = encontreSessionUsuario.get().getRolid();
				int idrol = roles.getId();
				int rolisvalid = auditRepository.getCantbyRolAndPrivi(idrol, 493);
				// rolisvalid = 3;
				if (rolisvalid == 0) {

					// boolean bloked = false;
					RespuestaMsgDto respuestaPrivDto = new RespuestaMsgDto(var);
					// respuestaDto.setBlocked(bloked);
					respuestaPrivDto.setMsg("No tiene los Privilegios");
					return new ResponseEntity(respuestaPrivDto, HttpStatus.FORBIDDEN);

				}

				try {

					if (vicepresidenciesRepository.existsById(vicepresidencyid)) {

						Optional<Vicepresidencies> uniDelete = vicepresidenciesRepository.findById(vicepresidencyid);
						String module = "Vicepresidencia";
						String Descmodule = "Se eliminó la Vicepresidencia: " + uniDelete.get().getName() + " con Id: "
								+ uniDelete.get().getId();

						auditDto.setIpaddr(HttpReqRespUtils.getClientIpAddressIfServletRequestExist());

						String singo1 = "(";
						String singo2 = ")";
						String usryemail = encontreSessionUsuario.get().getUsr().concat(" ").concat(singo1)
								.concat(encontreSessionUsuario.get().getEmail().concat(singo2));
						auditDto.setUserref(usryemail);
						auditDto.setModule(module);
						auditDto.setDesc(Descmodule);
						auditDto.setCreatedat(fechaDate);
						usersService.registrarAuditSesion(auditDto);

						// Borro el rol boolean existeUsers = ;
						int valor = 0;
						try {
							// usersRepository.deleteusersbyid(userid,fechaDate,valor);
							vicepresidenciesRepository.deleteVicepresidenciesbyid(vicepresidencyid);
							respuestaValueDto = new RespuestaValueDto(vicepresidencyid);

							estatus = HttpStatus.OK;
							return new ResponseEntity(respuestaValueDto, estatus);
						} catch (Exception e) {// Error Interno
							respuesta.setMsg("Error interno del servidor -conflicto. ");
							estatus = HttpStatus.CONFLICT;
							return new ResponseEntity(respuesta, estatus);
						}
					} else {// Registro no encontrado
						respuesta.setMsg("Registro no encontrado");
						estatus = HttpStatus.NOT_FOUND;
						return new ResponseEntity(respuesta, estatus);

					}

				} catch (Exception e) {// Error Interno
					// Manejo de excepciones
					respuesta.setMsg("Error interno del servidor");
					estatus = HttpStatus.INTERNAL_SERVER_ERROR;
					return new ResponseEntity(respuesta, estatus);
				} finally {
					if (entityManager != null && entityManager.isOpen()) {
						entityManager.close();
					}
				}
			} else {
				respuesta.setMsg("Sesión expirada o inválida");
				estatus = HttpStatus.UNAUTHORIZED;
				return new ResponseEntity(respuesta, estatus);

			}

		}

	}

}
