package com.ejie.ab39a.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ejie.ab39a.constantes.Constantes;
import com.ejie.ab39a.dao.PlanesGestionDao;
import com.ejie.ab39a.model.AccionesPg;
import com.ejie.ab39a.model.Entidades;
import com.ejie.ab39a.model.PlanesEstrategicos;
import com.ejie.ab39a.model.PlanesGestion;
import com.ejie.ab39a.seguridad.UtilSeguridad;
import com.ejie.x38.dto.JQGridRequestDto;
import com.ejie.x38.dto.JQGridResponseDto;
import com.ejie.x38.dto.TableRowDto;


/**
 * PlanesGestion.
 * 
 *  
 */
@Service(value = "planesGestionService")
public class PlanesGestionServiceImpl implements PlanesGestionService {

    @Autowired
    private PlanesGestionDao planesGestionDao;

    /**
     * Inserts a single row in the PlanesGestion table.
     *
     * @param planesGestion
     *            PlanesGestion
     * @return PlanesGestion
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Throwable.class)
    public PlanesGestion add(PlanesGestion planesGestion) {
        /*
         * 24012018 Ahora un mismo plan estratégico puede tener asociado mas un plan de gestión para
         * el mismo año. List<PlanesGestion> listGestion =
         * this.planesGestionDao.findAll(planesGestion, null); if (!listGestion.isEmpty()) {
         * List<ErrorField> listaErrores = new ArrayList<ErrorField>(); listaErrores.add(new
         * ErrorField("planEstrategico.anio.inicio", "validacion.existeRegistro")); throw new
         * ErrorGenericoException(listaErrores); }
         */

