/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rjconsultores.ventaboletos.web.gui.controladores.catalogos;

import java.util.Calendar;
import java.util.List;

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.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zul.Button;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Comboitem;
import org.zkoss.zul.Decimalbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.Radio;
import org.zkoss.zul.Row;

import com.rjconsultores.ventaboletos.entidad.FormaPago;
import com.rjconsultores.ventaboletos.enums.IndRestricaoFormaPago;
import com.rjconsultores.ventaboletos.enums.TipoCarteiraDigital;
import com.rjconsultores.ventaboletos.enums.TipoFormapago;
import com.rjconsultores.ventaboletos.service.FormaPagoService;
import com.rjconsultores.ventaboletos.utilerias.ApplicationProperties;
import com.rjconsultores.ventaboletos.utilerias.CustomEnum;
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.MyTextbox;

/**
 *
 * @author Administrador
 */
@Controller("editarFormaPagoController")
@Scope("prototype")
public class EditarFormaPagoController extends MyGenericForwardComposer {

	private static final long serialVersionUID = 1L;
	@Autowired
	private FormaPagoService formaPagoService;
	private FormaPago formaPago;
	private MyListbox formaPagoList;
	private MyTextbox txtNome;
	private MyTextbox txtCvePago;
	private Button btnApagar;
	private BusquedaFormaPagoController busquedaFormaPagoController;
	private Checkbox chkIndRestricaoFormaPago;
	private Checkbox chkIndTransferenciaReativacao;
	private Checkbox chkCompoeTarifaETaxa;
	private Checkbox chkCompoeTarifa;
	private Radio rd1;
	private Radio rd2;
	private Radio rd3;
	private Radio rd4;
	private Radio radioImp;
	private Radio radioPor;
	private static Logger log = LogManager.getLogger(EditarFormaPagoController.class);
	private Row rowEquivalencia;
	private Row rowRestricaoFormaPago;
	private Row rowTransferenciaReativacao;
	private Row rowTarifaTaxa;
	private Row rowSomenteTarifa;
	private Row rowIndPercentualDesconto;
	private Row rowPercentualDesconto;
	private Row rowValorDesconto;
	private Decimalbox percentualDescontoBox;
	private Decimalbox valorDescontoBox;
	private boolean exibeTipoRestricaoFormaPago;
	
	private Checkbox chkIndEstorno;
	private Checkbox chkAtivaEstornoReceitaDespesaCredito;
	
	private Checkbox chkIndVoucherRodoviaria;
	
	private Row rowIdEventoExtra;
	private Row rowAtivaEstornoReceitaDespesaCredito;

	private MyComboboxEstandar cmbTipoFormapago;
	private MyComboboxEstandar cmbTipoCarteiraDigital;
	private Label lblTipoCarteiraDigital;
	private Row rowTipoCarteiraDigital;

	public FormaPago getFormaPago() {
		return formaPago;
	}

	public void setFormaPago(FormaPago formaPago) {
		this.formaPago = formaPago;
	}

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

		super.doAfterCompose(comp);
		busquedaFormaPagoController = (BusquedaFormaPagoController) Executions.getCurrent().getArg().get("busquedaFormaPagoController");
		formaPago = (FormaPago) Executions.getCurrent().getArg().get("formaPago");
		
		if (formaPago.getFormapagoId() != null){
			formaPago = formaPagoService.obtenerID(formaPago.getFormapagoId());
		}
			
		formaPagoList = (MyListbox) Executions.getCurrent().getArg().get("formaPagoList");
		popularCombobox();
		/*
		 * Somente exibe se vai ter restrição de forma de pagamento na hora da venda se não houver cvesistema.
		 * Pode ser alterado para respeitar somente as formas de pagamento especiais.
		 *
		 */
		if (formaPago.getCveSistema() != null) {
			rowRestricaoFormaPago.setVisible(false);
			rowTransferenciaReativacao.setVisible(false);
			rowTarifaTaxa.setVisible(false);
			rowSomenteTarifa.setVisible(false);
		}else if(formaPago.getIndRestricaoFormaPago() == null ||
				formaPago.getIndRestricaoFormaPago().equals(IndRestricaoFormaPago.NORMAL.getSigla())){
			rowTarifaTaxa.setVisible(false);
			rowSomenteTarifa.setVisible(false);
		}else{
			rowTarifaTaxa.setVisible(true);
			rowSomenteTarifa.setVisible(true);
			chkIndRestricaoFormaPago.setChecked(true);
			if(formaPago.getIndRestricaoFormaPago().equals(IndRestricaoFormaPago.TARIFA_E_TAXAS.getSigla())){
				chkCompoeTarifaETaxa.setChecked(true);
			}else{
				chkCompoeTarifa.setChecked(true);
			}
		}

