
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Cosmos.BaseFrame;
using Cosmos.UserFrame;
using Cosmos.ServiceProvider;
using Cosmos.Common;
using Cosmos.CommonManager;
using System.Threading;
using System.Collections;
using SPC.Kiosk.Common;
using SPC.Kiosk.Popup.Model;
using System.Data;

namespace SPC.Kiosk.Payments
{
    /// <summary>
    /// POS HappyPoint Approval Process
    /// </summary>
    public class posHappyPoint : IDisposable
    {
        //UserLog.WriteLogFile(UserCom.LOG_ERROR, "SPC.Kiosk.Payments", "posHappyPoint.?", "Exception." + ex.Message);
        #region [ Members ]
        /// <summary>
        /// HappyPointCertify ErrorCode
        /// </summary>
        public enum ErrorCode
        {
            HappyPointCertifyMobilePhoneNumberError,
            HappyPointCertifyMobileCardNumberError,
            HappyPointCertifyMemInfoEncryptedCardNoError,
            HappyPointCertifyEncrtipError,
            HappyPointCertifyNotInitailzedError,
            HappyPointCertifyProcessingTimeOut,
            HappyPointUsingPointsError,
            HappyCouponCannotUse,
            HappyPointUnknownError,
        }
        /// <summary>
        /// ErrorMessage Event
        /// </summary>
        /// <param name="LogString">반환 로그</param>
        public delegate void ErrorMessageEventHandler(string ErrorString);
        /// <summary>
        ///  로그메세지 이벤트 반환용 
        /// </summary>
        public event ErrorMessageEventHandler ErrorMessageEvent;
        /// <summary>
        /// Error 반환 Event
        /// </summary>
        /// <param name="errorCode">반환 Error Code</param>
        public delegate void LogErrorHandler(ErrorCode errorCode);
        /// <summary>
        ///  Error Code 이벤트 반환용 
        /// </summary>
        public event LogErrorHandler ErrorEvent;
        /// <summary>
        /// IcReadStart Event
        /// </summary>
        /// <param name="sender"></param>
        public delegate void IcReadStart(object sender);
        /// <summary>
        /// IcReadStart Event 반환용 
        /// </summary>
        public event IcReadStart ReadStart;
        /// <summary>
        /// IcReadStart Event
        /// </summary>
        /// <param name="sender"></param>
        public delegate void IcReadEnd(object sender);
        /// <summary>
        /// IcReadStart Event 반환용 
        /// </summary>
        public event IcReadEnd ReadEnd;

        private SManager sManager = null;                                // 이 객체를 통해 업무 Service 호출
        private StateServer StateObject = null;                          // StateObject : StateServer Object (객체)
        private PosStatus m_cPosStatus = null;                           // 기본정보 참조
        private TranStatus m_cTrnStatus = null;                          // 거래정보 참조        
        private DeviceStatus m_cDevStatus = null;                        // 디바이스 관리
        private PosOLEDevice.DelegateIcReader delegateReader;            // IC리더 콜백
        private IICReaderUs m_cDeviceICReader = null;
        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스


        private IPaymentUs m_cHappyPointUse = null;


        /// <summary>
        /// 대상 금액
        /// </summary>
        private double m_nDestAmt = 0;
        /// <summary>
        /// 상품 선택 행(-1:전체)
        /// </summary>
        private string m_sSelRow = "-1";


        /// <summary>
        /// 입력구분
        /// </summary>
        private string m_sInPutType = "";
        /// <summary>
        /// 입력데이터
        /// </summary>
        private string m_sInPutData = "";
        /// <summary>
        /// 마스킹데이터
        /// </summary>
        private string m_sInMaskData = "";
        /// <summary>
        /// 카드데이터(암호화)
        /// </summary>
        private string m_sInEncData = "";
        /// <summary>
        /// 서비스코드
        /// </summary>
        private string m_sServiceCode = "";
        /// <summary>
        /// 승인카드번호
        /// </summary>
        private string m_sAppCardNo = "";
        /// <summary>
        /// 조회 성공 여부
        /// </summary>
        private bool m_bSearchSuccess = false;
        /// <summary>
        /// POS 초기화 필요 유무
        /// </summary>
        public bool NeedInitModule { get; set; } 
        /// <summary>
        /// 승인 수단 
        /// </summary>
        public string CertifyKey { get; set; } = string.Empty;
        private bool icCallBack = false;
        /// <summary>
        /// Ic Reader CallBack  Switch
        /// </summary>
        public bool IcCallBack
        {
            get { return icCallBack; }
            set
            {
                if (value)
                {
                    m_cDeviceICReader.RegIcCallback(delegateReader);
                }
                icCallBack = value;
            }
        }
        /// <summary>
        /// 마스크된 회원성명
        /// </summary>
        public string MemberName { get; protected set; } = string.Empty;
        public string MemberNumber { get; protected set; } = string.Empty;
        /// <summary>
        /// SPC 임직원 유무
        /// </summary>
        public bool IsCompanyMember { get; protected set; }
        /// <summary>
        /// 적립 가능 유무
        /// </summary>
        public bool CanReservePoint { get; protected set; }
        /// <summary>
        /// 회원 등급
        /// </summary>
        public string MemberLevel { get; protected set; } = string.Empty;
        /// <summary>
        /// 회원 비밀번호
        /// </summary>
        public string MemberPassword { get; protected set; } = string.Empty;
        /// <summary>
        /// HappyApp 가입 고객
        /// </summary>
        public bool IsAppMamber { get; protected set; } = false;
        /// <summary>
        /// 단골 매장 유무
        /// </summary>
        public bool IsFavoriteStore { get; protected set; } = false;
        /// <summary>
        /// 회원 적립 Point
        /// </summary>
        public double MemberPoint { get; protected set; } = 0d;
        /// <summary>
        /// 회원 가용 Point
        /// </summary>
        public double UseablePoint { get; protected set; } = 0d;
        /// <summary>
        /// 승인 요청 포인트
        /// </summary>
        public double UseingPoint { get;  set; } = 0d;
        /// <summary>
        /// 승인 포인트
        /// </summary>
        public double ApprovalPoint { get; protected set; } = 0d;
        /// <summary>
        /// Point 사용시 비번 필요 유무
        /// </summary>
        public bool NeedPassword { get;  protected set; }

