using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using OposMSR_1_9_Lib;
using OPOSCONSTANTSLib;
using Microsoft.Win32;
using LLNet.Utils;
using LLNet.GUI;
using System.Text.RegularExpressions;
using System.IO.Ports;

namespace LLNet.Tienda.MainForms.Forms
{
    public partial class FrmBCR : Form
    {
        #region Variables
        OPOSMSRClass omsr = new OPOSMSRClass();
        string track2 = "";
        static LLNet.Controls.LLEventLog EventLog;

        public bool exito = false;//Indica si la transacción se realizó
        public string NumAutoriz = "";//Número de autorización
        public string NumTarj = "";//Número de tarjeta enmascarado
        public bool reversada = false;//Indica si la transacción de la venta, fue reversada
        public string NumRef = "";//Número de referencia de la transacción
        public string Motivo = "";//Indica si la transacción fue cancelada o denegada

        string Id_tr_tarj = "";//Id log transacciones
        string Tarjeta = "";//Número de tarjeta sin enmascarar
        string url = "";//Dirección web del wcf EVERTEC
        string MACValue = "";//Valor de verificación o firma que se debe enviar
        string SystemTrace = "";
        bool anulacion = false;//Indica si se va hacer una anulación o una venta
        bool serial = false;//Indica si se está trabajando con cardreader serial
        SerialPort sp = new SerialPort();//Puerto serial
        #endregion

        public FrmBCR(decimal monto, string Id)
        {
            InitializeComponent();
            this.lblMonto.Text = monto.ToString();
            this.Id_tr_tarj = Id;

            //Dirección web del wcf EVERTEC
            this.url = Helpers.Nvl(CApp.GetParam("BDW"), "").ToString();
        }

        #region CambiarKey
        /// <summary>
        /// Verifica si la key para las transacciones con el BCR está vencida o no,
        /// si lo está, la cambia
        /// </summary>
        public void CambiarKey()
        {
            Utils.QueryParams qp = new QueryParams();
            qp.AddReplaceParam("CAJA", Program.Caja.ToString());
            if (url != "")
            {
                if (Echo())
                {
                    string CardAcqID = Helpers.Nvl(CApp.GetParam("CAI"), "").ToString();

                    if (CardAcqID != "")
                    {
                        DataSet ds_datos = CApp.bll.getDataSet("PDV", "ObtTermKey", qp);
                        if (ds_datos.Tables.Count > 0 && ds_datos.Tables[0].Rows.Count > 0)
                        {
                            qp = new QueryParams();
                            qp.AddReplaceParam("SECUENCIA", "WMS_S_IDLOG");
                            string secuencia = Helpers.Nvl(CApp.bll.GetSingleValue("SECUENCIA", qp, "General"), "").ToString();

                            //Log Inicio
                            qp = new QueryParams();
                            qp.AddReplaceParam("IDLOG", secuencia);
                            string texto = CardAcqID + "," + ds_datos.Tables[0].Rows[0].ItemArray[0].ToString() + "," +
                                ds_datos.Tables[0].Rows[0].ItemArray[1].ToString();
                            qp.AddReplaceParam("TEXTO", texto);
                            qp.AddReplaceParam("CAJA", Program.Caja.ToString());
                            GUI.CApp.bll.ExecuteSql("WMS_LOG_INI_BCR", qp, "PDV");

                            EVERTECEPS _Service = new EVERTECEPS(url);
                            string key = _Service.KeyExchange(CardAcqID, ds_datos.Tables[0].Rows[0].ItemArray[0].ToString(),
                                ds_datos.Tables[0].Rows[0].ItemArray[1].ToString());

                            //Log Fin
                            qp = new QueryParams();
                            qp.AddReplaceParam("IDLOG", secuencia);
                            texto = key;
                            qp.AddReplaceParam("TEXTO", texto);
                            GUI.CApp.bll.ExecuteSql("WMS_LOG_FIN_BCR", qp, "PDV");

                            qp = new QueryParams();
                            qp.AddReplaceParam("CAJA", Program.Caja.ToString());
                            qp.AddReplaceParam("KEY", key);
                            GUI.CApp.bll.ExecuteSql("AlmKey", qp, "PDV");
                        }
                    }
                }
            }
        }
        #endregion

