#region using statements
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
#endregion

namespace LLNet.Tienda.MainForms.Controls
{
    /*************************DLQG***********************************/ 
    /// <summary>
    /// Control de Pago con Credix
    /// </summary>
    public partial class ctlCredix : UserControl
    {    
       
        #region Declaracion de Eventos

        public event System.ComponentModel.CancelEventHandler BeforePayWithCredix;
        public event System.EventHandler PayWithCredix;

        #endregion

        public decimal? OriginalValue;

        public decimal Rate = 1;

        public decimal? Currency;

        #region Constructor
        public ctlCredix()
        {
            InitializeComponent();
            if (!DesignMode)
            {
                Utils.Helpers.Merge(GUI.CApp.bll.getTypedDataSet(dsPDV1.GetType(), dsPDV1.TDA_V_MONEDAS.TableName), dsPDV1);
                rowMoneda.Properties.Value = GUI.CApp.bll.GetSingleValue("MonedaBase", "General");
            }

            GUI.CApp.TraducirForm(this);
        }
        #endregion

        #region Eventos

        private void ctlCredix_Load(object sender, EventArgs e)
        {
            // Coloca el foco en la fila de Pago en Efectivo
            Vgc.FocusedRow = rowMONTO;
        }

        public void AgregarPago(object sender, decimal pCurrencyValue)
        {
            // Ejecuta el evento antes del pago en efectivo si se ha creado
            CancelEventArgs cea = new CancelEventArgs();
            if (BeforePayWithCredix != null)
                BeforePayWithCredix(sender, cea);

            // Detiene el proceso de pago con credix si se ha cancelado desde el evento
            if (cea.Cancel == true)
                return;

            if (pCurrencyValue == 0)
            {
                GUI.CApp.ShowMessage(GUI.CApp.TraducirPalabra("El monto a abonar debe ser mayor a cero"), catCredix.Properties.Caption.ToString(), false);
                Vgc.FocusedRow = rowMONTO;
                return;
            }

            // Obtiene los valores de pago
            decimal pValue = (OriginalValue < pCurrencyValue * Rate) ? (decimal)OriginalValue : pCurrencyValue * Rate;
            decimal pPay = pCurrencyValue * Rate;
            
            //moneda colones 188
            string mond = "188";
            //moneda dolares 840
            if (Currency == 2)
                mond = "840";
            //
            string Mto = FmtMonto(pCurrencyValue);
            decimal mont = decimal.Round(pCurrencyValue, 2); //redondea a 2 decimales

            string documento = Program.FrmMainPos.DsPedido.WMS_DOCUMENTOS[0].DOCUMENTO.ToString();
            //Formulario de Credix
            LLNet.Tienda.MainForms.Forms.Credix.FrmCredix frmCdx = new LLNet.Tienda.MainForms.Forms.Credix.FrmCredix(Mto, mond, mont, documento);
            frmCdx.ShowDialog();

            // Detiene el proceso de pago con credix si no tuvo respuesta positiva o se cancelo dsd el form
            if (frmCdx.exito == false )
                return;

            // Paga con credix
            Credix(pValue, pPay, Rate, Currency, pCurrencyValue);            

            // Ejecuta el evento despues del pago con credix
            if (PayWithCredix != null)
                PayWithCredix(sender, null);
        } 

        private string FmtMonto(decimal pmonto)
        {
            decimal mont = decimal.Round(pmonto, 2); //redondea a 2 decimales
            return FmtMonto(mont.ToString());
        }
        
        private string FmtMonto(string pmonto)
        {
            string monto = string.Empty;
            Int32 punto = pmonto.LastIndexOf('.');
            Int32 lngtd = pmonto.Length;
            Int32 cdec = lngtd - punto;
            if (punto == -1)
            {//no trae punto    
                monto = pmonto.ToString() + "00";
            }
            else
            {
                if (lngtd == 1)
                {//punto al final
                    monto = pmonto.ToString().Remove(punto,1)  + "00";
                }
                else
                {
                    if (lngtd == 2)
                    {//punto x.x    
                        monto = pmonto.ToString().Remove(punto, 1) + "0";
                    }
                    else
                    {
                        if (lngtd == 3)
                        {//punto x.x    
                            monto = pmonto.ToString().Remove(punto, 1);
                        }
                    }
                }
            }
            return monto;
        }

        #region Pago con Credix

        /// <summary>
        /// Pago con Credix
        /// </summary>
        public void Credix(decimal pValue, decimal pPay, decimal pRate, decimal? pCurrency, decimal pCurrencyValue)
        {
            Forms.frmPayments payment = ((Forms.frmPayments)FindForm());
            
            if (payment.beforePay(pValue) == -1) return;

            Model.PDV.DsPDV.WMS_PAGO_DOCUMENTOSRow pdr = payment.DsRecibo.WMS_PAGO_DOCUMENTOS.NewWMS_PAGO_DOCUMENTOSRow();
            // TODO: Cambiar la forma como obtiene el recibo
            pdr.DOCUMENTO = payment.DsRecibo.WMS_DOCUMENTOS[0].DOCUMENTO;
            pdr.TIPO_PAGO = 32;
            Utils.QueryParams qp = new LLNet.Utils.QueryParams();
            qp.AddReplaceParam("DOCUMENTO", (payment.DsRecibo.WMS_DOCUMENTOS[0].DOCUMENTO).ToString());
            pdr.LINEA = Convert.ToDecimal(GUI.CApp.bll.GetSingleValue("SiguienteLineaPago", qp, "PDV")) + payment.DsRecibo.WMS_PAGO_DOCUMENTOS.Rows.Count;
            pdr.VALOR = pValue;
            pdr.PAGADO = pPay;
            pdr.TASA_CAMBIO = pRate;
            if (pCurrency != null)
                pdr.MONEDA = (decimal)pCurrency;

            pdr.VALOR_MONEDA = pCurrencyValue;
            pdr.FECHA = DateTime.Now;
            pdr.EMISOR = 4;
            //pdr.TARJETA =             

            payment.DsRecibo.WMS_PAGO_DOCUMENTOS.AddWMS_PAGO_DOCUMENTOSRow(pdr);  
          
            //Deshabilitar el boton Cancelar para obligar el pago
            payment.btnCancelar.Enabled = false;
        }

        #endregion

        #endregion

        public void RecalcularMonto()
        {
            rowMONTO.Properties.Value = OriginalValue / Rate;
            rowMoneda.Properties.Value = Currency;
            Vgc.FocusedRow = rowMONTO;
            Vgc.ShowEditor();
        }

        private void Vgc_FocusedRecordCellChanged(object sender, DevExpress.XtraVerticalGrid.Events.IndexChangedEventArgs e)
        {
            Vgc.ShowEditor();
        }

        private void lueMoneda_Enter(object sender, EventArgs e)
        {
            DevExpress.XtraEditors.LookUpEdit lue = ((DevExpress.XtraEditors.LookUpEdit)sender);
            rowMoneda.Properties.Value = lue.EditValue;
        }

        private void lueMoneda_Leave(object sender, EventArgs e)
        {
            Rate = decimal.Parse(((LookUpEdit)sender).GetColumnValue("FACTOR").ToString());
            Currency = decimal.Parse(((LookUpEdit)sender).GetColumnValue("MONEDA").ToString());

            RecalcularMonto();
        }

    }
}