        public long PaySEQ { get; protected set; }
        /// <summary>
        /// 인증 처리 성공 유무
        /// </summary>
        public bool ProcessOK
        {
            get { return m_bSearchSuccess; }
        }
        /// <summary>
        /// Processing TimeOut
        /// </summary>
        public bool IsTimeout
        {
            set
            {
                if (value)
                {
                    ErrorEvent(ErrorCode.HappyPointCertifyProcessingTimeOut);
                }
            }
        }
        public List<M_HappyCoupon> MyHappyCoupons { get; protected set; } = new List<M_HappyCoupon>();
        public M_HappyCoupon UsedCoupon { get; protected set; } 
        #endregion

        #region [ Ctor  && Dispose ]
        /// <summary>
        /// Ctor
        /// </summary>
        public posHappyPoint()
        {
            try
            {
                sManager = new SManager();
                StateObject = (StateServer)StateServer.GetInstance();
                NeedInitModule = StateObject.POS == null
                               || StateObject.TRAN == null
                               || StateObject.DEVICE == null;
                if (!NeedInitModule)
                {
                    m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
                    m_cTrnStatus = (TranStatus)StateObject.TRAN;    // POS 거래정보 
                    m_cDevStatus = (DeviceStatus)StateObject.DEVICE;
                    m_cDeviceICReader = (IICReaderUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_ICREADER);
                    m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);

                    m_cHappyPointUse = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.POINTHAPPYPOINTUSE);

                    delegateReader = new PosOLEDevice.DelegateIcReader(OnIcReaderCallBack);     // IC리더 콜백
                }
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "Ctor", "Fail", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            try
            {
                InDataToZeroFill();

                sManager = null;
                StateObject = null;
                m_cPosStatus = null;      // POS 기본정보
                m_cTrnStatus = null;    // POS 거래정보 
                m_cDevStatus = null;
                m_cDataCommon = null;
                m_cDeviceICReader = null;
                delegateReader = null;     // IC리더 콜백
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "Dispose", "Fail", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }
        #endregion