        #region FrmBCR
        public FrmBCR(string monto, string tarj, string tarje, string autoriz, string rrn, string Id, string tarjetah, string systemt)
        {
            InitializeComponent();

            this.NumTarj = tarje;
            this.Tarjeta = tarj;
            this.lblNTarjeta.Text = tarje;
            this.NumAutoriz = autoriz;
            this.NumRef = rrn;
            this.Id_tr_tarj = Id;
            this.lblTarjetaH.Text = tarjetah;
            //
            this.lblMonto.Text = monto.ToString();
            this.sbtnAceptar.Enabled = true;
            this.lblFechaE.Visible = false;
            this.label3.Visible = false;
            this.anulacion = true;
            this.SystemTrace = systemt;

            //Dirección web del wcf EVERTEC
            this.url = Helpers.Nvl(CApp.GetParam("BDW"), "").ToString();
        }
        #endregion

        #region Cardreader
        #region SerialDataReceived
        void SerialDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp1 = (SerialPort)sender;
            string linea = sp1.ReadExisting();

            if (linea.Contains("%"))
            {
                bool caret = linea.Contains("^");
                if (caret)
                {
                    string[] datos = linea.Split('^');

                    if (datos[2].Contains(";"))
                    {
                        string[] daTrack = datos[2].Split(';');
                        this.track2 = daTrack[1];
                        this.track2 = this.track2.Remove(this.track2.IndexOf('?'), 1);
                        this.track2 = this.track2.Replace('=', 'D');
                    }

                    //Nombre con apellidos
                    string nomb = "";
                    if (datos[1].Contains("/"))
                    {
                        string[] n = datos[1].Split('/');
                        nomb = n[1].Trim();
                        string[] ap1 = datos[1].Split(' ');
                        nomb += " " + ap1[0];
                    }
                    else
                        nomb = datos[1];
                    this.lblTarjetaH.Text = nomb.Trim();

                    //Número tarjeta
                    string numt = Regex.Replace(datos[0], "[^0-9]", String.Empty);
                    this.Tarjeta = numt;

                    this.NumTarj = this.Tarjeta.Substring(0, 6);//Obtiene los primeros 6 dígitos del número de tarjeta
                    for (int i = 0; i < (this.Tarjeta.Length - 10); i++)
                        this.NumTarj += "*";
                    this.NumTarj += this.Tarjeta.Substring(this.Tarjeta.Length - 4, 4);//Obtiene los últimos 4 dígitos del número de tarjeta
                    this.lblNTarjeta.Text = this.NumTarj;

                    //Fecha vencimiento
                    string fecv = datos[2].Substring(0, 4);
                    this.lblFechaE.Text = fecv;

                    if (this.lblNTarjeta.Text != String.Empty && this.lblFechaE.Text != String.Empty && this.lblMonto.Text != String.Empty && this.lblTarjetaH.Text != String.Empty && this.track2 != "")
                    {
                        sbtnAceptar.Enabled = true;
                    }
                }
            }
            else if (linea.Contains(";"))
            {
                string[] daTrack = linea.Split(';');
                this.track2 = daTrack[1];
                this.track2 = this.track2.Remove(this.track2.IndexOf('?'), 1);
                this.track2 = this.track2.Replace('=', 'D');

                if (this.lblNTarjeta.Text != String.Empty && this.lblFechaE.Text != String.Empty && this.lblMonto.Text != String.Empty && this.lblTarjetaH.Text != String.Empty && this.track2 != "")
                {
                    if (this.track2.Contains(this.Tarjeta))
                        sbtnAceptar.Enabled = true;
                    else
                        sbtnAceptar.Enabled = false;
                }
            }
        }
        #endregion

        #region GetDirByAppConfig
        private string GetDirByAppConfig()
        {
            string result;
            try
            {
                result = System.Configuration.ConfigurationManager.AppSettings.Get("DalPath");
            }
            catch
            {
                result = "";
            }
            return result;
        }
        #endregion