		if (formaPago.getFormapagoId() == null) {
			btnApagar.setVisible(Boolean.FALSE);
		} else {

			if (formaPago.getIndoperacion() == null) {
				rd4.setChecked(true);
			} else if (formaPago.getIndoperacion() == 1) {
				rd1.setChecked(true);
			} else if (formaPago.getIndoperacion() == 2) {
				rd2.setChecked(true);
			} else if (formaPago.getIndoperacion() == 3) {
				rd3.setChecked(true);
			}
			
			chkIndEstorno.setChecked(formaPago.getIndProcessoEstorno());
			chkAtivaEstornoReceitaDespesaCredito.setChecked(formaPago.getIndEstornoReceitaDespesaCredito());
			chkIndVoucherRodoviaria.setChecked(formaPago.getIndVoucherRodoviaria());
			chkIndTransferenciaReativacao.setChecked(formaPago.getIndTransferenciaReativacao());

			if (formaPago.getFormapagoId() == 1) {
				cmbTipoFormapago.setDisabled(Boolean.TRUE);
			}

			if (formaPago.getFormapagoId() <= 11 || (formaPago.getFormapagoId() >= 92 && formaPago.getFormapagoId() <= 99) || formaPago.getFormapagoId() == 37 || StringUtils.isNotBlank(formaPago.getCveSistema())) {
				btnApagar.setVisible(Boolean.FALSE);
				txtNome.setDisabled(Boolean.TRUE);
				txtCvePago.setDisabled(Boolean.TRUE);

				Messagebox.show(
						Labels.getLabel("MSG.noEditabled"),
						Labels.getLabel("editarFormaPagoController.window.title"),
						Messagebox.OK, Messagebox.INFORMATION);
			}
		}

		if (!ApplicationProperties.getInstance().isCustomHabilitado(CustomEnum.MOSTRAR_EQUIVALENCIA.getDescricao())) {
			rowEquivalencia.setVisible(Boolean.FALSE);
		}

		if(formaPago != null) {
			rowIdEventoExtra.setVisible(formaPago.getIndProcessoEstorno());
		} 
		
		if(formaPago != null) {
			rowAtivaEstornoReceitaDespesaCredito.setVisible(formaPago.getIndEstornoReceitaDespesaCredito());
		} 
		
		if(formaPago.getTipoCarteiraDigital() != null) {
			cmbTipoCarteiraDigital.setValue(formaPago.getTipoCarteiraDigital().toString());
		}
		
		if(formaPago.getTipoFormapago() != null) {
			cmbTipoFormapago.setValue(formaPago.getTipoFormapago().toString());
		}

		
		if(Boolean.TRUE.equals(formaPago.getIndPercentualDesconto()) || formaPago.getIndPercentualDesconto()==null ) {
			rowPercentualDesconto.setVisible(true);
			radioPor.setChecked(true);
			rowValorDesconto.setVisible(false);
			percentualDescontoBox.setDisabled(false);
			valorDescontoBox.setDisabled(true);
			valorDescontoBox.setConstraint("no negative");
		}else {
			rowPercentualDesconto.setVisible(false);
			rowValorDesconto.setVisible(true);
			radioImp.setChecked(true);
			percentualDescontoBox.setDisabled(true);
			valorDescontoBox.setDisabled(false);
			valorDescontoBox.setConstraint("no negative");
		}
			

