using LLNet.Utils;
using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace LLNet.Tienda.MainForms.Controls
{
    public partial class ctlSinpeMovil : UserControl
    {
        public event System.EventHandler PayWithSinpe;
        public event System.ComponentModel.CancelEventHandler BeforePaywithSinpe;

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



        public ctlSinpeMovil()
        {
            InitializeComponent();

        }


        #region Procedimientos y funciones del controles


        public void FormatoCedula()
        {

            string v_tipoCed = "";

            if (rowTipoCedula.Properties.Value != null)
            {
                if (rowTipoCedula.Properties.Value == "Cédula Identidad")
                {
                    rowCedula.Properties.Value = "";
                    // lueCedula.Mask.EditMask = "\\d\\d-\\d\\d\\d\\d-\\d\\d\\d\\d";
                    lueCedula.Mask.EditMask = "0[1-9]{1}-\\d{4}-\\d{4}";
                    lueCedula.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Regular;
                }
                else if (rowTipoCedula.Properties.Value == "Cédula Jurídica")
                {
                    rowCedula.Properties.Value = "";
                    //lueCedula.Mask.EditMask = "\\d-\\d\\d\\d-\\d\\d\\d\\d\\d\\d";
                    lueCedula.Mask.EditMask = "3-\\d{3}-\\d{6}";
                    lueCedula.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Regular;
                }
                else if (rowTipoCedula.Properties.Value == "Extrangero no Residente")
                {
                    rowCedula.Properties.Value = "";
                    //lueCedula.Mask.EditMask = "\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d";
                    lueCedula.Mask.EditMask = "9.{1,19}";
                    lueCedula.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Regular;

                }
                else if (rowTipoCedula.Properties.Value == "DIMEX")
                {
                    rowCedula.Properties.Value = "";
                    //lueCedula.Mask.EditMask = "\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d";
                    lueCedula.Mask.EditMask = "1[0-9]{11}";
                    lueCedula.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Regular;
                }
                else if (rowTipoCedula.Properties.Value == "DIDI")
                {
                    rowCedula.Properties.Value = "";
                    //lueCedula.Mask.EditMask = "\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d";
                    lueCedula.Mask.EditMask = "5[0-9]{11}";
                    lueCedula.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Regular;
                }


                v_tipoCed = rowTipoCedula.Properties.Value.ToString();
            }

        }


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


        public void AgregarPago(object sender, decimal pCurrencyValue, string pCedula, string pDocumento)
        {


            // Ejecuta el evento antes del pago en efectivo si se ha creado
            CancelEventArgs cea = new CancelEventArgs();
            if (BeforePaywithSinpe != null)
                BeforePaywithSinpe(sender, cea);

            // Detiene el proceso de pago con Flexi 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"), catSINPE_MOVIL.Properties.Caption.ToString(), false);
                Vgc.FocusedRow = rowMONTO;
                return;
            }
            if (pCedula == "")
            {
                GUI.CApp.ShowMessage(GUI.CApp.TraducirPalabra("La cedula no puede estar en blanco"), catSINPE_MOVIL.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.ToString());
            decimal mont = decimal.Round(pCurrencyValue, 2);
            string documento = string.Empty;


            if (pDocumento == null)
            {
                documento = Program.FrmMainPos.DsPedido.WMS_DOCUMENTOS[0].DOCUMENTO.ToString();

            }
            else
            {
                documento = pDocumento;
            }


            // Paga con SINPE
            Sinpe(pValue, pPay, Rate, Currency, pCurrencyValue, pCedula, documento);



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

        public void Sinpe(decimal pValue, decimal pPay, decimal pRate, decimal? pCurrency, decimal pCurrencyValue, string pCedula, string pdocumento)
        {
            Forms.frmPayments payment = ((Forms.frmPayments)FindForm());

            if (payment.DsRecibo.WMS_PAGO_DOCUMENTOS.Rows.Count > 0)

            {
                foreach (var item in payment.DsRecibo.WMS_PAGO_DOCUMENTOS)
                {

                    if (item.TIPO_PAGO == 37)
                    {
                        GUI.CApp.ShowMessage("La forma de pago no se puede agregar, porque ya existe agregada", "Cobros y Facturación", true);
                        return;
                    }

                }

            }
                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 = 37;
                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.TASA_CAMBIO = pRate;



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


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


                //Almacena datos del cliente del SINPE
                Utils.QueryParams param = new QueryParams();

                param.AddReplaceParam("pDOCUMENTO", pdocumento.ToString());
                param.AddReplaceParam("pCEDULA", pCedula.ToString());
                param.AddReplaceParam("pMONTO", pCurrencyValue.ToString());
                param.AddReplaceParam("pJORNADA", Program.Jornada.ToString());
                param.AddReplaceParam("pCREADO_POR", GUI.CApp.usuario);

                GUI.CApp.bll.ExecuteSql("InsertCliente", param, "PDV");



            
        }




        private string FmtMonto(decimal pmonto)
        {
            decimal mont = decimal.Round(pmonto, 2); //redondea a 2 decimales
            return FmtMonto(mont);
        }

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


        #endregion

        private void ctlSinpeMovil_Load(object sender, EventArgs e)
        {
            Vgc.FocusedRow = rowCedula;
            //RecalcularMonto();
        }

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




        private void lueCedula_Click(object sender, EventArgs e)
        {
            FormatoCedula();
        }



    }
}
