package com.rjconsultores.ventaboletos.web.gui.controladores.tarifas;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.util.resource.Labels;
import org.zkoss.zhtml.Messagebox;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zul.Button;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.Paging;
import org.zkoss.zul.Textbox;

import com.rjconsultores.ventaboletos.entidad.ClaseServicio;
import com.rjconsultores.ventaboletos.entidad.OrgaoConcedente;
import com.rjconsultores.ventaboletos.entidad.TarifaKm;
import com.rjconsultores.ventaboletos.entidad.TaxaEmbarqueKm;
import com.rjconsultores.ventaboletos.service.ClaseServicioService;
import com.rjconsultores.ventaboletos.service.OrgaoConcedenteService;
import com.rjconsultores.ventaboletos.service.TarifaKmService;
import com.rjconsultores.ventaboletos.service.TaxaEmbarqueKmService;
import com.rjconsultores.ventaboletos.utilerias.UsuarioLogado;
import com.rjconsultores.ventaboletos.web.utilerias.MyComboboxEstandar;
import com.rjconsultores.ventaboletos.web.utilerias.MyGenericForwardComposer;
import com.rjconsultores.ventaboletos.web.utilerias.MyListbox;
import com.rjconsultores.ventaboletos.web.utilerias.MyTextboxDecimal;
import com.rjconsultores.ventaboletos.web.utilerias.paginacion.HibernateSearchObject;
import com.rjconsultores.ventaboletos.web.utilerias.paginacion.PagedListWrapper;
import com.rjconsultores.ventaboletos.web.utilerias.render.RenderTarifaKm;
import com.rjconsultores.ventaboletos.web.utilerias.render.RenderTaxaEmbarqueKm;
import com.rjconsultores.ventaboletos.web.utilerias.render.RenderTaxaEmbarqueOrgao;

@Controller("editarTarifaKmController")
@Scope("prototype")
public class EditarTarifaKmController extends MyGenericForwardComposer {

	private static final long serialVersionUID = 1L;
	@Autowired
	private transient PagedListWrapper<OrgaoConcedente> plwOrgao;
	private MyListbox tarifaKmMyListBox;
	private Set<TarifaKm> lsTarifaKm;
//	private Paging pagingTaxaEmbarqueKm;
//	private Textbox txtOrgao;
	private List<ClaseServicio> lsClase;
	@Autowired
	private ClaseServicioService claseService;
	@Autowired
    private OrgaoConcedenteService orgaoConcedenteService;
	private MyComboboxEstandar cmbClase;
	@Autowired
    private TarifaKmService tarifaKmService;
	private Button btnAdicionarTarifaKm;
	private Button btnRemoverTarifaKm;
	private OrgaoConcedente orgao;
	private MyTextboxDecimal txtValor;
	private MyTextboxDecimal txtKm;
	private static Logger log = Logger.getLogger(EditarTarifaKmController.class);
	
	

//	public Textbox getTxtOrgao() {
//		return txtOrgao;
//	}
//
//	public void setTxtOrgao(Textbox txtOrgao) {
//		this.txtOrgao = txtOrgao;
//	}

	

	public List<ClaseServicio> getLsClase() {
		return lsClase;
	}

	public Set<TarifaKm> getLsTarifaKm() {
		return lsTarifaKm;
	}

	public void setLsTarifaKm(Set<TarifaKm> lsTarifaKm) {
		this.lsTarifaKm = lsTarifaKm;
	}

	public void setLsClase(List<ClaseServicio> lsClase) {
		this.lsClase = lsClase;
	}

	public ClaseServicioService getClaseService() {
		return claseService;
	}

	public void setClaseService(ClaseServicioService claseService) {
		this.claseService = claseService;
	}

	public MyComboboxEstandar getCmbClase() {
		return cmbClase;
	}

