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;
using DevExpress.XtraEditors.Repository;

namespace LLNet.Tienda.MainForms.Controls
{
    public partial class ctlCheck : UserControl
    {
        #region Events

        public event System.ComponentModel.CancelEventHandler BeforePayWithCheck;
        public event System.EventHandler PayWithCheck;

        #endregion

        public decimal? OriginalValue;
        public decimal Rate = 1;
        public decimal? Currency;

        #region Constructor

        public ctlCheck()
        {
            InitializeComponent();
            if (!DesignMode)
            {
                Utils.QueryParams qp = new LLNet.Utils.QueryParams();
                qp.AddReplaceParam("RV_DOMAIN", "BANCOS");
                Utils.Helpers.Merge(GUI.CApp.bll.getTypedDataSet(dsGeneral1.GetType(), dsGeneral1.CG_REF_CODES.TableName, qp), dsGeneral1);
                Utils.Helpers.Merge(GUI.CApp.bll.getTypedDataSet(dsTienda1.GetType(), dsTienda1.TDA_V_MONEDAS.TableName), dsTienda1);
                Utils.Helpers.Merge(GUI.CApp.bll.getTypedDataSet(dsTienda1.GetType(), dsTienda1.MEDIO_AUTORIZACION.TableName), dsTienda1);
                rowMoneda.Properties.Value = GUI.CApp.bll.GetSingleValue("MonedaBase", "General");
                txtCheque.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;
                txtCheque.Mask.EditMask = Program.regexCheque;

               
            }
          
            GUI.CApp.TraducirForm(this);
            
          }

        #endregion

        #region Events

        private void ctlCheck_Load(object sender, EventArgs e)
        {

            Vgc.FocusedRow = rowMONTO;

        }

        private void txtCheque_KeyDown(object sender, KeyEventArgs e)
        {


        }

        #endregion

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

            RecalcularMonto();

        }

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

        private void txtAutorizacion_KeyDown(object sender, KeyEventArgs e)
        {
            // Si presiona enter en autorizacion
            if (e.KeyCode == Keys.Enter)
            {
                AgregarPago(((TextEdit)sender).EditValue.ToString());
            }

        }

        public void AgregarPago(string pAutorizacion)
        {
            // Ejecuta el evento antes de pagar con tarjeta de credito
            CancelEventArgs cea = new CancelEventArgs();
            if (BeforePayWithCheck != null)
                BeforePayWithCheck(null, cea);

            // Si en el evento se cancelo la operacion detiene el proceso
            if (cea.Cancel == true)
                return;


            if (rowBANCO.Properties.Value == null || rowBANCO.Properties.Value == DBNull.Value)
            {
                GUI.CApp.ShowMessage(GUI.CApp.TraducirPalabra("seleccione el banco emisor"),categoryRow1.Properties.Caption.ToString(),false);
                Vgc.FocusedRow = rowBANCO;
                return;
            }

            if (rowCHEQUE.Properties.Value == null || rowCHEQUE.Properties.Value == DBNull.Value)
            {
                GUI.CApp.ShowMessage(GUI.CApp.TraducirPalabra("ingrese número de cheque"), categoryRow1.Properties.Caption.ToString(),false);
                Vgc.FocusedRow = rowCHEQUE;
                return;
            }


            decimal pCurrencyValue = Convert.ToDecimal(rowMONTO.Properties.Value);

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

            // Obtiene los datos para el pago con cheque
            decimal pValue = (OriginalValue < pCurrencyValue * Rate) ? (decimal)OriginalValue : pCurrencyValue * Rate;
            decimal pPay = pCurrencyValue * Rate;
            
            if (rowBANCO.Properties.Value == null)
            {
                GUI.CApp.ShowMessage(GUI.CApp.TraducirPalabra("Seleccione banco"), categoryRow1.Properties.Caption.ToString(),false);
                Vgc.FocusedRow = rowBANCO;
                return;
            }
            string pBanco = rowBANCO.Properties.Value.ToString();

            if (rowCHEQUE.Properties.Value == null)
            {
                GUI.CApp.ShowMessage(GUI.CApp.TraducirPalabra("Ingrese número de cheque"), categoryRow1.Properties.Caption.ToString(),false);
                Vgc.FocusedRow = rowCHEQUE;
                return;
            }
            string pCheque = rowCHEQUE.Properties.Value.ToString();            

            // Efectua el pago
            Check(pValue, pPay, pCheque, Decimal.Parse(pBanco), Rate, Currency,
                Decimal.Parse(rowMONTO.Properties.Value.ToString()), pAutorizacion,Utils.Helpers.ObjToStr(rowMAutorizacion.Properties.Value) );

            // Ejecuta el evento despues de pagar con cheque
            if (PayWithCheck != null)
                PayWithCheck(null, null);

        }

        /// <summary>
        /// Pago con Cheque
        /// </summary>
        public void Check(decimal pValue, decimal pPay, string pCheque, decimal pBanco,
            decimal pRate, decimal? pCurrency, decimal pCurrencyValue, string pAutorizacion,string pMedioAutorizacion)
        {
            Forms.frmPayments payment = ((Forms.frmPayments)FindForm());

            if (Convert.ToDecimal(payment.rowTotal.Properties.Value) < Convert.ToDecimal(payment.rowAbonado.Properties.Value) + pPay)
            {
                if (GUI.CApp.ShowMessage("El monto ingresado genera vuelto, ¿está seguro de ingresar este pago?", "Cobros y Facturación", true, true) == DialogResult.Cancel)
                {
                    return;
                }
            }

            if (payment.beforePay(pValue) == -1) return; 

            Model.PDV.DsPDV.WMS_PAGO_DOCUMENTOSRow pdr = payment.DsRecibo.WMS_PAGO_DOCUMENTOS.NewWMS_PAGO_DOCUMENTOSRow();
            pdr.DOCUMENTO = payment.DsRecibo.WMS_DOCUMENTOS[0].DOCUMENTO;
            pdr.TIPO_PAGO = 4;
            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.FECHA = DateTime.Now;
            pdr.CHEQUE = pCheque;
            pdr.BANCO = pBanco;
            pdr.TASA_CAMBIO = pRate;
            pdr.AUTORIZACION = pAutorizacion;
            pdr.MEDIO_AUTORIZACION = pMedioAutorizacion;

            if (pCurrency != null)
                pdr.MONEDA = (decimal)pCurrency;

            pdr.VALOR_MONEDA = pCurrencyValue;
            payment.DsRecibo.WMS_PAGO_DOCUMENTOS.AddWMS_PAGO_DOCUMENTOSRow(pdr);
        }

        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();
            
        }

    }
}