        #region statusUpdateOccurred
        private void statusUpdateOccurred(int e)
        {
            string ExeDir = GetDirByAppConfig();
            EventLog = new LLNet.Controls.LLEventLog(ExeDir);

            int status = e;
            string statusMsg = "StatusUpdateOccurred = ";
            switch (status)
            {
                case (int)OPOS_Constants.OPOS_SUE_POWER_ONLINE:
                    statusMsg += "OPOS_SUE_POWER_ONLINE";
                    EventLog.WriteLog(LLNet.Utils.Types.ErrorTypes.MESSAGES, statusMsg);
                    break;
                case (int)OPOS_Constants.OPOS_SUE_POWER_OFFLINE:
                    statusMsg += "OPOS_SUE_POWER_OFFLINE";
                    EventLog.WriteLog(LLNet.Utils.Types.ErrorTypes.MESSAGES, statusMsg);
                    break;
            }
        }
        #endregion

        #region dataOccurred
        private void dataOccurred(int e)
        {
            Datos();

            if (this.lblNTarjeta.Text != String.Empty && this.lblFechaE.Text != String.Empty && this.lblMonto.Text != String.Empty && this.lblTarjetaH.Text != String.Empty)
            {
                sbtnAceptar.Enabled = true;
            }
            try
            {
                omsr.DataEventEnabled = true;
            }
            catch (Exception ex)
            {
                CApp.ShowMessage(ex.Message, "Cobros y Facturación", true);
            }
        }
        #endregion

        #region Datos
        /// <summary>
        /// Obtiene los datos del track1 y track2
        /// </summary>
        private void Datos()
        {
            try
            {
                bool bandera = true;//Indica si la tarjeta está vencida o no

                track2 = omsr.Track2Data;//Obtiene los datos del track2

                string track1 = omsr.Track1Data;//Obtiene los datos del track1
                if (track2.IndexOf('=') >= 0)
                {
                    //Limpia los labels
                    this.lblNTarjeta.Text = String.Empty;
                    this.lblFechaE.Text = String.Empty;
                    this.lblTarjetaH.Text = String.Empty;
                    this.NumTarj = "";

                    string[] datos = track2.Split('=');
                    string fechavenc = datos[1].Substring(0, 4);
                    this.Tarjeta = datos[0];//Número de tarjeta

                    this.NumTarj = this.Tarjeta.Substring(0, 6);//Obtiene los primeros 6 dígitos del número de tarjeta
                    for (int i = 0; i < (this.Tarjeta.Length - 10); i++)
                        this.NumTarj += "*";
                    this.NumTarj += this.Tarjeta.Substring(this.Tarjeta.Length - 4, 4);//Obtiene los últimos 4 dígitos del número de tarjeta

                    this.lblNTarjeta.Text = this.NumTarj;//Muestra el número de tarjeta
                    this.lblFechaE.Text = datos[1].Substring(0, 4);//Muestra la fecha de vencimiento de la tarjeta

                    this.track2 = this.track2.Replace('=', 'D');
                }
                if (bandera)
                {
                    if (track1.IndexOf('^') >= 0)
                    {
                        string[] datos = track1.Split('^');
                        string tarjetahabiente = datos[1].Trim();
                        this.lblTarjetaH.Text = tarjetahabiente.Replace('/', ' ');//Muestra el nombre del tarjetahabiente
                    }
                }
            }
            catch (Exception ex)
            {
                CApp.ShowMessage(ex.Message, "Cobros y Facturación", true);
            }
        }
        #endregion