		exibirOcultarCampos();
		txtNome.focus();
	}

	private void popularCombobox() {
		for (TipoFormapago tipoFormapago : TipoFormapago.values()) {
			Comboitem comboItem = new Comboitem(tipoFormapago.toString());
			comboItem.setValue(tipoFormapago);
			comboItem.setParent(cmbTipoFormapago);
		}
		
		for (TipoCarteiraDigital tipoCarteiraDigital: TipoCarteiraDigital.values()) {
			Comboitem comboItem = new Comboitem(tipoCarteiraDigital.toString());
			comboItem.setValue(tipoCarteiraDigital);
			comboItem.setParent(cmbTipoCarteiraDigital);
		}
	}

	public void onCheck$chkIndRestricaoFormaPago(Event event) {
		rowTarifaTaxa.setVisible(getChkIndRestricaoFormaPago().isChecked());
		rowSomenteTarifa.setVisible(getChkIndRestricaoFormaPago().isChecked());
		chkCompoeTarifaETaxa.setChecked(true);
		chkCompoeTarifa.setChecked(false);
	}
	
	public void onChange$cmbTipoFormapago(Event event) {
		exibirOcultarCampos();
	}

	private void exibirOcultarCampos() {
		rowTipoCarteiraDigital.setVisible(false);
		cmbTipoCarteiraDigital.setVisible(false);
		lblTipoCarteiraDigital.setVisible(false);
		rowIdEventoExtra.setVisible(chkIndEstorno.isChecked());
		rowAtivaEstornoReceitaDespesaCredito.setVisible(chkAtivaEstornoReceitaDespesaCredito.isChecked());	
		
		if(cmbTipoFormapago!=null && cmbTipoFormapago.getSelectedItem() != null) {
			TipoFormapago tipoFormaPagoEscolhido = ((TipoFormapago) cmbTipoFormapago.getSelectedItem().getValue());
			
			if(TipoFormapago.CARTEIRA_DIGITAL.equals(tipoFormaPagoEscolhido)) {
				rowTipoCarteiraDigital.setVisible(true);
				cmbTipoCarteiraDigital.setVisible(true);
				lblTipoCarteiraDigital.setVisible(true);
			}
		}
	}

	public void onCheck$chkCompoeTarifaETaxa(Event event) {
		chkCompoeTarifa.setChecked(!chkCompoeTarifaETaxa.isChecked());
	}

	public void onCheck$chkCompoeTarifa(Event event) {
		chkCompoeTarifaETaxa.setChecked(!chkCompoeTarifa.isChecked());
	}

	public void onClick$btnSalvar(Event ev) throws InterruptedException {
		txtNome.getValue();
		txtCvePago.getValue();
		cmbTipoFormapago.getValue();

		try {
			if(!verificarCampos()) {
				return;
			}
			
			formaPago.setActivo(Boolean.TRUE);
			formaPago.setFecmodif(Calendar.getInstance().getTime());
			formaPago.setUsuarioId(UsuarioLogado.getUsuarioLogado().getUsuarioId());
			
			Comboitem cbTipoFormaPago = cmbTipoFormapago.getSelectedItem();
			formaPago.setTipoFormapago(null);
			if (cbTipoFormaPago != null) {
				formaPago.setTipoFormapago((TipoFormapago) cbTipoFormaPago.getValue());
			}
			
			formaPago.setTipoCarteiraDigital(null);
			if(cmbTipoCarteiraDigital.isVisible() && cmbTipoCarteiraDigital.getSelectedItem() != null ) {
				formaPago.setTipoCarteiraDigital((TipoCarteiraDigital) cmbTipoCarteiraDigital.getSelectedItem().getValue());
			}

			if (rd4.isChecked()) {
				formaPago.setIndoperacion(null);
			} else if (rd1.isChecked()) {
				formaPago.setIndoperacion(new Short("1"));
			} else if (rd2.isChecked()) {
				formaPago.setIndoperacion(new Short("2"));
			} else if (rd3.isChecked()) {
				formaPago.setIndoperacion(new Short("3"));
			}

			if(!chkIndRestricaoFormaPago.isChecked()){
				formaPago.setIndRestricaoFormaPago(IndRestricaoFormaPago.NORMAL.getSigla());
			}else{
				if(chkCompoeTarifaETaxa.isChecked()){
					formaPago.setIndRestricaoFormaPago(IndRestricaoFormaPago.TARIFA_E_TAXAS.getSigla());
				}else if(chkCompoeTarifa.isChecked()){
					formaPago.setIndRestricaoFormaPago(IndRestricaoFormaPago.SOMENTE_TARIFA.getSigla());
				}
			}
			
			if(!chkIndEstorno.isChecked()) {
				formaPago.setTipoEventoExtraId(null);
			}
			
			if(!chkAtivaEstornoReceitaDespesaCredito.isChecked()) {
				formaPago.setTipoEventoExtraIdCredito(null);
			}

			formaPago.setIndProcessoEstorno(chkIndEstorno.isChecked());
			formaPago.setIndEstornoReceitaDespesaCredito(chkAtivaEstornoReceitaDespesaCredito.isChecked());
			formaPago.setIndVoucherRodoviaria(chkIndVoucherRodoviaria.isChecked());
			formaPago.setIndTransferenciaReativacao(chkIndTransferenciaReativacao.isChecked());
			if(radioPor.isChecked()) {
				formaPago.setPercentualDesconto(percentualDescontoBox.getValue());				
				formaPago.setValorDesconto(null);
				formaPago.setIndPercentualDesconto(true);
			}else {
				formaPago.setIndPercentualDesconto(false);
				formaPago.setValorDesconto(valorDescontoBox.getValue());
				formaPago.setPercentualDesconto(null);
			}
				
			if (formaPago.getFormapagoId() == null) {
				List<FormaPago> lsFP =
						formaPagoService.buscarPorDescricao(formaPago.getDescpago());

				if (lsFP.isEmpty()) {
					formaPagoService.suscribir(formaPago);
					formaPagoList.addItemNovo(formaPago);

					Messagebox.show(
							Labels.getLabel("editarFormaPagoController.MSG.suscribirOK"),
							Labels.getLabel("editarFormaPagoController.window.title"),
							Messagebox.OK, Messagebox.INFORMATION);
				} else {
					Messagebox.show(
							Labels.getLabel("MSG.Registro.Existe"),
							Labels.getLabel("editarFormaPagoController.window.title"),
							Messagebox.OK, Messagebox.EXCLAMATION);
				}
			} else {
				formaPagoService.actualizacion(formaPago);
				formaPagoList.updateItem(formaPago);

				Messagebox.show(
						Labels.getLabel("editarFormaPagoController.MSG.suscribirOK"),
						Labels.getLabel("editarFormaPagoController.window.title"),
						Messagebox.OK, Messagebox.INFORMATION);
			}
			busquedaFormaPagoController.refreshLista();
			closeWindow();
		} catch (Exception ex) {
			log.error("editarFormaPagoController: " + ex);
			Messagebox.show(
					Labels.getLabel("MSG.Error"),
					Labels.getLabel("editarFormaPagoController.window.title"),
					Messagebox.OK, Messagebox.ERROR);
		}
	}

	private boolean verificarCampos() throws InterruptedException {
		if(cmbTipoCarteiraDigital.isVisible() && cmbTipoCarteiraDigital.getSelectedItem() == null) {
			Messagebox.show(
					Labels.getLabel("editarFormaPagoController.MSG.tipoCarteiraDigital.label"),
					Labels.getLabel("editarFormaPagoController.window.title"),
					Messagebox.OK, Messagebox.EXCLAMATION);			
			return false;
		}
		return true;
	}

	public void onClick$btnApagar(Event ev) {
		try {
			int resp = Messagebox.show(
					Labels.getLabel("editarFormaPagoController.MSG.borrarPergunta"),
					Labels.getLabel("editarFormaPagoController.window.title"),
					Messagebox.YES | Messagebox.NO, Messagebox.QUESTION);

			if (resp == Messagebox.YES) {
				formaPagoService.borrar(formaPago);

				Messagebox.show(
						Labels.getLabel("editarFormaPagoController.MSG.borrarOK"),
						Labels.getLabel("editarFormaPagoController.window.title"),
						Messagebox.OK, Messagebox.INFORMATION);

				formaPagoList.removeItem(formaPago);

				closeWindow();
			}
		} catch (Exception ex) {
			log.error(ex);
		}
	}

	public MyComboboxEstandar getCmbTipoFormapago() {
		return cmbTipoFormapago;
	}

	public void setCmbTipoFormapago(MyComboboxEstandar cmbTipoFormapago) {
		this.cmbTipoFormapago = cmbTipoFormapago;
	}

	/**
	 * @return the chkIndRestricaoFormaPago
	 */
	public Checkbox getChkIndRestricaoFormaPago() {
		return chkIndRestricaoFormaPago;
	}
	
	/**
	 * @return the chkIndTransferenciaReativacao
	 */
	public Checkbox getChkIndTransferenciaReativacao() {
		return chkIndTransferenciaReativacao;
	}

	/**
	 * @return the chkCompoeTarifaETaxa
	 */
	public Checkbox getChkCompoeTarifaETaxa() {
		return chkCompoeTarifaETaxa;
	}

	/**
	 * @return the chkCompoeTarifa
	 */
	public Checkbox getChkCompoeTarifa() {
		return chkCompoeTarifa;
	}

	/**
	 * @param chkIndTransferenciaReativacao
	 *            the chkIndTransferenciaReativacao to set
	 */
	public void setChkIndTransferenciaReativacao(Checkbox chkIndTransferenciaReativacao) {
		this.chkIndTransferenciaReativacao = chkIndTransferenciaReativacao;
	}
	
	/**
	 * @param chkIndRestricaoFormaPago
	 *            the chkIndRestricaoFormaPago to set
	 */
	public void setChkIndRestricaoFormaPago(Checkbox chkIndRestricaoFormaPago) {
		this.chkIndRestricaoFormaPago = chkIndRestricaoFormaPago;
	}

	/**
	 * @param chkCompoeTarifaETaxa
	 *            the chkCompoeTarifaETaxa to set
	 */
	public void setChkCompoeTarifaETaxa(Checkbox chkCompoeTarifaETaxa) {
		this.chkCompoeTarifaETaxa = chkCompoeTarifaETaxa;
	}

	/**
	 * @param chkCompoeTarifa
	 *            the chkCompoeTarifa to set
	 */
	public void setChkCompoeTarifa(Checkbox chkCompoeTarifa) {
		this.chkCompoeTarifa = chkCompoeTarifa;
	}

	/**
	 * @return the exibeTipoRestricaoFormaPago
	 */
	public boolean isExibeTipoRestricaoFormaPago() {
		return exibeTipoRestricaoFormaPago;
	}

	/**
	 * @param exibeTipoRestricaoFormaPago the exibeTipoRestricaoFormaPago to set
	 */
	public void setExibeTipoRestricaoFormaPago(boolean exibeTipoRestricaoFormaPago) {
		this.exibeTipoRestricaoFormaPago = exibeTipoRestricaoFormaPago;
	}

	/**
	 * @return the rowTarifaTaxa
	 */
	public Row getRowTarifaTaxa() {
		return rowTarifaTaxa;
	}

	/**
	 * @return the rowSomenteTarifa
	 */
	public Row getRowSomenteTarifa() {
		return rowSomenteTarifa;
	}

	/**
	 * @param rowTarifaTaxa the rowTarifaTaxa to set
	 */
	public void setRowTarifaTaxa(Row rowTarifaTaxa) {
		this.rowTarifaTaxa = rowTarifaTaxa;
	}

	/**
	 * @param rowSomenteTarifa the rowSomenteTarifa to set
	 */
	public void setRowSomenteTarifa(Row rowSomenteTarifa) {
		this.rowSomenteTarifa = rowSomenteTarifa;
	}

	public Checkbox getChkIndEstorno() {
		return chkIndEstorno;
	}

	public void setChkIndEstorno(Checkbox chkIndEstorno) {
		this.chkIndEstorno = chkIndEstorno;
	}

	public Checkbox getChkIndVoucherRodoviaria() {
		return chkIndVoucherRodoviaria;
	}

	public void setChkIndVoucherRodoviaria(Checkbox chkIndVoucherRodoviaria) {
		this.chkIndVoucherRodoviaria = chkIndVoucherRodoviaria;
	}
	
	public void onClick$chkIndEstorno(Event event) {
		rowIdEventoExtra.setVisible(chkIndEstorno.isChecked());
	}
	
	public void onClick$chkAtivaEstornoReceitaDespesaCredito(Event event) {
		rowAtivaEstornoReceitaDespesaCredito.setVisible(chkAtivaEstornoReceitaDespesaCredito.isChecked());
	}
	
	public Checkbox getChkAtivaEstornoReceitaDespesaCredito() {
		return chkAtivaEstornoReceitaDespesaCredito;
	}

	public void setChkAtivaEstornoReceitaDespesaCredito(Checkbox chkAtivaEstornoReceitaDespesaCredito) {
		this.chkAtivaEstornoReceitaDespesaCredito = chkAtivaEstornoReceitaDespesaCredito;
	}

	public Row getRowAtivaEstornoReceitaDespesaCredito() {
		return rowAtivaEstornoReceitaDespesaCredito;
	}

	public void setRowAtivaEstornoReceitaDespesaCredito(Row rowAtivaEstornoReceitaDespesaCredito) {
		this.rowAtivaEstornoReceitaDespesaCredito = rowAtivaEstornoReceitaDespesaCredito;
	}

	public void onClick$radioPor(Event ev) {
		rowPercentualDesconto.setVisible(true);
		rowValorDesconto.setVisible(false);
		valorDescontoBox.setDisabled(true);
		percentualDescontoBox.setDisabled(false);
		percentualDescontoBox.setConstraint("no negative");
	}
	
	public void onClick$radioImp(Event ev) {
		rowPercentualDesconto.setVisible(false);
		rowValorDesconto.setVisible(true);
		percentualDescontoBox.setDisabled(true);
		valorDescontoBox.setDisabled(false);
		valorDescontoBox.setConstraint("no negative");
	}
}