	public void setCmbClase(MyComboboxEstandar cmbClase) {
		this.cmbClase = cmbClase;
	}
	
	

//	public Paging getPagingTaxaEmbarqueKm() {
//		return pagingTaxaEmbarqueKm;
//	}
//
//	public void setPagingTaxaEmbarqueKm(Paging pagingTaxaEmbarqueKm) {
//		this.pagingTaxaEmbarqueKm = pagingTaxaEmbarqueKm;
//	}

	public OrgaoConcedenteService getOrgaoConcedenteService() {
		return orgaoConcedenteService;
	}

	public void setOrgaoConcedenteService(OrgaoConcedenteService orgaoConcedenteService) {
		this.orgaoConcedenteService = orgaoConcedenteService;
	}

	public TarifaKmService getTarifaKmService() {
		return tarifaKmService;
	}

	public void setTarifaKmService(TarifaKmService tarifaKmService) {
		this.tarifaKmService = tarifaKmService;
	}

	public Button getBtnAdicionarTarifaKm() {
		return btnAdicionarTarifaKm;
	}

	public void setBtnAdicionarTarifaKm(Button btnAdicionarTarifaKm) {
		this.btnAdicionarTarifaKm = btnAdicionarTarifaKm;
	}

	public PagedListWrapper<OrgaoConcedente> getPlwOrgao() {
		return plwOrgao;
	}

	public void setPlwOrgao(PagedListWrapper<OrgaoConcedente> plwOrgao) {
		this.plwOrgao = plwOrgao;
	}

	@Override
	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);
		
		lsClase = claseService.obtenerTodos();
		
		orgao = orgaoConcedenteService.obtenerID(OrgaoConcedente.CODIGO_ARTESP);//artesp = 21
		//orgao = orgaoConcedenteService.buscar("ARTESP").get(0);
		
		tarifaKmMyListBox.setItemRenderer(new RenderTarifaKm());
		//lsTarifaKm = new TreeSet<TarifaKm>();
		
		tarifaKmMyListBox.setData(new ArrayList());//lsTarifaKm) );
		
//		if (orgao != null && orgao.getOrgaoConcedenteId() != null) {
//			
//			if(null != cmbClase.getSelectedItem().getValue() && 
//					(cmbClase.getSelectedItem().getValue() instanceof ClaseServicio) )
//			{
//				ClaseServicio c = (ClaseServicio)cmbClase.getSelectedItem().getValue();
//			}
			
//            lsTarifaKm = tarifaKmService.buscarPorOrgaoAndClasse(orgao, claseId);
//            taxaEmbarqueKmArtespList.setData(lsTaxaEmbarqueKmArtesp);
//            cmbOrgao.setDisabled(Boolean.TRUE);
//            cmbOrgao.setValue(orgao.getDescOrgao());
//        }
//		TaxaEmbarqueKm t = new TaxaEmbarqueKm() ;
//		lsTaxaEmbarqueKmArtesp.add(t);
//		taxaEmbarqueKmArtespList.setData(lsTaxaEmbarqueKmArtesp);
		
		//orgaoConcedenteService.
		