        #region [ Methods ]
        /// <summary>
        /// HappyPoint 회원 조회 (16 자리이면 Mobile BarCode, 그외는 전화 번호)
        /// </summary>
        /// <param name="_inputString"></param>
        public void StartCertifyProcessing(string _inputString)
        {
            try
            {
                CommonLog.InfoLogWrite(this, "StartCertifyProcessing()", "Start");
                SendReadStart();
                if (NeedInitModule)
                {
                    Thread.Sleep(1000); //진행창 보이기 위한 딜레이
                    ErrorEvent(ErrorCode.HappyPointCertifyNotInitailzedError);
                }
                else
                {
                    var startPorcess = false;
                    if (_inputString.Replace("=", "").Replace("@", "").Length.Equals(16))
                    {
                        // Mobile BarCode
                        if (CmUtil.CheckHappyMobileCard(_inputString))
                        {
                            m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_MOBILE_SWIP;
                            m_sInMaskData = m_sAppCardNo = _inputString.Replace("=", "").Replace("@", "");
                            m_sInPutData = _inputString + "@";
                            startPorcess = true;
                        }
                        else
                        {
                            SendErrLogEvent(ErrorCode.HappyPointCertifyMobileCardNumberError);
                        }
                    }
                    else
                    {
                        // 전화 번호
                        if (IsCellularPhoneNumber(_inputString))
                        {
                            m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_KEYIN;
                            m_sInMaskData = m_sAppCardNo = m_sInPutData = _inputString;
                            startPorcess = true;

                        }
                        else
                        {
                            SendErrLogEvent(ErrorCode.HappyPointCertifyMobilePhoneNumberError);
                        }
                    }
                    //조회 전문 처리
                    if (startPorcess)
                    {
                        if (EncryptedCardNo(m_sInPutData, ref m_sInMaskData, ref m_sInEncData))
                        {
                            SearchTxtInPut();
                        }
                        else
                        {
                            SendErrLogEvent(ErrorCode.HappyPointCertifyEncrtipError);
                        }
                    }

                }
                SendReadEnd();
                CommonLog.InfoLogWrite(this, "StartCertifyProcessing()", string.Format("End : Result={0}", ProcessOK ? "OK" : "Fail"));

            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "StartCertifyProcessing()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }
        /// <summary>
        /// 쿠폰 사용 처리
        /// </summary>
        /// <param name="_inputString"></param>
        /// <param name="_totalPrice"></param>
        public void StartCouponProcessing(string _inputString, double _totalPrice)
        {
            try
            {
                CommonLog.InfoLogWrite(this, "StartCouponProcessing()", "Start");
                SendReadStart();
                if (NeedInitModule)
                {
                    Thread.Sleep(1000); //진행창 보이기 위한 딜레이
                    ErrorEvent(ErrorCode.HappyPointCertifyNotInitailzedError);
                }
                else
                {
                    var startPorcess = false;
                    if (_inputString.Length < 11)
                    {
                        SendErrLogEvent(ErrorCode.HappyCouponCannotUse);
                    }
                    else
                    {
                        m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_KEYIN;
                        m_sInMaskData = m_sAppCardNo = m_sInPutData = _inputString;
                        m_nDestAmt = _totalPrice;
                        startPorcess = true;

                    }
                    if (startPorcess)
                    {
                        if (EncryptedCardNo(m_sInPutData, ref m_sInMaskData, ref m_sInEncData))
                        {
                            CouponCompleteTxtInPut();
                        }
                        else
                        {
                            SendErrLogEvent(ErrorCode.HappyPointCertifyEncrtipError);
                        }
                    }

                }
                SendReadEnd();
                CommonLog.InfoLogWrite(this, "StartCouponProcessing()", string.Format("End : Result={0}", ProcessOK ? "OK" : "Fail"));

            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "StartCouponProcessing()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }
        /// <summary>
        /// 해피포인트 사용을 위한 조회
        /// </summary>
        private bool SearchTxtInPutForUsing()
        {
            string sRet = UserCom.RST_ERR;
            try
            {   
                m_bSearchSuccess = false;
                var m_sPosMenuKey = PosKey.MENU_KEY.HAPPY_POINT_USE;

                // 조회
                string[] saRecvdData = null;
                sRet = m_cHappyPointUse.SearchPayment(new string[] { m_sPosMenuKey, m_sInPutType, m_sInMaskData, m_sInEncData, "1", m_sAppCardNo }, ref saRecvdData);
                if (sRet != UserCom.RST_OK)
                {
                    InDataToZeroFill();
                    return false;
                }

                Column.TR_PAYMENT.DATA cPayItem = (Column.TR_PAYMENT.DATA)m_cHappyPointUse.GetPayment(new string[] { });

                var m_bPassWord = true;
                if (cPayItem.HP_ADD_INFO_SCH.Trim() != "")
                {
                    int nNowPos = 0;
                    string[] aIrtRsp = new string[Column.POINT_ADD_INFO_SEARCH.LEN.Length];
                    ItemColumn.ParseMessage(Column.POINT_ADD_INFO_SEARCH.LEN, Column.POINT_ADD_INFO_SEARCH.TYPE, Encoding.Default.GetBytes(cPayItem.HP_ADD_INFO_SCH), ref nNowPos, ref aIrtRsp);

                    if (aIrtRsp[Column.POINT_ADD_INFO_SEARCH.SEQ.pointHPUSEYN] != "Y")
                    {
                        //WinManager.ConfirmMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0139));
                        return false;
                    }
                    m_bPassWord = (aIrtRsp[Column.POINT_ADD_INFO_SEARCH.SEQ.pointHPUSEPWYN] == "Y") ? true : false;

                    if (m_sInPutData.StartsWith(PosConst.HP_CARD_PRIFIX) == false)
                    {
                        // 고객정보
                        string sMemInfo = aIrtRsp[Column.POINT_ADD_INFO_SEARCH.SEQ.pointMEMINFO].Trim();
                        if (sMemInfo.Length >= 17 && CmUtil.LongParse(sMemInfo.Substring(0, 1)) > 0)
                        {
                            string sInPutData = sMemInfo.Substring(1, 16).Trim();        // 카드번호
                            string sInMaskData = "";
                            if (EncryptedCardNo(sInPutData, ref sInMaskData, ref m_sInEncData) == false) return false;
                            cPayItem.CanFiller1 = m_sInEncData;

                            cPayItem.OCCUR_ENTRY_14 = m_sAppCardNo = sInPutData;        // 승인카드번호
                        }
                    }

                    //#20171017 전자영수증 발행 start, phj
                    cPayItem.OCCUR_ENTRY_23 = CmUtil.MidH(cPayItem.HP_ADD_INFO_SCH, 144, 1).Trim();
                    //#20171017 전자영수증 발행 end, phj
                }

                if (cPayItem.OCCUR_ENTRY_12 == "Y")
                {
                    m_cTrnStatus.Sale.HappyBuzzMemNo = m_sInPutData;
                }

                cPayItem.CanFiller3 = m_sInPutData;

                // MoonSeokWoo 2017.09.26 마이원 카드 제약조건 제거.
                //if (cPayItem.HP_RESERVED.StartsWith("M") == true)       // 마이원카드 사용 불가
                //{
                //    WinManager.ConfirmMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0139));
                //    return false;
                //}

                
                // 할인 대상상품 합계
                double nDestPluAmt = 0;
                ArrayList alTrPluItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);
                foreach (Column.TR_PLU.DATA cPluItem in alTrPluItem)
                {
                    if (cPluItem.CANCEL_DIV == PosConst.CANCEL_DIV.CANCEL || cPluItem.CANCEL_DIV_MAIN == PosConst.CANCEL_DIV.CANCEL) continue;  // 지정취소
                    if (cPluItem.alTrSaleCpi == null) continue;

                    foreach (Column.TR_SALE_CPI_RSLT.DATA cTrSaleCpi in cPluItem.alTrSaleCpi)
                    {
                        if (cTrSaleCpi.TRGT_CUST_TYPE == ItemConst.CPI_TRGT_CUST_TYPE.HPC_PAY && cTrSaleCpi.DC_SUM_AMT > 0)
                        {
                            nDestPluAmt = CmUtil.DoubleAdd(nDestPluAmt, cPluItem.BILL_AMT);
                            break;
                        }
                    }
                }

                //// 결제포인트
                //txtUsePoint.Value = (m_nRemainPayAmt > cPayItem.AMT_ENTRY_04) ? cPayItem.AMT_ENTRY_04.ToString() : m_nRemainPayAmt.ToString();


                //#20180821 해피포인트 고객이름 마스킹 start
                if (cPayItem.HP_CUST_NAME != "") { cPayItem.HP_CUST_NAME = m_cDataCommon.NameMasking(cPayItem.HP_CUST_NAME); }
                //#20180821 해피포인트 고객이름 마스킹 end

                //lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0109) + "  [ " + cPayItem.HP_CUST_NAME + " ]";
                m_bSearchSuccess = true;
                return true;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            return false;
        }


        /// <summary>
        /// 해피 포인트 사용 처리
        /// </summary>
        /// <param name="_inputString"></param>
        /// <param name="_usingPoints"></param>
        /// <param name="_memberPassword"></param>
        public void StartPaymentProcessing(string _inputString, double _usingPoints,string _memberPassword)
        {
            try
            {
                CommonLog.InfoLogWrite(this, "StartPaymentProcessing()", "Start");
                SendReadStart();
                if (NeedInitModule)
                {
                    Thread.Sleep(3000); //진행창 보이기 위한 딜레이
                    ErrorEvent(ErrorCode.HappyPointCertifyNotInitailzedError);
                }
                else
                {
                    var startPorcess = false;
                    if (_inputString.Replace("=", "").Replace("@", "").Length.Equals(16)
                        && _usingPoints > 0)
                    {
                        UseingPoint = _usingPoints;
                        m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_MOBILE_SWIP;
                        m_sInMaskData = _inputString;
                        m_sInPutData = _inputString + "@";
                        startPorcess = true;
                    }
                    else
                    {
                        SendErrLogEvent(ErrorCode.HappyPointUsingPointsError);
                    }
                    //승인 전문 처리
                    if (startPorcess)
                    {
                        if (EncryptedCardNo(m_sInPutData, ref m_sInMaskData, ref m_sInEncData))
                        {
                            if (SearchTxtInPutForUsing())   CompleteTxtInPut();
                            else SendErrLogEvent(ErrorCode.HappyPointCertifyEncrtipError);
                        }
                        else
                        {
                            SendErrLogEvent(ErrorCode.HappyPointCertifyEncrtipError);
                        }
                    }

                }
                SendReadEnd();
                CommonLog.InfoLogWrite(this, "StartPaymentProcessing()", string.Format("End : Result={0}", ProcessOK ? "OK" : "Fail"));

            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "StartPaymentProcessing()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }
        /// <summary>
        /// 단골 매장 처리
        /// </summary>
        /// <param name="sReqDivCd"></param>
        /// <returns></returns>
        public void StartFavoriteStoreProcess(string _inputString, bool _regType)
        {
            CommonLog.InfoLogWrite(this, "StartFavoriteStoreProcess()", "Start");
            SendReadStart();
            if (NeedInitModule)
            {
                Thread.Sleep(3000); //진행창 보이기 위한 딜레이
                ErrorEvent(ErrorCode.HappyPointCertifyNotInitailzedError);
            }
            else
            {
                var m_cHappyPoint = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.POINTHPREGULARCUST);
                m_bSearchSuccess = false;
                try
                {
                    var sReqDivCd = _regType ? "10" : "11";
                    if (_inputString.Length > 15)
                    {
                        m_sInPutData = string.Format("{0}@", _inputString.Substring(0, 16));
                        m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_MOBILE_SWIP;
                    }
                    else
                    {
                        m_sInPutData = _inputString;
                        m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_KEYIN;
                    }
                    if (EncryptedCardNo(m_sInPutData, ref m_sInMaskData, ref m_sInEncData))
                    {
                        var sRet = m_cHappyPoint.SetPayment(new string[] { m_sInPutType, m_sInMaskData, m_sInEncData, sReqDivCd });
                        if (sRet != UserCom.RST_OK)
                        {
                            InDataToZeroFill();
                            if (sRet == null || sRet.Equals(UserCom.RST_ERR))
                            {
                                SendErrLogEvent(ErrorCode.HappyPointUnknownError);
                            }
                            else
                            {
                                SendErrorMessageEvent(sRet);
                            }
                        }
                        else
                        {
                            m_bSearchSuccess = true;
                        }
                    }
                    else
                    {
                        SendErrLogEvent(ErrorCode.HappyPointCertifyEncrtipError);
                    }
                }
                catch (Exception ex)
                {
                    CommonLog.ErrorLogWrite(this, "StartFavoriteStoreProcess()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
                }
            }
            SendReadEnd();
            CommonLog.InfoLogWrite(this, "StartFavoriteStoreProcess()", string.Format("End : Result={0}", ProcessOK ? "OK" : "Fail"));
        }


        /// <summary>
        /// 휴대폰 번호 형식 확인
        /// </summary>
        /// <param name="sInputData"></param>
        /// <returns></returns>
        private bool IsCellularPhoneNumber(string sInputData)
        {
            bool bRet = false;
            try
            {
                if (sInputData.Length == 10 || sInputData.Length == 11)
                {
                    if (sInputData.StartsWith("010") == true || sInputData.StartsWith("011") == true || sInputData.StartsWith("017") == true ||
                       sInputData.StartsWith("016") == true || sInputData.StartsWith("018") == true || sInputData.StartsWith("019") == true)
                    {
                        bRet = true;
                    }
                }
            }
            catch 
            {
                bRet = false;
            }
            return bRet;
        }
        /// <summary>
        /// Happoint 조회 전문 처리
        /// </summary>
        private void SearchTxtInPut()
        {
            CommonLog.DebugLogWrite(this, "SearchTxtInPut()", "Start");
            var m_cHappyPoint = (IPaymentExpUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.POINTHAPPYPOINT);
            string sRet = UserCom.RST_ERR;
            try
            {

                m_bSearchSuccess = false;
                string[] saRecvdData = null;
                sRet = m_cHappyPoint.SearchPayment(new string[] { m_sInPutType, m_sInMaskData, m_sInEncData, "0", "", m_sAppCardNo }, ref saRecvdData);
                if (sRet != UserCom.RST_OK)
                {
                    CertifyKey = string.Empty;
                    InDataToZeroFill();
                    if (sRet == null || sRet.Equals(UserCom.RST_ERR))
                    {
                        SendErrLogEvent(ErrorCode.HappyPointUnknownError);
                    }
                    else
                    {
                        SendErrorMessageEvent(sRet);
                    }
                }
                else
                {
                    CertifyKey = m_sAppCardNo;
                    var cPointItem = (Column.TR_ETC.DATA)m_cHappyPoint.GetPayment(new string[] { });

                    NeedPassword = true;
                    if (cPointItem.HP_ADD_INFO_SCH.Trim() != "")
                    {
                        int nNowPos = 0;
                        string[] aIrtRsp = new string[Column.POINT_ADD_INFO_SEARCH.LEN.Length];
                        ItemColumn.ParseMessage(Column.POINT_ADD_INFO_SEARCH.LEN, Column.POINT_ADD_INFO_SEARCH.TYPE, Encoding.Default.GetBytes(cPointItem.HP_ADD_INFO_SCH), ref nNowPos, ref aIrtRsp);
                        MemberNumber = cPointItem.OCCUR_ENTRY_10;
                        MemberLevel = cPointItem.OCCUR_ENTRY_15;
                        MemberPoint = cPointItem.AMT_ENTRY_03;
                        UseablePoint = cPointItem.AMT_ENTRY_04;
                        IsAppMamber = cPointItem.OCCUR_ENTRY_12.ToUpper().Equals("Y");
                        IsCompanyMember = cPointItem.ETC_DTL_CD_04.StartsWith("3A");
                        CanReservePoint = aIrtRsp[Column.POINT_ADD_INFO_SEARCH.SEQ.pointHPADDYN].Equals("Y");
                        NeedPassword = (aIrtRsp[Column.POINT_ADD_INFO_SEARCH.SEQ.pointHPUSEPWYN] == "Y") ? true : false;

                        // 고객정보
                        string sMemInfo = aIrtRsp[Column.POINT_ADD_INFO_SEARCH.SEQ.pointMEMINFO].Trim();
                        if (sMemInfo.Length >= 17 && CmUtil.LongParse(sMemInfo.Substring(0, 1)) > 0)
                        {
                            string sInPutData = sMemInfo.Substring(1, 16).Trim();        // 카드번호
                            string sInMaskData = "";
                            IsFavoriteStore = sMemInfo.Substring(53, 1).Equals("Y");
                            if (EncryptedCardNo(sInPutData, ref sInMaskData, ref m_sInEncData) == false)
                            {
                                SendErrLogEvent(ErrorCode.HappyPointCertifyMemInfoEncryptedCardNoError);
                                return;
                            }
                            cPointItem.CanFiller1 = m_sInEncData;
                        }

                        //#20171017 전자영수증 발행 start, phj
                        cPointItem.OCCUR_ENTRY_23 = CmUtil.MidH(cPointItem.HP_ADD_INFO_SCH, 144, 1).Trim();
                        //#20171017 전자영수증 발행 end, phj
                    }

                    if (cPointItem.OCCUR_ENTRY_12 == "Y")
                    {
                        m_cTrnStatus.Sale.HappyBuzzMemNo = m_sInPutData;
                    }

                    cPointItem.CanFiller3 = m_sInPutData;
                    MemberName = cPointItem.HP_CUST_NAME;

                    #region InCard Coupon Query
                    var m_cHappyCoupon = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.POINTHAPPYCOUPON);
                    try
                    {
                        sRet = m_cHappyCoupon.SearchPayment(new string[] { m_sInPutType, m_sInPutData, m_sInEncData, "1" }, ref saRecvdData);
                        if (sRet.Equals(UserCom.RST_OK))
                        {
                            var cPayItem2 = (Column.TR_PAYMENT.DATA)m_cHappyCoupon.GetPayment(new string[] { });
                            var aHP_CPN_INFO = cPayItem2.HP_CPN_INFO;
                            if (aHP_CPN_INFO is ArrayList && aHP_CPN_INFO.Count > 0)
                            {
                                var newCouponData = new List<M_HappyCoupon>();
                                foreach (var aCouponData in aHP_CPN_INFO)
                                {
                                    if (aCouponData is string[] aCouponInfos
                                        && aCouponInfos.Length > 3)
                                    {
                                        var couponName = CmUtil.MidH(aCouponInfos[1], 0, 40);
                                        var aNewCouponData = new M_HappyCoupon
                                        {
                                            Number = string.IsNullOrEmpty(aCouponInfos[0])
                                                   ? string.Empty
                                                   : aCouponInfos[0].Trim(),
                                            Name = string.IsNullOrEmpty(couponName)
                                                   ? string.Empty
                                                   : couponName.Trim(),
                                            StartDate = CommonFunction.GetDate(aCouponInfos[2]),
                                            EndDate = CommonFunction.GetDate(aCouponInfos[2]),
                                        };
                                        newCouponData.Add(aNewCouponData);
                                    }
                                }
                                MyHappyCoupons = newCouponData;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        CommonLog.ErrorLogWrite(this, "SearchTxtInPut()", "Coupon Search Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
                    }
                    finally
                    {
                        m_cHappyCoupon = null;
                    } 
                    #endregion
                    m_bSearchSuccess = true;
                }
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "SearchTxtInPut()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
            finally
            {
                m_cHappyPoint = null;
            }
            CommonLog.DebugLogWrite(this, "SearchTxtInPut()", "End");
        }

        /// <summary>
        /// 포인트 사용 승인 처리
        /// </summary>
        /// <returns></returns>
        private void CompleteTxtInPut()
        {
            CommonLog.DebugLogWrite(this, "CompleteTxtInPut()", "Start");
            //var m_cHappyPointUse = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.POINTHAPPYPOINTUSE);
            string sRet = UserCom.RST_ERR;
            try
            {
                m_bSearchSuccess = false;
                var m_sPosMenuKey = PosKey.MENU_KEY.HAPPY_POINT_USE;
                // 포인트 사용 승인 처리
                sRet = m_cHappyPointUse.SetPayment(new string[] { m_sPosMenuKey, m_sInPutType, m_sInMaskData, m_sInEncData, UseingPoint.ToString(), MemberPassword, m_sAppCardNo, "", "" });
                if (sRet != UserCom.RST_OK)
                {
                    CertifyKey = string.Empty;
                    MemberPassword = string.Empty;
                    InDataToZeroFill();
                    if (sRet == null || sRet.Equals(UserCom.RST_ERR))
                    {
                        SendErrLogEvent(ErrorCode.HappyPointUnknownError);
                    }
                    else
                    {
                        SendErrorMessageEvent(sRet);
                    }
                }
                else
                {
                    var cPointItem = (Column.TR_PAYMENT.DATA)m_cHappyPointUse.GetPayment(new string[] { });
                    PaySEQ = cPointItem.SEQ;
                    ApprovalPoint = UseingPoint;
                    m_bSearchSuccess = true;
                }
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "CompleteTxtInPut()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
            finally
            {
                m_cHappyPointUse = null;
            }
            CommonLog.DebugLogWrite(this, "CompleteTxtInPut()", "End");
        }
        /// <summary>
        /// 쿠폰 사용 승인 전문
        /// </summary>
        private void CouponCompleteTxtInPut()
        {
            CommonLog.DebugLogWrite(this, "CouponCompleteTxtInPut()", "Start");
            var m_cHappyCoupon = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.POINTHAPPYCOUPON);
            string sRet = UserCom.RST_ERR;
            try
            {
                m_bSearchSuccess = false;
                // 해피쿠폰 조회
                string[] saRecvdData = null;
                sRet = m_cHappyCoupon.SearchPayment(new string[] { m_sInPutType, m_sInPutData, m_sInEncData, "0" }, ref saRecvdData);
                if (sRet != UserCom.RST_OK)
                {
                    CertifyKey = string.Empty;
                    InDataToZeroFill();
                    if (sRet == null || sRet.Equals(UserCom.RST_ERR))
                    {
                        SendErrLogEvent(ErrorCode.HappyPointUnknownError);
                    }
                    else
                    {
                        SendErrorMessageEvent(sRet);
                    }
                }
                else
                {
                    var cPayItem = (Column.TR_PAYMENT.DATA)m_cHappyCoupon.GetPayment(new string[] { });
                    var aprovalProcessStart = false;
                    //내려온 제품군 또는 상품코드가 존재 할 때
                    if (cPayItem.CpnItemDcCode != "")
                    {
                        // 제품군 코드가 내려왔으면  제품군에 속하고, 등록 된 상품을 화면에 보여주고, 사용자가 선택한 제품 할인적용.
                        // 상품코드가 내려왔으면 바로 해당 상품으로 할인적용.
                        if (ChoiceCpnItem(cPayItem.CpnItemDcCode) == false)
                        {
                            SendErrLogEvent(ErrorCode.HappyCouponCannotUse);
                        }
                        else
                        {
                            aprovalProcessStart = true;
                        }
                    }
                    //내려온 제품군 또는 상품코드가 존재하지 않을 때
                    else
                    {

                        // 전체금액 대상
                        m_sSelRow = "-1";
                        aprovalProcessStart = true;
                    }
                    if (aprovalProcessStart)
                    {
                        // 해피포인트 쿠폰 등록 처리
                        sRet = m_cHappyCoupon.SetPayment(new string[] { m_sInPutType, m_sInPutData, m_sInEncData, m_nDestAmt.ToString(), m_sSelRow });
                        if (sRet != UserCom.RST_OK)
                        {
                            if (sRet == null || sRet.Equals(UserCom.RST_ERR))
                            {
                                SendErrLogEvent(ErrorCode.HappyPointUnknownError);
                            }
                            else
                            {
                                SendErrorMessageEvent(sRet);
                            }
                        }
                        else
                        {
                            var cPayItem2 = (Column.TR_PAYMENT.DATA)m_cHappyCoupon.GetPayment(new string[] { });
                            UsedCoupon = new M_HappyCoupon
                            {
                                Number = cPayItem.OCCUR_ENTRY_01,
                                Name = cPayItem.CanFiller2,
                                IsUsed = true,
                                PaySEQ = cPayItem2.SEQ,
                                UseAmount = cPayItem2.PAY_AMT,
                            };
                            m_bSearchSuccess = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "CouponCompleteTxtInPut()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
            finally
            {
                m_cHappyCoupon = null;
            }
            CommonLog.DebugLogWrite(this, "CouponCompleteTxtInPut()", "End");
        }


        #region ChoicePluItem (대상 상품 선택)
        /// <summary>
        /// 대상 상품 선택
        /// </summary>
        /// <returns></returns>
        private bool ChoiceCpnItem(string CpnItemDcCode)
        {

            #region  변경
            string CpnItemDcType = string.Empty;
            string sItemNm = string.Empty;
            string sItemCode = string.Empty;
            bool bItemCheck = false; // false: 등록된상품과 일치된상품없음. true: 등록된상품과 일치된상품있음.
            double dPayAmt = -1;

            //#20180502 온라인쿠폰 제품군, 상품코드 할인 적용 기능 적용 start
            string sGubun = string.Empty;
            //#20180502 온라인쿠폰 제품군, 상품코드 할인 적용 기능 적용 end

            try
            {
                // 제품군의 속한 상품 리스트를 가져온다.
                // 조회응답전문에 코드는 내려왔는데 제품군 마스터에 존재하지 않으면 상품코드로 간주한다.
                DataTable dtCpnItemDcList = null;
                dtCpnItemDcList = m_cDataCommon.CpnItemDCTargetList(CpnItemDcCode);
                if (dtCpnItemDcList == null || dtCpnItemDcList.Rows.Count == 0)
                {
                    // 상품코드
                    CpnItemDcType = "2";
                }
                else
                {
                    // 제품군 
                    CpnItemDcType = "1";


                    //#20180502 온라인쿠폰 제품군, 상품코드 할인 적용 기능 적용 start 
                    DataRow dr = dtCpnItemDcList.Rows[0];
                    // 00: 일반제품군, 01: 대분류 코드 ,02: 중분류 코드 ,03: 소분류 코드
                    sGubun = CmUtil.GetDataRowStr(dr, PosMst.MST_CPN_ITEM_GRP_MNG.DATA.GUBUN);
                    //#20180502 온라인쿠폰 제품군, 상품코드 할인 적용 기능 적용 end
                }


                ArrayList alPluItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);
                Column.TR_PLU.DATA cPluItem = null;
                if (CpnItemDcType == "1")
                {
                    foreach (DataRow dr in dtCpnItemDcList.Rows)
                    {
                        for (int i = 0; i < alPluItem.Count; i++)
                        {
                            cPluItem = (Column.TR_PLU.DATA)alPluItem[i];
                            if (cPluItem.CANCEL_DIV == PosConst.CANCEL_DIV.CANCEL || cPluItem.CANCEL_DIV_MAIN == PosConst.CANCEL_DIV.CANCEL) continue;    // 지정취소
                            if (cPluItem.DC_PRMT_YN == "1") continue;

                            //#20180502 온라인쿠폰 제품군, 상품코드 할인 적용 기능 적용 start
                            //기존
                            //if (CmUtil.GetDataRowStr(dr, PosMst.MST_CPN_ITEM_GRP_MNG_DTL.DATA.ITEM_CD) == cPluItem.ITEM_PLU_CD)
                            //{
                            //    if (dPayAmt > -1 && dPayAmt <= cPluItem.SALE_PRC) continue;
                            //    dPayAmt = cPluItem.SALE_PRC;// 판매단가 
                            //
                            //    m_sSelRow = i.ToString();
                            //
                            //    bItemCheck = true;
                            //    sItemNm = cPluItem.ITEM_PLU_CD;
                            //    sItemCode = cPluItem.ITEM_NAME;
                            //    break;
                            //}

                            //변경
                            if (sGubun == "00")
                            {
                                if (CmUtil.GetDataRowStr(dr, PosMst.MST_CPN_ITEM_GRP_MNG_DTL.DATA.ITEM_CD) != cPluItem.ITEM_PLU_CD) continue;
                            }
                            else if (sGubun == "01")
                            {
                                if (CmUtil.GetDataRowStr(dr, PosMst.MST_CPN_ITEM_GRP_MNG_DTL.DATA.ITEM_CD) != cPluItem.L_CLSS) continue;
                            }
                            else if (sGubun == "02")
                            {
                                if (CmUtil.GetDataRowStr(dr, PosMst.MST_CPN_ITEM_GRP_MNG_DTL.DATA.ITEM_CD) != cPluItem.M_CLSS) continue;
                            }
                            else if (sGubun == "03")
                            {
                                if (CmUtil.GetDataRowStr(dr, PosMst.MST_CPN_ITEM_GRP_MNG_DTL.DATA.ITEM_CD) != cPluItem.S_CLSS) continue;
                            }


                            //#20181030 판매단가 제일 높은 것으로 원복 start
                            //기존
                            /*
                            //#20180711 단가 제일 높은것으로 변경 start
                            //기존
                            //if (dPayAmt > -1 && dPayAmt <= cPluItem.SALE_PRC) continue;
                            //변경                            
                            //#15859 유형군 쿠폰 적용 시 오류 확인요청 start
                            //적용 대상 상품 체크시 실판매금액(BILL_AMT)로 체크 하도록 변경
                            //단가가 동일한 상품이 있는 경우 수량에 따라 적용이 안되는 경우가 생김
                            //기존
                            //if (dPayAmt > -1 && dPayAmt >= cPluItem.SALE_PRC) continue;
                            //변경
                            if (dPayAmt > -1 && dPayAmt >= cPluItem.BILL_AMT) continue;
                            //#15859 유형군 쿠폰 적용 시 오류 확인요청 end
                            //#20180711 단가 제일 높은것으로 변경 end
                            */

                            //변경
                            if (dPayAmt > -1 && dPayAmt >= cPluItem.SALE_PRC) continue;
                            //#20181030 판매단가 제일 높은 것으로 원복 end

                            //#20181030 판매단가 제일 높은 것으로 원복 start
                            //기존
                            /*
                            //#15859 유형군 쿠폰 적용 시 오류 확인요청 start
                            //적용 대상 상품 체크시 실판매금액(BILL_AMT)로 체크 하도록 변경
                            //단가가 동일한 상품이 있는 경우 수량에 따라 적용이 안되는 경우가 생김
                            //기존
                            //dPayAmt = cPluItem.SALE_PRC;// 판매단가 
                            //변경
                            dPayAmt = cPluItem.BILL_AMT;// 판매단가 
                            //#15859 유형군 쿠폰 적용 시 오류 확인요청 end
                            */
                            //변경
                            dPayAmt = cPluItem.SALE_PRC;// 판매단가 
                            //#20181030 판매단가 제일 높은 것으로 원복 end

                            m_sSelRow = i.ToString();

                            bItemCheck = true;
                            sItemNm = cPluItem.ITEM_PLU_CD;
                            sItemCode = cPluItem.ITEM_NAME;
                            //#20180502 온라인쿠폰 제품군, 상품코드 할인 적용 기능 적용 start,20180511
                            //판매단가 가장 작은 제품에 적용되지 않고 첫번째 제품에 적용됨
                            //break;
                            //#20180502 온라인쿠폰 제품군, 상품코드 할인 적용 기능 적용 end,20180511

                            //#20180502 온라인쿠폰 제품군, 상품코드 할인 적용 기능 적용 end
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < alPluItem.Count; i++)
                    {
                        cPluItem = (Column.TR_PLU.DATA)alPluItem[i];
                        if (cPluItem.CANCEL_DIV == PosConst.CANCEL_DIV.CANCEL || cPluItem.CANCEL_DIV_MAIN == PosConst.CANCEL_DIV.CANCEL) continue;    // 지정취소
                        if (cPluItem.DC_PRMT_YN == "1") continue;
                        if (cPluItem.ITEM_PLU_CD == CpnItemDcCode)
                        {
                            m_sSelRow = i.ToString();

                            bItemCheck = true;
                            sItemNm = cPluItem.ITEM_PLU_CD;
                            sItemCode = cPluItem.ITEM_NAME;
                            break;
                        }
                    }
                }


                // 등록된 상품과 응답전문의 상품코드가 일치.
                if (bItemCheck == true)
                {
                    cPluItem = (Column.TR_PLU.DATA)alPluItem[CmUtil.IntParse(m_sSelRow)];
                    m_nDestAmt = cPluItem.BILL_AMT;
                    return true;
                }
                // 등록된 상품과 응답전문의 상품코드가 불일치.
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "ChoiceCpnItem()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));

                return false;
            }
            #endregion
            //20171229 요건변경(할인대상 상품 중 제일 단가가 작은제품적용, 동일 판매가 일 경우 판매코드 제일 작은 상품) end, phj
        }
        #endregion

        /// <summary>
        /// 카드 번호 암호화
        /// </summary>
        /// <param name="sInData"></param>
        /// <param name="sInMaskData"></param>
        /// <param name="sInEncData"></param>
        /// <returns></returns>
        private bool EncryptedCardNo(string sInData, ref string sInMaskData, ref string sInEncData)
        {
            string sEncData = sInData;
            bool bRet = false;
            try
            {

                //#20170913 현금영수증, 포인트카드 마스킹 미적용 start
                // "0"인 경우 마스킹 미처리
                //기존
                //sEncData = m_cDeviceICReader.GetEncryptedCardNo(sInData).Trim();
                //변경
                sEncData = m_cDeviceICReader.GetEncryptedCardNo(sInData, "0").Trim();
                //#20170913 현금영수증, 포인트카드 마스킹 미적용 end

                if (CmUtil.MidH(sEncData, 0, 2) == "00")
                {
                    sInEncData = CmUtil.MidH(sEncData, 2, 512).Trim();                          // 암호화 데이터
                    sInMaskData = CmUtil.MidH(sEncData, 514, sEncData.Length - 514).Trim();     // 마스킹 데이터

                    //#20170913 현금영수증, 포인트카드 마스킹 미적용 start
                    sInMaskData = CmUtil.MidH(sInMaskData, 0, 6) + "********";
                    //#20170913 현금영수증, 포인트카드 마스킹 미적용 end

                    bRet = true;
                }
                else
                {
                    //암호화 처리 실패!
                    CommonLog.ErrorLogWrite(this, "EncryptedCardNo()", "Fail !!");
                }

            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "EncryptedCardNo()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
            return bRet;
        }

        #region DeviceEvent 관련


        /// <summary>
        /// IC 카드 정보 입력 처리
        /// </summary>
        /// <returns></returns>
        private bool GetIcCardData()
        {
            string sRsvStr = "";
            try
            {
                //IcCallBack = false;     // IC리더 콜백 해지

                ClearCardInfo();        // 카드 입력 정보 클리어

                if (m_cDeviceICReader.GetCardInfo_ICReader(PosConst.IC_READER_TRAN_TYPE.POINT, 0, ref sRsvStr) == true)
                {
                    if (CmUtil.MidH(sRsvStr, 0, 2) == "00")
                    {
                        m_sInEncData = CmUtil.MidH(sRsvStr, 6, 512).Trim();
                        m_sInMaskData = CmUtil.MidH(sRsvStr, 1030, 37).Trim();
                        m_sServiceCode = CmUtil.MidH(sRsvStr, 1067, 5).Trim();

                        m_sInPutData = m_sInMaskData;
                        m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_SWIP;



                        return true;
                    }
                }

            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "GetIcCardData()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
            finally
            {
                // 여전법 대응////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref sRsvStr);
                //////////////////////////////////////////////////////////////////////////////////
            }
            return false;
        }

        /// <summary>
        /// RF 카드 정보 입력 처리
        /// </summary>
        /// <returns></returns>
        private bool GetRfCardData()
        {
            string sRsvStr = "";
            try
            {
                //IcCallBack = false;             // IC리더 콜백 해지
                ClearCardInfo();        // 카드 입력 정보 클리어

                //카드 정보 입력
                if (m_cDeviceICReader.GetRfCreditCardInfo("1", m_cTrnStatus.Head.NetSaleAmt.ToString(), "", "", "", ref sRsvStr) == false)
                {
                    if (sRsvStr != "") SendErrorMessageEvent(sRsvStr);
                    return false;
                }

                m_sInEncData = CmUtil.MidH(sRsvStr, 2, 512).Trim();
                m_sInMaskData = CmUtil.MidH(sRsvStr, 514, 40).Trim();
                m_sServiceCode = CmUtil.MidH(sRsvStr, 554, 5).Trim();

                m_sInPutData = m_sInMaskData;
                m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_RF;

                //ReadBarCode= m_sInPutData.Length > 16 ? CmUtil.MidH(m_sInPutData, 0, 16) : m_sInPutData;
                return true;
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "GetRfCardData()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
            finally
            {
                // 여전법 대응////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref sRsvStr);
                //////////////////////////////////////////////////////////////////////////////////
            }
            return false;
        }

        /// <summary>
        /// POP 카드 정보 입력 처리
        /// </summary>
        /// <returns></returns>
        private bool GetPopCardData()
        {
            string sRsvStr = "";
            try
            {
                //IcCallBack = false;             // IC리더 콜백 해지

                ClearCardInfo();        // 카드 입력 정보 클리어

                if (m_cDeviceICReader.RfPrepaidCardInfo(ref sRsvStr) == false)
                {
                    if (sRsvStr != "") SendErrorMessageEvent(sRsvStr);
                    return false;
                }
                if (sRsvStr.StartsWith("T") == true)
                {
                    m_sInPutData = sRsvStr.Substring(7, 16).Trim();
                }
                else if (sRsvStr.StartsWith("E") == true)
                {
                    m_sInPutData = sRsvStr.Substring(1, 20).Trim();
                }
                else
                {
                    return false;
                }

                bool bRet = EncryptedCardNo(m_sInPutData, ref m_sInMaskData, ref m_sInEncData);
                if (bRet == true)
                {
                    m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_RF;
                }
                return bRet;
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "GetPopCardData()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
            finally
            {
                // 여전법 대응////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref sRsvStr);
                //////////////////////////////////////////////////////////////////////////////////
            }
            return false;
        }
        #endregion

        #region 여전법 대응
        /// <summary>
        /// ZeroFill 초기화
        /// </summary>
        private void InDataToZeroFill()
        {
            try
            {

                //여전법 대응!
                //////////////////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref m_sInPutData);
                CmUtil.ZeroFillClear(ref m_sInEncData);
                CmUtil.ZeroFillClear(ref m_sInMaskData);
                //////////////////////////////////////////////////////////////////////////////////
            }
            catch
            {
            }

        }
        #endregion 여전법 대응

        #region IC리더 콜백
        //delegate void DelegateIcReaderCallBack(int rc, StringBuilder str);
        /// <summary>
        /// IC리더 콜백 함수
        /// </summary>
        /// <param name="num"></param>
        /// <param name="str"></param>
        public void OnIcReaderCallBack(int num, StringBuilder str)
        {
            try
            {
                SendReadStart();
                if (num == 1)
                {
                    GetIcCardData();
                }
                else
                {
                    if (str.ToString().StartsWith("EN"))
                    {
                        ClearCardInfo();        // 카드 입력 정보 클리어

                        m_sInEncData = CmUtil.MidH(str.ToString(), 0, 512).Trim();
                        m_sInMaskData = CmUtil.MidH(str.ToString(), 512, 40).Trim();
                        m_sInPutData = m_sInMaskData;
                        m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_SWIP;
                    }
                }
                if (!string.IsNullOrEmpty(m_sInPutData)) SearchTxtInPut();
                SendReadEnd();
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "OnIcReaderCallBack()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }
        #endregion

        #region Call Process에 이벤트 전송
        private void SendErrorMessageEvent(string _errorMessageString)
        {
            try
            {
                CommonLog.ErrorLogWrite(this, "SendErrorMessageEvent()", _errorMessageString);
                ErrorMessageEvent(_errorMessageString);
            }
            catch
            {
            }
        }
        private void SendErrLogEvent(ErrorCode _errorCode)
        {
            try
            {
                CommonLog.DebugLogWrite(this, "SendErrLogEvent()", _errorCode.ToString());
                ErrorEvent(_errorCode);
            }
            catch
            {

            }
        }
        private void SendReadStart()
        {
            try
            {
                CommonLog.DebugLogWrite(this, "SendReadStart()");
                ReadStart(this);
            }
            catch
            {

            }
        }
        private void SendReadEnd()
        {
            try
            {
                CommonLog.DebugLogWrite(this, "SendReadEnd()");
                ReadEnd(this);
            }
            catch
            {

            }
        } 
        #endregion

        private void ClearCardInfo()
        {
            try
            {
                m_sInPutType = "";      // 입력구분
                m_sInPutData = "";      // 입력데이터
                m_sInMaskData = "";     // 마스킹
                m_sInEncData = "";      // 카드데이터
                m_sServiceCode = "";    // 서비스코드
                m_sAppCardNo = "";      // 승인카드번호


                m_bSearchSuccess = false;
            }
            catch 
            {
            }
        }
        #endregion




    }
}