package com.fp.frontend.controller.armas.lov;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import org.primefaces.context.RequestContext;

import com.fp.dto.Request;
import com.fp.dto.Response;
import com.fp.dto.query.DtoQuery;
import com.fp.dto.query.Filter;
import com.fp.dto.query.SubQuery;
import com.fp.frontend.controller.AbstractController;
import com.fp.frontend.enums.EnumLovOption;
import com.fp.frontend.helper.CallerHelper;
import com.fp.frontend.helper.MessageHelper;
import com.fp.persistence.parmas.ins.TarmPlanificacionInspeccion;
import com.fp.persistence.parmas.ins.TarmPlanificacionTramite;

/**
 * Clase controladora del lov asociado al bean TgeneCatalog.
 *
 * @author c.p.
 * @version 2.1
 */
@ManagedBean
@ViewScoped
public class PlanificacionTramiteLovController extends AbstractController<TarmPlanificacionTramite> {

    private static final long serialVersionUID = 1L;
    String centrocontrol;

    public PlanificacionTramiteLovController() throws Exception {
        super(TarmPlanificacionTramite.class);
    }

    @PostConstruct
    private void postconstruct() {
        this.init();
        try {
            centrocontrol = CallerHelper.getLovParameter("centrocontrol");
//			if (centrocontrol != null) {
//	            super.addFilter("personcode", centrocontrol);f
//	        }
            super.startQuery();
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    /**
     * Incializa el controlador, cuando se esta utilizando una pagina que utliza
     * el controlador.
     */
    private void init() {
        try {
            this.recperpage = 15; // Cambiar al # reg a mirar.
            this.lrecord = new ArrayList<>();
            this.beanalias = "CATALOGLOV";
        } catch (Exception e) {
            MessageHelper.setMessageError(e);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void querydatabase() {
        try {
            if (centrocontrol != null) {
                Request request = this.callerhelper.getRequest();
                DtoQuery dto = super.getDtoQuery(true);
                dto.setOrderby("t.mes , 9 ");

                Filter filtro = new Filter();
                filtro.setSql("(inspeccion is null or inspeccion != 'Y') and cplanificacion in (select o.pk from TarmPlanificacionInspeccion o where o.ccentrocontrol='" + centrocontrol.trim() + "' and aprobada='Y')");
                dto.addFiltro(filtro);

                SubQuery subqueryName = new SubQuery("TcustPersonDetail", "name", "name",
                        " i.pk.personcode = (select o.personcode from TarmDocumentoHabilitante o where o.pk=t.cdocumento)"
                        + " and i.pk.dateto = to_date('2999-12-31', 'YYYY-MM-DD')");
                dto.addSubQuery(subqueryName);

                SubQuery subqueryCodigoPlanificacion = new SubQuery("TarmPlanificacionInspeccion", "codigo", "codigoplanificacion", " i.pk = t.cplanificacion");
                dto.addSubQuery(subqueryCodigoPlanificacion);

                SubQuery subqueryPersoncode = new SubQuery("TarmDocumentoHabilitante", "personcode", "personcode", " i.pk = t.cdocumento");
                dto.addSubQuery(subqueryPersoncode);

                SubQuery subqueryIdentificacion = new SubQuery("TcustPersonDetail", "identification", "identification",
                        " i.pk.personcode = (select o.personcode from TarmDocumentoHabilitante o where o.pk=t.cdocumento)"
                        + " and i.pk.dateto = to_date('2999-12-31', 'YYYY-MM-DD')");
                dto.addSubQuery(subqueryIdentificacion);

                SubQuery subqueryTramite = new SubQuery("TgeneCatalogDetail", "description", "tramite",
                        " i.pk.catalog =   (select o.tipotramite        from TarmTramite o where o.pk=t.ctramite) "
                        + " and i.pk.catalogcode=(select o.tipotramitecodigo from TarmTramite o where o.pk=t.ctramite)");
                dto.addSubQuery(subqueryTramite);

                SubQuery subqueryCategoria = new SubQuery("TgeneCatalogDetail", "description", "categoria",
                        " i.pk.catalog =   (select o.categoria       from TarmTramite o where o.pk=t.ctramite) "
                        + " and i.pk.catalogcode=(select o.categoriacodigo from TarmTramite o where o.pk=t.ctramite)");
                dto.addSubQuery(subqueryCategoria);

                SubQuery subqueryUsoActividad = new SubQuery("TgeneCatalogDetail", "description", "usoactividad",
                        " i.pk.catalog =   (select o.usoactividad       from TarmTramite o where o.pk=t.ctramite) "
                        + " and i.pk.catalogcode=(select o.usoactividadcodigo from TarmTramite o where o.pk=t.ctramite)");
                dto.addSubQuery(subqueryUsoActividad);

                HashMap<String, DtoQuery> mtables = new HashMap<String, DtoQuery>();
                mtables.put(this.beanalias, dto); // permite adicionar mas de una tabla.

                request.setQueryTables(mtables);

                Response resp = this.callerhelper.executeQuery(request);

                if (resp.getResponseCode().compareTo(Response.RESPONSE_OK) != 0) {
                    this.lrecord = new ArrayList<TarmPlanificacionTramite>();
                    MessageHelper.setMessageError(resp);
                } else {
                    this.lrecord = (List<TarmPlanificacionTramite>) resp.get(this.beanalias);
                    super.postQuery(this.lrecord);
                }
            } else {
                MessageHelper.setMessageError("NO TIENE ASIGNADO UN CENTRO DE CONTROL");
            }
        } catch (Throwable e) {
            MessageHelper.setMessageError(e);
        }
    }

    public void setcatalog() {
        // se utiliza en la pagina del lov.
        RequestContext.getCurrentInstance().closeDialog(this.record);
    }

    public void setcatalog(TarmPlanificacionTramite tarmPlanificacionTramite) {
        // se utiliza en la pagina del lov.
        RequestContext.getCurrentInstance().closeDialog(tarmPlanificacionTramite);
    }

    public static void openLov(Map<String, List<String>> params) {
        Map<String, Object> options = new HashMap<String, Object>();
        options.put(EnumLovOption.MODAL.getLabel(), true);
        options.put(EnumLovOption.HEIGHT.getLabel(), 450);
        options.put(EnumLovOption.WIDTH.getLabel(), 700);
        options.put(EnumLovOption.RESIZABLE.getLabel(), false);

        RequestContext.getCurrentInstance().openDialog("/pages/armas/lov/planificacionTramiteLov.xhtml", options, params);
    }
}