//
//		taxaEmbarqueKmList.setItemRenderer(new RenderTaxaEmbarqueOrgao());
//		taxaEmbarqueKmList.addEventListener("onDoubleClick", new EventListener() {
//
//			@Override
//			public void onEvent(Event event) throws Exception {
//				OrgaoConcedente c = (OrgaoConcedente) taxaEmbarqueKmList.getSelected();
//				verTaxaEmbarqueKm(c);
//			}
//		});
//
//		refreshLista();
//
//		txtOrgao.focus();
	}

	private void verTaxaEmbarqueKm(OrgaoConcedente o) {
//		if (o == null) {
//			return;
//		}
//
//		Map args = new HashMap();
//		args.put("orgao", o);
//		args.put("taxaEmbarqueKmList", taxaEmbarqueKmArtespList);
//
//		openWindow("/gui/tarifas/editarTaxaEmbarqueKm.zul",
//				Labels.getLabel("busquedaTaxaEmbarqueKmController.window.title"),
//				args, MODAL);
	}

	private void refreshLista() {

//		HibernateSearchObject<OrgaoConcedente> taxaEmbarqueKmBusqueda = new HibernateSearchObject<OrgaoConcedente>(OrgaoConcedente.class, pagingTaxaEmbarqueKm.getPageSize());
//
//		taxaEmbarqueKmBusqueda.addFilterEqual("activo", Boolean.TRUE);
//
//		if (!txtOrgao.getValue().equals("")) {
//			taxaEmbarqueKmBusqueda.addFilterLike("descOrgao", "%" + txtOrgao.getText().trim().concat("%"));
//		}
//
//		taxaEmbarqueKmBusqueda.addSortAsc("descOrgao");
//
//		plwOrgao.init(taxaEmbarqueKmBusqueda, taxaEmbarqueKmList, pagingTaxaEmbarqueKm);
//
//		if (taxaEmbarqueKmList.getData().length == 0) {
//			try {
//				Messagebox.show(Labels.getLabel("MSG.ningunRegistro"),
//						Labels.getLabel("busquedaTaxaEmbarqueKmController.window.title"),
//						Messagebox.OK, Messagebox.INFORMATION);
//			} catch (InterruptedException ex) {
//			}
//		}
	}
	
	private void limparInput() {
        txtKm.setConstraint("");
        txtValor.setConstraint("");
        txtKm.setText("");
        txtValor.setText("");
        txtKm.setConstraint("no empty, no zero, no negative, /[0-9]+(\\,[0-9][0-9]?)?/");
        txtValor.setConstraint("no empty, no zero, no negative, /[0-9]+(\\,[0-9][0-9]?)?/");
    }
	
	public void onClick$btnAdicionarTarifaKm(Event ev) throws InterruptedException {
		
		ClaseServicio c = (ClaseServicio)cmbClase.getSelectedItem().getValue();
        
        if (lsTarifaKm.isEmpty()) {
        	List<TarifaKm> ar = tarifaKmService.buscarPorOrgaoAndClasse(orgao, c);
        	lsTarifaKm= new TreeSet(ar);
            //lsTarifaKm = tarifaKmService.buscarPorOrgaoAndClasse(orgao, c);
            if(lsTarifaKm.isEmpty()){lsTarifaKm = new TreeSet<TarifaKm>();}
            tarifaKmMyListBox.setData(new ArrayList(lsTarifaKm) );
        }

        //ChecandoDuplicado
        boolean existe = false;
        for (TarifaKm km : lsTarifaKm) {
            if (km.getKmate().equals(txtKm.getValue())) {
                existe = true;
            }
        }

        if (existe) {
            Messagebox.show(
                    Labels.getLabel("editarTaxaEmbarqueKmController.MSG.existe"),
                    Labels.getLabel("editarTaxaEmbarqueKmController.window.title"),
                    Messagebox.OK, Messagebox.INFORMATION);
            
            limparInput();
            
            return;
        }
        

        TarifaKm km = new TarifaKm();
        km.setOrgaoconcedenteId((orgao) );
        km.setKmate(txtKm.getValueDecimal());
        km.setValortaxa(txtValor.getValueDecimal());
        km.setActivo(true);
        km.setFecmodif(Calendar.getInstance().getTime());
        km.setUsuarioId(UsuarioLogado.getUsuarioLogado().getUsuarioId());
        km.setClaseServicio(c);

        lsTarifaKm.add(km);
        tarifaKmMyListBox.setData(new ArrayList(lsTarifaKm));

        limparInput();

    }
	
	public void onClick$btnRemoverTarifaKm(Event ev) {
		TarifaKm t = (TarifaKm) tarifaKmMyListBox.getSelected();
        if (t != null) {
            t.setActivo(Boolean.FALSE);
            t.setUsuarioId(UsuarioLogado.getUsuarioLogado().getUsuarioId());
            t.setFecmodif(Calendar.getInstance().getTime());
            if(null != t.getTarifakmId()) { tarifaKmService.actualizacion(t); }
            
            lsTarifaKm.remove(t);
            tarifaKmMyListBox.setData(new ArrayList(lsTarifaKm));
        }
    }
	
	public void onClick$btnSalvar(Event ev) throws InterruptedException {

        try {
            if (lsTarifaKm.isEmpty()) {
                Messagebox.show(
                        Labels.getLabel("editarTarifaKmController.MSG.necessitaInfromar.value"),
                        Labels.getLabel("editarTarifaKmController.window.title"),
                        Messagebox.OK, Messagebox.EXCLAMATION);
                return;
            }

            for (TarifaKm km : lsTarifaKm) {
                if (km.getTarifakmId() == null) {
                    tarifaKmService.suscribir(km);
                }
            }
            Messagebox.show(
                    Labels.getLabel("editarTarifaKmController.MSG.suscribirOK"),
                    Labels.getLabel("editarTarifaKmController.window.title"),
                    Messagebox.OK, Messagebox.INFORMATION);

            closeWindow();


        } catch (Exception ex) {
            log.error("",ex);
            Messagebox.show(
                    Labels.getLabel("MSG.Error"),
                    Labels.getLabel("editarTarifaKmController.window.title"),
                    Messagebox.OK, Messagebox.ERROR);
        }
    }
	
	public void onChange$cmbClase(Event ev) {
		//cambiarPantallaTipo();    
		if (orgao != null && orgao.getOrgaoConcedenteId() != null && ( null != cmbClase.getSelectedItem().getValue()) ) {
			ClaseServicio c = (ClaseServicio)cmbClase.getSelectedItem().getValue();
			List ar = tarifaKmService.buscarPorOrgaoAndClasse(orgao, c);
			System.out.println();
            lsTarifaKm = new TreeSet(ar);
            tarifaKmMyListBox.setData(new ArrayList( lsTarifaKm));
            if(c.getClaseservicioId() == -1){btnAdicionarTarifaKm.setDisabled(Boolean.TRUE);}
            else{btnAdicionarTarifaKm.setDisabled(Boolean.FALSE);}
//            cmbOrgao.setDisabled(Boolean.TRUE);
//            cmbOrgao.setValue(orgao.getDescOrgao());
        }
	}

	public void onClick$btnPesquisa(Event ev) {
		refreshLista();
	}

	public void onClick$btnRefresh(Event ev) {
		refreshLista();
	}

	public void onClick$btnNovo(Event ev) {
		verTaxaEmbarqueKm(new TaxaEmbarqueKm());
	}

	public MyListbox getTarifaKmMyListBox() {
		return tarifaKmMyListBox;
	}

	public void setTarifaKmMyListBox(MyListbox tarifaKmMyListBox) {
		this.tarifaKmMyListBox = tarifaKmMyListBox;
	}
	
	public OrgaoConcedente getOrgao() {
		return orgao;
	}

	public void setOrgao(OrgaoConcedente orgao) {
		this.orgao = orgao;
	}
	
	public MyTextboxDecimal getTxtKm() {
		return txtKm;
	}

	public void setTxtKm(MyTextboxDecimal txtKm) {
		this.txtKm = txtKm;
	}

	public MyTextboxDecimal getTxtValor() {
		return txtValor;
	}

	public void setTxtValor(MyTextboxDecimal txtValor) {
		this.txtValor = txtValor;
	}
	
	public Button getBtnRemoverTarifaKm() {
		return btnRemoverTarifaKm;
	}

	public void setBtnRemoverTarifaKm(Button btnRemoverTarifaKm) {
		this.btnRemoverTarifaKm = btnRemoverTarifaKm;
	}

	private void verTaxaEmbarqueKm(TaxaEmbarqueKm tx) {
//		if (tx == null) {
//			return;
//		}
//
//		Map args = new HashMap();
//		args.put("orgao", null);
//		args.put("taxaEmbarqueKm", tx);
//		args.put("taxaEmbarqueKmList", taxaEmbarqueKmArtespList);
//
//		openWindow("/gui/tarifas/editarTaxaEmbarqueKm.zul",
//				Labels.getLabel("busquedaTaxaEmbarqueKmController.window.title"),
//				args, MODAL);
	}
}
