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

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

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.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.Checkbox;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Longbox;
import org.zkoss.zul.Paging;
import org.zkoss.zul.Textbox;

import com.rjconsultores.ventaboletos.entidad.Parada;
import com.rjconsultores.ventaboletos.entidad.Voucher;
import com.rjconsultores.ventaboletos.service.ParadaService;
import com.rjconsultores.ventaboletos.web.utilerias.MyGenericForwardComposer;
import com.rjconsultores.ventaboletos.web.utilerias.MyListbox;
import com.rjconsultores.ventaboletos.web.utilerias.paginacion.HibernateSearchObject;
import com.rjconsultores.ventaboletos.web.utilerias.paginacion.PagedListWrapper;
import com.rjconsultores.ventaboletos.web.utilerias.render.RenderPadrao;

@Controller("busquedaVoucherController")
@Scope("prototype")
public class BusquedaVoucherController extends MyGenericForwardComposer {

	private static Logger log = LogManager.getLogger(BusquedaVoucherController.class); 
	private static final long serialVersionUID = 1L;
	@Autowired
	private transient PagedListWrapper<Voucher> plwpagingVoucher;
	@Autowired
	private ParadaService paradaService;
	
	private MyListbox voucherList;
	private Paging pagingVoucher;
	private Longbox txtNumVoucher;
	private Textbox txtNumContrato;
	private Textbox txtNit;
	private Textbox txtNome;
	private Datebox datInicial;
	private Datebox datFinal;
	private Combobox cmbOrigem;
	private Combobox cmbDestino;
	private Checkbox chkEmitido;
	private Checkbox chkLegalizado;
	private Checkbox chkFaturado;
	private Checkbox chkCancelado;

	@Override
	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);

		voucherList.setItemRenderer(new RenderPadrao<Voucher>(Voucher.class));
		voucherList.addEventListener("onDoubleClick", new EventListener() {

			@Override
			public void onEvent(Event event) throws Exception {
				Voucher cc = (Voucher) voucherList.getSelected();
				verVoucher(cc);
			}
		});

		refreshLista();
		
		txtNumVoucher.focus();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void verVoucher(Voucher gc) {
		if (gc == null) {
			return;
		}

		Map args = new HashMap();
		args.put("voucher", gc);
		args.put("voucherList", voucherList);

		openWindow("/gui/configuraciones_comerciales/negcorporativos/editarVoucher.zul",
				Labels.getLabel("editarVoucherController.window.title"), args, MODAL);
	}

	private void refreshLista() {
		HibernateSearchObject<Voucher> configBusqueda = new HibernateSearchObject<Voucher>(Voucher.class,pagingVoucher.getPageSize());

		if (txtNumVoucher.getText().length() > 0) {
			configBusqueda.addFilterEqual("voucherId", txtNumVoucher.getValue());
		}
		
		if (txtNumContrato.getText().length() > 0) {
			configBusqueda.addFilterEqual("numContrato", txtNumContrato.getText());
		}
		
		if (txtNit.getText().length() > 0) {
			configBusqueda.addFilterEqual("transportadora.nit", txtNit.getText());
		}
		
		if (txtNome.getText().length() > 0) {
			configBusqueda.addFilterLike("transportadora.nomeTransportadora", "%" + txtNome.getText().trim().concat("%"));
		}
		
		if (datInicial.getValue() != null ) {
			configBusqueda.addFilterGreaterOrEqual("dataValidade", datInicial.getValue());
		}
		
		if (datFinal.getValue() != null ) {
			configBusqueda.addFilterLessOrEqual("dataValidade", datFinal.getValue());
		}
		
		if (cmbOrigem.getSelectedItem() != null ) {
			Parada origem = (Parada)cmbOrigem.getSelectedItem().getValue();
			configBusqueda.addFilterEqual("origenId", origem.getParadaId());
		}
		
		if (cmbDestino.getSelectedItem() != null ) {
			Parada destino = (Parada)cmbDestino.getSelectedItem().getValue();
			configBusqueda.addFilterEqual("destinoId", destino.getParadaId());
		}
		
		List<Integer> statusList = new ArrayList<Integer>();
		if(chkEmitido.isChecked()) 
			statusList.add( Integer.valueOf( chkEmitido.getValue()));
		
		if(chkLegalizado.isChecked()) 
			statusList.add( Integer.valueOf( chkLegalizado.getValue()));
		
		if(chkFaturado.isChecked()) 
			statusList.add( Integer.valueOf( chkFaturado.getValue()));
		
		if(chkCancelado.isChecked()) 
			statusList.add( Integer.valueOf( chkCancelado.getValue()));

		if(! statusList.isEmpty() ) {
			configBusqueda.addFilterIn( "status", statusList );
		}

		
		configBusqueda.addFilterEqual("activo", Boolean.TRUE);
		configBusqueda.addSortAsc("voucherId");

		plwpagingVoucher.init(configBusqueda, voucherList, pagingVoucher);

		if (voucherList.getData().length == 0) {
			try {
				Messagebox.show(Labels.getLabel("MSG.ningunRegistro"),
						Labels.getLabel("busquedaVoucherController.window.title"),
						Messagebox.OK, Messagebox.INFORMATION);
			} catch (InterruptedException ex) {
				log.error(ex);
			}
		}else {
			preencheComplemento();
		}
	}

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

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

	public void onClick$btnNovo(Event ev) {
		verVoucher(new Voucher());
	}
	
	private void preencheComplemento() {
		for (Object item : voucherList.getListData()) {
			Voucher obj = (Voucher)item;
			if( StringUtils.isEmpty(obj.getDescOrigem())) {
				obj.setDescOrigem( paradaService.obtenerID(obj.getOrigenId()).getDescparada() );
			}
			
			if( StringUtils.isEmpty(obj.getDescDestino() )) {
				obj.setDescDestino( paradaService.obtenerID(obj.getDestinoId()).getDescparada() );
			}
		}
	}	
}