        #region errorOccurred
        private void errorOccurred(int e, int e1, int e2, ref int e3)
        {
            string ExeDir = GetDirByAppConfig();
            EventLog = new LLNet.Controls.LLEventLog(ExeDir);

            string errorCode = "" + e.ToString();
            switch (e)
            {
                case (int)OPOS_Constants.OPOS_E_EXTENDED:
                    errorCode += "=OPOS_E_EXTENDED";
                    EventLog.WriteLog(LLNet.Utils.Types.ErrorTypes.MESSAGES, errorCode);
                    break;
                case (int)OPOS_Constants.OPOS_E_FAILURE:
                    errorCode += "=OPOS_E_FAILURE";
                    EventLog.WriteLog(LLNet.Utils.Types.ErrorTypes.MESSAGES, errorCode);
                    break;
            }

            string errorCodeExtended = "" + e1;
            switch (e1)
            {
                case (int)OPOSMSRConstants.OPOS_EMSR_START:
                    errorCodeExtended += "=OPOS_EMSR_START";
                    EventLog.WriteLog(LLNet.Utils.Types.ErrorTypes.MESSAGES, errorCodeExtended);
                    break;
                case (int)OPOSMSRConstants.OPOS_EMSR_END:
                    errorCodeExtended += "=OPOS_EMSR_END";
                    EventLog.WriteLog(LLNet.Utils.Types.ErrorTypes.MESSAGES, errorCodeExtended);
                    break;
                case (int)OPOSMSRConstants.OPOS_EMSR_PARITY:
                    errorCodeExtended += "=OPOS_EMSR_PARITY";
                    EventLog.WriteLog(LLNet.Utils.Types.ErrorTypes.MESSAGES, errorCodeExtended);
                    break;
                case (int)OPOSMSRConstants.OPOS_EMSR_LRC:
                    errorCodeExtended += "=OPOS_EMSR_LRC";
                    EventLog.WriteLog(LLNet.Utils.Types.ErrorTypes.MESSAGES, errorCodeExtended);
                    break;
            }

            throw new Exception(errorCode + " " + errorCodeExtended);
            omsr.ClearInput();
        }
        #endregion
        #endregion