        PlanesGestion planG = this.planesGestionDao.add(planesGestion);
        this.planesGestionDao.generarPlanesGestion(planG);
        return planG;
    }

    /**
     * Updates a single row in the PlanesGestion table.
     *
     * @param planesGestion
     *            PlanesGestion
     * @return PlanesGestion
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Throwable.class)
    public PlanesGestion update(PlanesGestion planesGestion) {
        return this.planesGestionDao.update(planesGestion);
    }

    /**
     * Finds a single row in the PlanesGestion table.
     *
     * @param planesGestion
     *            PlanesGestion
     * @return PlanesGestion
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, isolation = Isolation.READ_COMMITTED)
    public PlanesGestion find(PlanesGestion planesGestion) {
        PlanesGestion planes = new PlanesGestion();
        Integer tipoEntidad = 0;
        String usuarioConectado = null;
        if (UtilSeguridad.getUsuarioConectado().isTecnicoEntidad()) {
            usuarioConectado = Constantes.USUARIO_TEC_ENTIDAD;
            Entidades entidad = UtilSeguridad.getUsuarioConectado().getTecnicosEntidad().getEntidadPrincipal();
            tipoEntidad = entidad.getTipoEntidad();
            planesGestion.setPlanesEstrategicos(new PlanesEstrategicos());
            planesGestion.getPlanesEstrategicos()
                    .setCodTecnico(UtilSeguridad.getUsuarioConectado().getTecnicosEntidad().getCodtecnico());
            planesGestion.getPlanesEstrategicos().setEntidad(new Entidades());
            planesGestion.getPlanesEstrategicos().getEntidad().setTipoEntidad(tipoEntidad);
        } else if (UtilSeguridad.getUsuarioConectado().isTecnicoHps()) {
            usuarioConectado = Constantes.USUARIO_HPS;
        }
        planesGestion.setUsuarioConectado(usuarioConectado);
        planes = this.planesGestionDao.find(planesGestion);
        if (planes.getPlanesEstrategicos().getEntidad() == null) {
            planesGestion.setPlanesEstrategicos(new PlanesEstrategicos());
            planesGestion.getPlanesEstrategicos().setEntidad(new Entidades());
        }
        planes.getPlanesEstrategicos().getEntidad().setTipoEntidad(tipoEntidad);

        return planes;

    }

    /**
     * Deletes a single row in the PlanesGestion table.
     *
     * @param planesGestion
     *            PlanesGestion
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Throwable.class)
    public void remove(PlanesGestion planesGestion) {
        this.planesGestionDao.remove(planesGestion);
    }

    /**
     * Actualiza la fecha de actualizacion del plan de gestión
     *
     * @param planesGestion
     *            PlanesGestion planesGestion
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Throwable.class)
    public void updateActualizar(PlanesGestion planesgestion) {
        this.planesGestionDao.updateActualizar(planesgestion);
    }

    /**
     * Actualiza la fecha de actualizacion del plan de gestión
     *
     * @param planesGestion
     *            PlanesGestion planesGestion
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Throwable.class)
    public void updateActualizar(AccionesPg accionesPg) {
        this.planesGestionDao.updateActualizar(accionesPg);
    }
    
    /**
     * Finds a list of rows in the PlanesGestion table.
     *
     * @param planesGestion
     *            PlanesGestion
     * @param jqGridRequestDto
     *            JQGridRequestDto
     * @return List<PlanesGestion>
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, isolation = Isolation.READ_COMMITTED)
    public List<PlanesGestion> findAll(PlanesGestion planesGestion, JQGridRequestDto jqGridRequestDto) {
        return this.planesGestionDao.findAll(planesGestion, jqGridRequestDto);
    }

    /**
     * Finds rows in the PlanesGestion table using like.
     *
     * @param planesGestion
     *            PlanesGestion
     * @param jqGridRequestDto
     *            JQGridRequestDto
     * @param startsWith
     *            Boolean
     * @return List<PlanesGestion>
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, isolation = Isolation.READ_COMMITTED)
    public List<PlanesGestion> findAllLike(PlanesGestion planesGestion, JQGridRequestDto jqGridRequestDto,
            Boolean startsWith) {
        return this.planesGestionDao.findAllLike(planesGestion, jqGridRequestDto, startsWith);
    }

    /*
     * OPERACIONES RUP_TABLE
     */

    /**
     * Removes rows from the PlanesGestion table.
     *
     * @param filterPlanesGestion
     *            PlanesGestion
     * @param jqGridRequestDto
     *            JQGridRequestDto
     * @param startsWith
     *            Boolean
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Throwable.class)
    public void removeMultiple(PlanesGestion filterPlanesGestion, JQGridRequestDto jqGridRequestDto,
            Boolean startsWith) {
        this.planesGestionDao.removeMultiple(filterPlanesGestion, jqGridRequestDto, startsWith);
    }

    /**
     * Filter method in the PlanesGestion table.
     *
     * @param filterPlanesGestion
     *            PlanesGestion
     * @param jqGridRequestDto
     *            JQGridRequestDto
     * @param startsWith
     *            Boolean
     * @return JQGridResponseDto<PlanesGestion>
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, isolation = Isolation.READ_COMMITTED)
    public JQGridResponseDto<PlanesGestion> filter(PlanesGestion filterPlanesGestion, JQGridRequestDto jqGridRequestDto,
            Boolean startsWith) {
        List<PlanesGestion> listaPlanesGestion = this.planesGestionDao.findAllLike(filterPlanesGestion,
                jqGridRequestDto, false);
        Long recordNum = this.planesGestionDao
                .findAllLikeCount(filterPlanesGestion != null ? filterPlanesGestion : new PlanesGestion(), false);
        if (jqGridRequestDto.getMultiselection().getSelectedIds() != null) {
            List<TableRowDto<PlanesGestion>> reorderSelection = this.planesGestionDao
                    .reorderSelection(filterPlanesGestion, jqGridRequestDto, startsWith);
            return new JQGridResponseDto<PlanesGestion>(jqGridRequestDto, recordNum, listaPlanesGestion,
                    reorderSelection);
        }
        return new JQGridResponseDto<PlanesGestion>(jqGridRequestDto, recordNum, listaPlanesGestion);
    }

    /**
     * 
     * @param filterPlanesGestion
     * @param jqGridRequestDto
     * @param startsWith
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, isolation = Isolation.READ_COMMITTED)
    public JQGridResponseDto<PlanesGestion> filterCopiar(PlanesGestion filterPlanesGestion,
            JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
        List<PlanesGestion> listaPlanesGestion = this.planesGestionDao.findAllLikeCopiar(filterPlanesGestion,
                jqGridRequestDto, false);
        Long recordNum = this.planesGestionDao
                .findAllLikeCopiarCount(filterPlanesGestion != null ? filterPlanesGestion : new PlanesGestion(), false);
        if (jqGridRequestDto.getMultiselection().getSelectedIds() != null) {
            List<TableRowDto<PlanesGestion>> reorderSelection = this.planesGestionDao
                    .reorderSelection(filterPlanesGestion, jqGridRequestDto, startsWith);
            return new JQGridResponseDto<PlanesGestion>(jqGridRequestDto, recordNum, listaPlanesGestion,
                    reorderSelection);
        }
        return new JQGridResponseDto<PlanesGestion>(jqGridRequestDto, recordNum, listaPlanesGestion);
    }

    /**
     * Reorder the selection made in PlanesGestion table.
     *
     * @param filterPlanesGestion
     *            PlanesGestion
     * @param jqGridRequestDto
     *            JQGridRequestDto
     * @param startsWith
     *            Boolean
     * @return Object
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, isolation = Isolation.READ_COMMITTED)
    public Object reorderSelection(PlanesGestion filterPlanesGestion, JQGridRequestDto jqGridRequestDto,
            Boolean startsWith) {
        return this.planesGestionDao.reorderSelection(filterPlanesGestion, jqGridRequestDto, startsWith);
    }

    /**
     * Crea una copia del plan de gestión
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Throwable.class)
    public PlanesGestion crearCopiaPlanGestion(PlanesGestion planesGestion) {
        /*
         * PlanesGestion planesGestionSinPLan = new PlanesGestion();
         * planesGestionSinPLan.setPlanesEstrategicos(planesGestion. getPlanesEstrategicos());
         * planesGestionSinPLan.setAnyo(planesGestion.getAnyo());
         * planesGestionSinPLan.setUsuarioConectado(planesGestion. getUsuarioConectado());
         * planesGestionSinPLan.setCodplang(null);
         */
        /*
         * 24012018 Ahora un mismo plan estratégico puede tener asociado mas un plan de gestión para
         * el mismo año. List<PlanesGestion> listGestion =
         * this.planesGestionDao.findAll(planesGestionSinPLan, null); if (!listGestion.isEmpty()) {
         * List<ErrorField> listaErrores = new ArrayList<ErrorField>(); listaErrores.add(new
         * ErrorField("planEstrategico.anio.inicio", "validacion.existeRegistro")); throw new
         * ErrorGenericoException(listaErrores); }
         */
        Integer codplangorigen = planesGestion.getCodplang();
        planesGestion = this.planesGestionDao.add(planesGestion);
        Integer codplangdestino = planesGestion.getCodplang();
        Integer nuevoPlanId = 0;
        if (codplangdestino != null && codplangdestino.intValue() != 0) {
            nuevoPlanId = this.planesGestionDao.crearCopiaPlanGestion(codplangorigen, codplangdestino);
        }
        planesGestion.setCodplang(nuevoPlanId);
        return planesGestion;
    }

}