        #region GetMD5HashData
        /// <summary>
        /// EVERTEC
        /// Obtiene el MacValue, a partir de la información proporcionada
        /// </summary>
        /// <param name="data">Información a encriptar</param>
        /// <returns>MacValue</returns>
        private string GetMD5HashData(string data)
        {
            System.Text.UTF8Encoding encode = new System.Text.UTF8Encoding();
            System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] hash = null;
            hash = md5.ComputeHash(encode.GetBytes(data));
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            byte outputByte = 0;
            foreach (byte outputByte_loopVariable in hash)
            {
                outputByte = outputByte_loopVariable;
                sb.Append(outputByte.ToString("x2").ToUpper());
            }
            return sb.ToString().ToLower();
        }
        #endregion

        #region Echo
        /// <summary>
        /// Prueba de conexión
        /// </summary>
        private bool Echo()
        {
            bool exito = false;
            try
            {
                EVERTECEPS _Service = new EVERTECEPS(this.url);

                string result = _Service.EchoTest("EchoTest");
                exito = true;
            }
            catch (Exception ex)
            {
                this.Motivo = ex.Message;
                this.Motivo = this.Motivo.Replace("'", " ");
                exito = false;

                if (serial)
                {
                    sp.Close();
                    sp = new SerialPort();
                }
                else
                {
                    if (omsr.Claimed)
                    {
                        omsr.Close();
                        omsr = new OPOSMSRClass();
                    }
                }
            }

            return exito;
        }
        #endregion

        #region Reversar
        /// <summary>
        /// Reversa una transacción
        /// </summary>
        private void Reversar()
        {
            if (this.url != "")
            {
                if (Echo())
                {
                    EVERTECEPS _Service = new EVERTECEPS(this.url);
                    Authorization _Authorization = new Authorization();
                    this.MACValue = String.Empty;
                    string CardAcqID = Helpers.Nvl(CApp.GetParam("CAI"), "").ToString();
                    string Processing = "";

                    QueryParams qp = new QueryParams();
                    qp.AddReplaceParam("DOMAIN", "ProcesingCode BCR");
                    qp.AddReplaceParam("MEANING", "Venta - Reversiones");
                    Processing = Helpers.Nvl(CApp.bll.GetSingleValue("RV_LOW_VALUE", qp, "PDV"), "").ToString();

                    if (CardAcqID != "" && Processing != "")
                    {
                    Reversion:
                        //Obtiene el terminalid y el key
                        qp = new QueryParams();
                        qp.AddReplaceParam("CAJA", Program.Caja.ToString());
                        DataSet ds_datos = CApp.bll.getDataSet("PDV", "ObtTermKey", qp);
                        if (ds_datos.Tables.Count > 0 && ds_datos.Tables[0].Rows.Count > 0)
                        {
                            //Obtener MaCValue
                            this.MACValue = GetMD5HashData(CardAcqID + ds_datos.Tables[0].Rows[0].ItemArray[0].ToString() +
                                ds_datos.Tables[0].Rows[0].ItemArray[1].ToString() + this.Tarjeta + this.lblMonto.Text +
                                "" + Processing + this.SystemTrace);

                            _Authorization = _Service.ReverseTransaction(CardAcqID, ds_datos.Tables[0].Rows[0].ItemArray[0].ToString(),
                                ds_datos.Tables[0].Rows[0].ItemArray[1].ToString(), this.Tarjeta, this.lblMonto.Text,
                                "", Processing, this.SystemTrace, this.MACValue);

                            if (_Authorization.ResponseCode == "00")
                            {
                                this.NumAutoriz = _Authorization.AuthorizationIdentificationResponse;
                                this.NumRef = _Authorization.RetrievalReferenceNumber;
                                this.exito = true;
                                this.reversada = true;

                                try
                                {
                                    qp = new QueryParams();
                                    qp.AddReplaceParam("ID_TR_TARJ", Id_tr_tarj);
                                    qp.AddReplaceParam("TARJETHAB", this.lblTarjetaH.Text);
                                    qp.AddReplaceParam("TARJETA", this.Tarjeta);
                                    qp.AddReplaceParam("SYSTEMTRACE", this.SystemTrace);
                                    CApp.bll.ExecuteSql("WMS_P_REGDATTARJ", qp, "PDV");
                                }
                                catch (Exception ex)
                                {
                                    CApp.ShowMessage(ex.Message, "Cobros y Facturación", true);
                                }
                            }
                            else
                            {
                                if (_Authorization.ResponseCode == "KE")
                                {
                                    CambiarKey();
                                    goto Reversion;
                                }
                                else
                                {
                                    this.Motivo = _Authorization.ResponseCode + " " + _Authorization.ResponseCodeDescription;
                                    this.Motivo = this.Motivo.Replace("'", " ");
                                    CApp.ShowMessage(_Authorization.ResponseCodeDescription, "Cobros y Facturación", true);
                                }
                            }
                        }
                    }//if (CardAcqID != "" && Processing != "")
                }//if (Echo())
            }//if (this.url != "")
        }
        #endregion

        #region Venta
        /// <summary>
        /// Proceso de cobro con tarjeta
        /// </summary>
        private void Venta()
        {
            if (this.url != "")
            {
                if (Echo())
                {
                    EVERTECEPS _Service = new EVERTECEPS(this.url);
                    Authorization _Authorization = new Authorization();
                    this.MACValue = String.Empty;
                    string CardAcqID = Helpers.Nvl(CApp.GetParam("CAI"), "").ToString();
                    string Processing = "";

                    QueryParams qp = new QueryParams();
                    qp.AddReplaceParam("DOMAIN", "ProcesingCode BCR");
                    qp.AddReplaceParam("MEANING", "Venta - Reversiones");
                    Processing = Helpers.Nvl(CApp.bll.GetSingleValue("RV_LOW_VALUE", qp, "PDV"), "").ToString();

                    if (CardAcqID != "" && Processing != "")
                    {
                    Venta:
                        //Obtiene el terminalid y el key
                        qp = new QueryParams();
                        qp.AddReplaceParam("CAJA", Program.Caja.ToString());
                        DataSet ds_datos = CApp.bll.getDataSet("PDV", "ObtTermKey", qp);
                        if (ds_datos.Tables.Count > 0 && ds_datos.Tables[0].Rows.Count > 0)
                        {
                            qp = new QueryParams();
                            qp.AddReplaceParam("SECUENCIA", "WMS_S_SYSTEM_TRACE");
                            this.SystemTrace = Helpers.Nvl(CApp.bll.GetSingleValue("ObtSecuencia", qp, "PDV"), "").ToString();

                            //Obtener MaCValue
                            this.MACValue = GetMD5HashData(CardAcqID + ds_datos.Tables[0].Rows[0].ItemArray[0].ToString() +
                                ds_datos.Tables[0].Rows[0].ItemArray[1].ToString() + this.track2 + this.lblMonto.Text +
                                "" + Processing + this.SystemTrace);

                            try
                            {
                                _Authorization = _Service.GetAuthorizationTrack2(CardAcqID, ds_datos.Tables[0].Rows[0].ItemArray[0].ToString(),
                                    ds_datos.Tables[0].Rows[0].ItemArray[1].ToString(), this.track2, this.lblMonto.Text,
                                    "", Processing, this.SystemTrace, this.MACValue);

                                if (_Authorization.ResponseCode == "00")
                                {
                                    this.NumAutoriz = _Authorization.AuthorizationIdentificationResponse;
                                    this.NumRef = _Authorization.RetrievalReferenceNumber;
                                    this.exito = true;

                                    try
                                    {
                                        qp = new QueryParams();
                                        qp.AddReplaceParam("ID_TR_TARJ", Id_tr_tarj);
                                        qp.AddReplaceParam("TARJETHAB", this.lblTarjetaH.Text);
                                        qp.AddReplaceParam("TARJETA", this.Tarjeta);
                                        qp.AddReplaceParam("SYSTEMTRACE", this.SystemTrace);
                                        CApp.bll.ExecuteSql("WMS_P_REGDATTARJ", qp, "PDV");
                                    }
                                    catch (Exception ex)
                                    {
                                        CApp.ShowMessage(ex.Message, "Cobros y Facturación", true);
                                    }
                                }
                                else
                                {
                                    if (_Authorization.ResponseCode == "KE")
                                    {
                                        CambiarKey();
                                        goto Venta;
                                    }
                                    else
                                    {
                                        this.Motivo = _Authorization.ResponseCode + " " + _Authorization.ResponseCodeDescription;
                                        CApp.ShowMessage(_Authorization.ResponseCodeDescription, "Cobros y Facturación", true);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                this.Motivo = ex.Message;
                                this.Motivo = this.Motivo.Replace("'", " ");

                                Reversar();

                                if (serial)
                                {
                                    sp.Close();
                                    sp = new SerialPort();
                                }
                                else
                                {
                                    if (omsr.Claimed)
                                    {
                                        omsr.Close();
                                        omsr = new OPOSMSRClass();
                                    }
                                }
                                this.Dispose();

                                if (reversada)
                                    CApp.ShowMessage("Transacción reversada. " + ex.Message, "Cobros y Facturación", true);
                                else
                                    CApp.ShowMessage(ex.Message, "Cobros y Facturación", true);
                            }
                        }
                    }//if (CardAcqID != "" && Processing != "")
                }//if (Echo())
                else
                    this.exito = false;
            }//if (this.url != "")            
        }
        #endregion

        #region Anulacion
        /// <summary>
        /// Proceso de anulación de una transacción
        /// </summary>
        private void Anulacion()
        {
            try
            {
                if (this.url != "")
                {
                    if (Echo())
                    {
                        EVERTECEPS _Service = new EVERTECEPS(this.url);
                        Authorization _Authorization = new Authorization();
                        this.MACValue = String.Empty;
                        string CardAcqID = Helpers.Nvl(CApp.GetParam("CAI"), "").ToString();
                        string Processing = "";

                        QueryParams qp = new QueryParams();
                        qp.AddReplaceParam("DOMAIN", "ProcesingCode BCR");
                        qp.AddReplaceParam("MEANING", "Anulaciones");
                        Processing = Helpers.Nvl(CApp.bll.GetSingleValue("RV_LOW_VALUE", qp, "PDV"), "").ToString();

                        if (CardAcqID != "" && Processing != "" && this.Tarjeta != "")
                        {
                        Anulacion:
                            //Obtiene el terminalid y el key
                            qp = new QueryParams();
                            qp.AddReplaceParam("CAJA", Program.Caja.ToString());
                            DataSet ds_datos = CApp.bll.getDataSet("PDV", "ObtTermKey", qp);
                            if (ds_datos.Tables.Count > 0 && ds_datos.Tables[0].Rows.Count > 0)
                            {
                                //Obtener MaCValue
                                this.MACValue = GetMD5HashData(CardAcqID + ds_datos.Tables[0].Rows[0].ItemArray[0].ToString() +
                                    ds_datos.Tables[0].Rows[0].ItemArray[1].ToString() + this.Tarjeta + this.SystemTrace +
                                    this.NumRef + this.NumAutoriz + this.lblMonto.Text + Processing);

                                _Authorization = _Service.GetVoid(CardAcqID, ds_datos.Tables[0].Rows[0].ItemArray[0].ToString(),
                                    ds_datos.Tables[0].Rows[0].ItemArray[1].ToString(), Tarjeta, this.SystemTrace, this.NumRef, this.NumAutoriz,
                                    this.lblMonto.Text, Processing, this.MACValue);

                                if (_Authorization.ResponseCode == "00")
                                {
                                    this.NumAutoriz = _Authorization.AuthorizationIdentificationResponse;
                                    this.NumRef = _Authorization.RetrievalReferenceNumber;
                                    this.exito = true;

                                    try
                                    {
                                        qp = new QueryParams();
                                        qp.AddReplaceParam("ID_TR_TARJ", Id_tr_tarj);
                                        qp.AddReplaceParam("TARJETHAB", this.lblTarjetaH.Text);
                                        qp.AddReplaceParam("TARJETA", this.Tarjeta);
                                        qp.AddReplaceParam("SYSTEMTRACE", this.SystemTrace);
                                        CApp.bll.ExecuteSql("WMS_P_REGDATTARJ", qp, "PDV");
                                    }
                                    catch (Exception ex)
                                    {
                                        CApp.ShowMessage(ex.Message, "Cobros y Facturación", true);
                                    }
                                }
                                else
                                {
                                    if (_Authorization.ResponseCode == "KE")
                                    {
                                        CambiarKey();
                                        goto Anulacion;
                                    }
                                    else
                                    {
                                        this.Motivo = _Authorization.ResponseCode + " " + _Authorization.ResponseCodeDescription;
                                        this.Motivo = this.Motivo.Replace("'", " ");
                                        CApp.ShowMessage(_Authorization.ResponseCodeDescription, "Cobros y Facturación", true);
                                    }
                                }
                            }
                        }//if (CardAcqID != "" && Processing != "")
                    }//if(Echo())
                }//if (this.url != "")
            }
            catch (Exception ex)
            {
                CApp.ShowMessage(ex.Message, "Cobros y Facturación", true);
            }
        }
        #endregion

        #region FrmBCR_Load
        private void FrmBCR_Load(object sender, EventArgs e)
        {
            try
            {
                RegistryKey llave = Registry.CurrentUser;
                llave = llave.OpenSubKey(@"Software\Logistika\POS Retail 8.0.0");

                if (llave != null)
                {
                    string tipoLec = llave.GetValue("TipoLector", "").ToString();//Tipo Card Reader

                    if (tipoLec != "")
                    {
                        string msr = llave.GetValue("NombreLector", "").ToString();

                        if (msr != "")
                        {
                            if (tipoLec.ToUpper() == "UPOS")
                            {
                                int res = omsr.Open(msr);
                                if (res == (int)OPOS_Constants.OPOS_SUCCESS)//Si res es distinto a OPOS_Constants.OPOS_SUCCESS
                                {
                                    #region msr upos
                                    omsr.ClaimDevice(1000);

                                    _IOPOSMSREvents_StatusUpdateEventEventHandler sue = new _IOPOSMSREvents_StatusUpdateEventEventHandler(statusUpdateOccurred);
                                    omsr.StatusUpdateEvent += sue;
                                    _IOPOSMSREvents_DataEventEventHandler de = new _IOPOSMSREvents_DataEventEventHandler(dataOccurred);
                                    omsr.DataEvent += de;
                                    _IOPOSMSREvents_ErrorEventEventHandler ee = new _IOPOSMSREvents_ErrorEventEventHandler(errorOccurred);
                                    omsr.ErrorEvent += ee;

                                    omsr.DeviceEnabled = true;
                                    omsr.DataEventEnabled = true;
                                    omsr.ErrorReportingType = (int)OPOSMSRConstants.MSR_ERT_TRACK;

                                    if (omsr.CapJISTwo == true)
                                    {
                                        //DBCS
                                        omsr.TracksToRead = (int)OPOSMSRConstants.MSR_TR_2_4;
                                    }
                                    else
                                    {
                                        //ISO
                                        omsr.TracksToRead = (int)OPOSMSRConstants.MSR_TR_1_2_3_4;
                                    }
                                    #endregion
                                }// if (res != (int)OPOS_Constants.OPOS_SUCCESS)
                                else
                                {
                                    CApp.ShowMessage("No se puede acceder al cardreader", "Cobros y Facturación", true);
                                    this.Dispose();
                                }//else de if (res != (int)OPOS_Constants.OPOS_SUCCESS)
                            }//if (tipoLec.ToUpper() == "UPOS")
                            else if (tipoLec.ToUpper() == "SERIAL")
                            {
                                CheckForIllegalCrossThreadCalls = false;
                                sp = new SerialPort(msr);
                                sp.BaudRate = 9600;
                                sp.DataBits = 8;
                                sp.Parity = Parity.None;
                                sp.StopBits = StopBits.One;
                                sp.Handshake = Handshake.None;
                                try
                                {
                                    sp.Open();
                                    sp.DataReceived += new SerialDataReceivedEventHandler(SerialDataReceived);
                                    this.serial = true;
                                }
                                catch (System.IO.IOException) { }
                            }//else if (tipoLec.ToUpper() == "SERIAL")
                            else
                            {
                                CApp.ShowMessage("El valor de TipoLector no es válido", "Cobros y Facturación", true);
                                this.Dispose();
                            }
                        }//if (msr != "")
                        else
                        {
                            CApp.ShowMessage("No se encuentra el puerto/nombre del card reader", "Cobros y Facturación", true);
                            this.Dispose();
                        }//else de if (msr != "")
                    }//if (tipoLec != "")
                    else
                    {
                        CApp.ShowMessage("No se encuentra el tipo de card reader", "Cobros y Facturación", true);
                        this.Dispose();
                    }//else de if (tipoLec != "")
                }//if (llave != null)
                else
                {
                    CApp.ShowMessage("No se encuentra la configuración del card reader", "Cobros y Facturación", true);
                    this.Dispose();
                }//else de if (llave != null)
            }
            catch (Exception ex)
            {
                CApp.ShowMessage(ex.Message, "Cobros y Facturación", true);
            }
        }
        #endregion

        #region FrmBCR_KeyDown
        private void FrmBCR_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                switch (e.KeyCode)
                {
                    case Keys.F12:
                        if (this.sbtnAceptar.Enabled)
                            sbtnAceptar_Click(null, null);
                        break;
                    case Keys.Escape:
                        btnSalir_Click(null, null);
                        break;
                }
            }
            catch (Exception ex)
            {
                CApp.ShowMessage(ex.Message, "Cobros y Facturación", true);
            }
        }
        #endregion

        #region btnSalir_Click
        private void btnSalir_Click(object sender, EventArgs e)
        {
            this.Motivo = "Transacción cancelada";

            if (serial)
            {
                sp.Close();
                sp = new SerialPort();
            }
            else
            {
                if (omsr.Claimed)
                {
                    omsr.Close();
                    omsr = new OPOSMSRClass();
                }
            }
            this.Dispose();
        }
        #endregion

        #region sbtnAceptar_Click
        private void sbtnAceptar_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.anulacion)
                    Anulacion();
                else
                    Venta();

                if (serial)
                {
                    sp.Close();
                    sp = new SerialPort();
                }
                else
                {
                    if (omsr.Claimed)
                    {
                        omsr.Close();
                        omsr = new OPOSMSRClass();
                    }
                }
                this.Dispose();
            }
            catch (Exception ex)
            {
                CApp.ShowMessage(ex.Message, "Cobros y Facturación", true);
            }
        }
        #endregion
    }
}