using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Collections;

using Cosmos.Win;
using Cosmos.BaseFrame;
using Cosmos.UserFrame;
using Cosmos.ServiceProvider;
using Cosmos.Common;
using Cosmos.CommonManager;
using System.Diagnostics;

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 선불카드 사용 - 중국
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Win
{
    public partial class frmPrepaidCard_China : frm_PayMainBack
    {

        #region 변수 선언

        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        private PosStatus m_cPosStatus = new PosStatus();                           // 기본정보 참조
        private TranStatus m_cTrnStatus = new TranStatus();                         // 거래정보 참조        
        private DeviceStatus m_cDevStatus = new DeviceStatus();                     // 디바이스 관리
        private PosOLEDevice.DelegateOlePos delegatePos;
        
        //#Rhee, 20180206 카드번호 수동입력 방지 기능 추가 Start
        private Stopwatch sStopwatch = new Stopwatch();                             // 스톱워치
        //#Rhee, 20180206 카드번호 수동입력 방지 기능 추가 End

        private IICReaderUs m_cDeviceICReader = null;
        private ISignPadUs m_cDeviceSignPad = null;
        private IDataProcessUs m_cDataService = null;                               // 거래데이터 합계금액 계산 및 관리
        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스
        private IPaymentUs m_cPrepaidcard_China = null;
        private ICampaignUs m_cCampaingMain = null;                                 // 캠페인 관리

        private bool bNotDoubleClik = false;                                        // 더블 클릭 방지용

        private string m_sPosMenuKey;
        /// <summary>
        /// 포인트 사용(해피포인트)
        /// </summary>
        public string SetPosMenuKey { set { this.m_sPosMenuKey = value; } }

        private string m_sHappyPointSave;
        /// <summary>
        /// 해피포인트 카드등록 구분(0:카드등록, 1:적립등록)
        /// </summary>
        public string SetHappyPointSave { set { this.m_sHappyPointSave = value; } }

        /// <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 bool m_bPassWord = false;
        /// <summary>
        /// 결제포인트 금액
        /// </summary>
        private double m_nUsePoint;
        /// <summary>
        /// 받을금액
        /// </summary>
        private double m_nRemainPayAmt;
        /// <summary>
        /// 조회 성공 여부
        /// </summary>
        private bool m_bSearchSuccess = false;

        //#Rhee, 20180206 카드번호 수동입력 방지 기능 추가 Start
        /// <summary>
        /// 입력 시작 시간
        /// </summary>
        private long m_lInPutStartTime = 0;

        /// <summary>
        /// 입력 종료 시간
        /// </summary>
        private long m_lInPutStopTime = 0;

        /// <summary>
        /// 입력 시간 체크
        /// </summary>
        private bool m_bChkTime = false;
        //#Rhee, 20180206 카드번호 수동입력 방지 기능 추가 End

        #endregion 변수 선언

        #region 생성자 & 소멸자 & 폼초기화
        public frmPrepaidCard_China()
        {
            InitializeComponent();

            base.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw, true);
            //this.UpdateStyles();

            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_cDeviceSignPad = (ISignPadUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_SIGNPAD);
            m_cDataService = (IDataProcessUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_SERVICE);
            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
            m_cPrepaidcard_China = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.PREPAIDCARD_CHINA);
            m_cCampaingMain = (ICampaignUs)sManager.InitServiceInstance(ServiceLists.ASV_CAMPAIGN.DLL, ServiceLists.ASV_CAMPAIGN.CAMPAIGN_MAIN);

            delegatePos = new PosOLEDevice.DelegateOlePos(OnDeviceEvent);
        }

        private void frmPrepaidCard_China_Load(object sender, EventArgs e)
        {
            UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "");

            InitControl();
        }

        private void frmPrepaidCard_China_Activated(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(delegatePos);
        }

        private void frmPrepaidCard_China_Deactivate(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(null);
        }

        private void frmPrepaidCard_China_FormClosing(object sender, FormClosingEventArgs e)
        {
            InDataToZeroFill();
            UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", lblTitle.Text);
        }

        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            try
            {
                this.Location = new Point(0, 50);
                this.Size = new Size(1024, 525);

                // 이미지 로딩 처리
                //picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_S);
                //picBack.Location = new Point(216, 123);
                FormManager.SetFormAllControlFont(this, m_cPosStatus.Base.FONT);
                FormManager.SetTextBoxGlobalInfo(this, m_cPosStatus.Global.m_stCultureMaster.nGroupingDigits, m_cPosStatus.Global.m_stCultureMaster.strGroupingSymbol
                    , m_cPosStatus.Global.m_stCultureMaster.nDecimalDigits, m_cPosStatus.Global.m_stCultureMaster.strDecimalSymbol);

                btnExit.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BTN_CLOSE);
                if (btnExit.Image != null) btnExit.Text = "";

                btnEnter.BackColor = CmUtil.GetColorToString(m_cPosStatus.ScnMst.ThemeColor);

                if (m_sPosMenuKey == PosKey.MENU_KEY.PREPAID_CARDS_HPJOY) lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0818); 

                //lblRemainAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0037);
                lblCardNo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0051);
                lblBalanceAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0307);
                lblPayAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0308);

                btnSearch.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0004);
                btnEnter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0057); 

                m_nRemainPayAmt = m_cTrnStatus.Sale.RemainPayAmt;
                 
                InitPayMainBack(m_cPosStatus, m_cDataCommon, m_sPosMenuKey, PosConst.MOT_MSG_TYPE.PAY_STEP_3, "");

                // 기능 버튼 설정 체크
                FormManager.SetbtnMenu(txtCardNo, m_cDevStatus.ICReader.UseYn, btnMenu1, btnMenu2, btnMenu3, btnMenu4);

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

                txtCardNo.Value = m_sInMaskData;
                txtCardNo.ReadOnly = false;

                if (m_sInPutData != "")
                {
                    if (SearchTxtInPut() == true)
                    {
                        if (m_bPassWord == true)
                        {
                            //txtPassword.Select();
                        }
                        else
                        {
                            txtPayAmt.Select();
                        }
                    }
                    else
                    {
                        txtCardNo.Select();
                    }
                }
                else
                {
                    txtCardNo.Select();
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        /// <summary>
        /// 카드 입력 정보 클리어
        /// </summary>
        private void ClearCardInfo()
        {
            try
            {
                m_sInPutType = "";      // 입력구분
                m_sInPutData = "";      // 입력데이터
                m_sInMaskData = "";     // 마스킹
                m_sInEncData = "";      // 카드데이터
                
                m_nUsePoint = 0;        // 결제포인트
                m_bSearchSuccess = false;

                txtBalanceAmt.Text = "";
                txtPayAmt.Text = ""; 
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion

        #region 버튼 입력 처리
        /// <summary>
        /// 버튼 입력 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnProc_Click(object sender, EventArgs e)
        {
            try
            {
                if (bNotDoubleClik) return;
                bNotDoubleClik = true;
                 
                if (((Cosmos.UI.CsmButton)sender) == btnSearch)        // 조회
                {
                    SearchTxtInPut();
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnEnter)         // 승인
                {
                    CompleteTxtInPut();
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnExit)
                { 
                    bNotDoubleClik = false;

                    this.DialogResult = DialogResult.Cancel;
                    this.Close();
                    return;
                }
                //padInPut.SetActiveFocus();
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
                bNotDoubleClik = false;
            }
            bNotDoubleClik = false;
        }
        #endregion

        #region 텍스트박스 키 입력 이벤트 처리
        //#Rhee, 20180206 카드번호 수동입력 방지 기능 추가 Start
        /// <summary>
        /// 텍스트박스 키 입력 이벤트 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtEditBox_EditBoxTextChangedEvnet(object sender, System.EventArgs e)
        {            
            if (txtCardNo.Value.Length == 1)
            {
                sStopwatch.Start();
                m_lInPutStartTime = sStopwatch.ElapsedMilliseconds/100;                
            }
            else if (txtCardNo.Value.Length == 16 && !m_bChkTime)
            {
                m_lInPutStopTime = sStopwatch.ElapsedMilliseconds/100;
                sStopwatch.Stop();

                if ((m_lInPutStopTime - m_lInPutStartTime) <= 10 )          // 카드번호 16글자 입력시간 1초이내 여부 체크
                {
                    m_bChkTime = true;                    
                }
                else
                {
                    txtCardNo.Value = "";
                    m_bChkTime = false;  
                }                
            }
            else if(txtCardNo.Value.Length == 0)
            {
                sStopwatch.Reset();
                m_lInPutStartTime = 0;
                m_lInPutStopTime = 0;
                m_bChkTime = false;
            }
        }
        //#Rhee, 20180206 카드번호 수동입력 방지 기능 추가 End

        /// <summary>
        /// 텍스트박스 키 입력 이벤트 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="sFuncValue"></param>
        private void txtEditBox_EditBoxKeyDownEvent(object sender, string sFuncValue)
        {
            try
            {
                if (bNotDoubleClik) return;
                bNotDoubleClik = true;

                try
                {
                    if (sFuncValue == PosKey.MENU_KEY.ENTER)
                    {
                        if (((Cosmos.UI.CsmPosEditBox)sender) == txtCardNo)
                        {
                            //if (txtCardNo.Text == "")
                            //{
                            //    if (GetIcCardData() == false) return;      // 카드정보 읽기
                            //}

                            if (CheckTxtInPut(sender) == false) return;
                            if (SearchTxtInPut() == false) return;         // 조회
                        }

                        if (((Cosmos.UI.CsmPosEditBox)sender) == txtPayAmt)
                        {
                            if (CheckTxtInPut(sender) == false) return;
                                                        
                            CompleteTxtInPut();         // 승인 처리
                        }
                    }
                    else if (sFuncValue == PosKey.MENU_KEY.CLEAR)
                    {
                        if (((Cosmos.UI.CsmPosEditBox)sender) == txtCardNo) ClearCardInfo();        // 카드 입력 정보 클리어

                        if (((Cosmos.UI.CsmPosEditBox)sender).ReadOnly == false) ((Cosmos.UI.CsmPosEditBox)sender).Text = "";
                    }
                }
                catch (Exception ex)
                {
                    WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
                }
                finally
                {
                    bNotDoubleClik = false;
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            bNotDoubleClik = false;
        }               

        /// <summary>
        /// 텍스트박스 활성화 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtEditBox_EnterEvent(object sender, EventArgs e)
        {
            try
            {
                padInPut.SetActiveControl = (Control)sender;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion

        #region 텍스트박스 입력 유효성 체크
        /// <summary>
        /// 텍스트박스 입력 유효성 체크
        /// </summary>
        /// <param name="sender"></param>
        /// <returns></returns>
        private bool CheckTxtInPut(object sender)
        {
            try
            {
                // 특정 문자값 제거
                try
                {
                    if (m_cDevStatus.Msr.STX != "" && txtCardNo.Value.StartsWith(m_cDevStatus.Msr.STX)) txtCardNo.Value = txtCardNo.Value.Substring(1);

                    int iLastEtx = txtCardNo.Value.LastIndexOf(m_cDevStatus.Msr.ETX);
                    if (m_cDevStatus.Msr.ETX != "" && iLastEtx > 0) txtCardNo.Value = CmUtil.MidH(txtCardNo.Value, 0, iLastEtx);
                }
                catch { }

                // 카드번호 길이 체크
                txtCardNo.Value = txtCardNo.Value.Replace(";", "");
                txtCardNo.Value = txtCardNo.Value.Replace("?", "");
                
                if (sender == null || ((Cosmos.UI.CsmPosEditBox)sender) == txtCardNo)
                {
                    if (txtCardNo.Value.Length < 10)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0037);
                        txtCardNo.Focus();
                        return false;
                    } 

                    if (m_sInEncData == "")
                    {
                        if (m_sInPutData == "")
                        {
                            m_sInPutData = txtCardNo.Value;
                            if (m_sInPutData.IndexOf("=") > 0 )
                            {
                                m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_SWIP;
                            }
                            else
                            {
                                m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_KEYIN;
                            }
                        }
                        if (EncryptedCardNo(m_sInPutData, ref m_sInMaskData, ref m_sInEncData) == false) return false;
                    }
                } 

                // 결제포인트 체크
                if (sender == null || ((Cosmos.UI.CsmPosEditBox)sender) == txtPayAmt)
                {
                    //#Rhee,20171017 선불카드 잔액 1위엔 이하 결제 가능 하게 수정 start
                    // 기존
                    //if (m_cDataService.LongParse(txtBalanceAmt.Text) == 0)
                    // 변경
                    if (m_cDataService.DoubleParse(txtBalanceAmt.Text) == 0)
                    //#Rhee,20171017 선불카드 잔액 1위엔 이하 결제 가능 하게 수정 end
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0043);
                        txtCardNo.Focus();
                        return false;
                    }

                    //#Rhee,20171010 선불카드 1위엔 이하 결제 가능 하게 수정 start
                    // 기존
                    // if (txtPayAmt.Value.Length > 10 || m_cDataService.LongParse(txtPayAmt.Value) <= 0
                    // 변경
                    if (txtPayAmt.Value.Length > 10 || m_cDataService.DoubleParse(txtPayAmt.Value) <= 0)
                    //#Rhee,20171010 선불카드 1위엔 이하 결제 가능 하게 수정 end
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0597);
                        txtPayAmt.Focus();
                        return false;
                    }

                    //if (CmUtil.AmountCut(m_cDataService.DoubleParse(txtPayAmt.Value), CmUtil.IntParse(m_cPosStatus.Mst.PayRudDwLoc)) != m_cDataService.DoubleParse(txtPayAmt.Value))
                    //{
                    //    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0036);
                    //    txtPayAmt.Focus();
                    //    return false;
                    //}

                    if (m_cDataService.DoubleParse(txtBalanceAmt.Text) < m_cDataService.DoubleParse(txtPayAmt.Text))
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0246);
                        txtPayAmt.Focus();
                        return false;
                    }
                    if (m_cDataService.DoubleParse(txtPayAmt.Text) > m_cTrnStatus.Sale.RemainPayAmt)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0039);
                        txtPayAmt.Focus();
                        return false;
                    }
                    if (CmUtil.AmountCut(m_cDataService.DoubleParse(txtPayAmt.Value), CmUtil.IntParse(m_cPosStatus.Mst.PayRudDwLoc)) != m_cDataService.DoubleParse(txtPayAmt.Value))
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0036);    // 입력한 금액은 입력 불가 단위 입니다.
                        txtPayAmt.Focus();
                        return false;
                    }
                     
                }
            }
            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;
            }
            return true;
        }
        #endregion

        #region 입력 완료 처리
        /// <summary>
        /// 포인트 조회 처리
        /// </summary>
        /// <returns></returns>
        private bool SearchTxtInPut()
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                if (CheckTxtInPut(txtCardNo) == false) return false;

                m_nUsePoint = 0;        // 결제포인트

                txtBalanceAmt.Text = "";
                txtPayAmt.Text = ""; 
                m_bSearchSuccess = false;

                // 조회
                string[] saRecvdData = null;
                sRet = m_cPrepaidcard_China.SearchPayment(new string[] { m_sPosMenuKey, m_sInPutType, m_sInPutData, "0" }, ref saRecvdData);
                if (sRet != UserCom.RST_OK) return false;

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

                // 가용포인트
                txtBalanceAmt.Text = m_cPosStatus.Global.NumericTOCurrency(cPayItem.AMT_ENTRY_04);          
                // 결제포인트
                txtPayAmt.Value = (m_nRemainPayAmt > cPayItem.AMT_ENTRY_04) ? cPayItem.AMT_ENTRY_04.ToString() : m_nRemainPayAmt.ToString();

                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="nFlowMode"></param>
        /// <returns></returns>
        private bool CompleteTxtInPut()
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                if (CheckTxtInPut(null) == false) return false;

                if (m_bSearchSuccess == false)
                {
                    // 조회
                    if (SearchTxtInPut() == false) return false;
                }

                // 포인트 사용 승인 처리 => 포인트 소숫점 처리(2017.06.26)
                sRet = m_cPrepaidcard_China.SetPayment(new string[] { m_sPosMenuKey, m_sInPutType, m_sInPutData, txtPayAmt.Value});
                //sRet = m_cPrepaidcard_China.SetPayment(new string[] { m_sPosMenuKey, m_sInPutType, m_sInPutData, m_cDataService.DoubleParse(txtPayAmt.Value).ToString() });
                if (sRet != UserCom.RST_OK) return false;

                this.DialogResult = DialogResult.OK;
                this.Close();

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

        #region DeviceEvent 관련
        /// <summary>
        /// DeviceEvent 관련
        /// </summary>
        /// <param name="sDevice"></param>
        /// <param name="sData1"></param>
        /// <param name="sData2"></param>
        /// <param name="sData3"></param>
        public void OnDeviceEvent(string sDevice, string sData1, string sData2, string sData3)
        {
            try
            {
                if (bNotDoubleClik) return;
                bNotDoubleClik = true;

                switch (sDevice)
                {
                    case PosConst.OPOS_DEVICE.MSR:
                        this.Invoke(new EventHandler(OnMSREvent));
                        break;
                    case PosConst.OPOS_DEVICE.SCANNER:
                        this.Invoke(new EventHandler(OnScannerEvent));
                        break;
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
                bNotDoubleClik = false;
            }
            bNotDoubleClik = false;
        }

        /// <summary>
        /// MSR Event
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnMSREvent(object source, EventArgs e)
        {
            try
            {
                string sMsrData = m_cDevStatus.Msr.Track2Data;
                if (sMsrData.Length > 0)
                {
                    m_sInEncData = "";
                    m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_SWIP;
                    m_sInPutData = sMsrData;

                    txtCardNo.Value = m_sInPutData.Length > 16 ? m_sInPutData.Substring(0, 16) : m_sInPutData;

                    txtEditBox_EditBoxKeyDownEvent(txtCardNo, PosKey.MENU_KEY.ENTER);
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        /// <summary>
        /// 스캐너 이벤트 처리
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnScannerEvent(object source, EventArgs e)
        {
            try
            {
                string sScanData = m_cDevStatus.Scanner.DataLabel;
                if (sScanData.Length > 0)
                {
                    m_sInEncData = "";
                    m_sInPutData = sScanData;
                    if (m_sInPutData.Length > 16 && CmUtil.IsNumber(m_sInPutData.Substring(16, 1)) == false)
                    {
                        m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_MOBILE_SWIP;
                        txtCardNo.Value = m_sInPutData.Substring(0, 16);
                    }
                    else
                    {
                        m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_KEYIN;
                        txtCardNo.Value = m_sInPutData;
                    }

                    txtEditBox_EditBoxKeyDownEvent(txtCardNo, PosKey.MENU_KEY.ENTER);
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                   System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

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

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

                    return true;
                //}
                //else
                //{
                //    //암호화 처리 실패!
                //    UserLog.WriteLogFile(UserCom.LOG_ERROR, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                //        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "Fail =>" + sInData);
                //    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0280);
                //}
            }
            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>
        /// IC 카드 정보 입력 처리
        /// </summary>
        /// <returns></returns>
        private bool GetIcCardData()
        {
            try
            {
                txtCardNo.Value = "";
                ClearCardInfo();        // 카드 입력 정보 클리어

                string sRsvStr = "";
                if (m_cDeviceICReader.GetCardInfo_ICReader(PosConst.IC_READER_TRAN_TYPE.POINT, CmUtil.IntParse(txtPayAmt.Value), 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_sInPutData = m_sInMaskData;
                        m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_SWIP;

                        txtCardNo.Value = m_sInPutData.Length > 16 ? m_sInPutData.Substring(0, 16) : m_sInPutData;
                        return true;
                    }
                }
                // WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0321);
            }
            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>
        /// RF 카드 정보 입력 처리
        /// </summary>
        /// <returns></returns>
        private bool GetRfCardData()
        {
            try
            {
                txtCardNo.Value = "";
                ClearCardInfo();        // 카드 입력 정보 클리어

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

                m_sInEncData = CmUtil.MidH(sRsvStr, 2, 512).Trim();
                m_sInMaskData = CmUtil.MidH(sRsvStr, 514, 40).Trim();
                
                m_sInPutData = m_sInMaskData;
                m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_RF;

                txtCardNo.Value = m_sInPutData.Length > 16 ? m_sInPutData.Substring(0, 16) : m_sInPutData;
                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>
        /// <returns></returns>
        private bool GetPinPadData()
        {
            try
            {
                //txtPassword.Text = "";
                
                string sPassWord = "";
                if (m_cDeviceSignPad.GetMsg_SignPad(false, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0013), ref sPassWord, 4) == true)
                {
                    //txtPassword.Text = sPassWord;

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

        private void lblCardNo_MouseDown(object sender, MouseEventArgs e)
        {
            //if (e.Button == System.Windows.Forms.MouseButtons.Right)
            //{
            //    m_cDevStatus.Scanner.DataLabel = "8231124183433925%";
            //    OnScannerEvent(null, null);
            //}
        }      

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

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

                txtCardNo.Value = string.Empty;
            }
            catch (Exception) { }

        }
        #endregion 여전법 대응

    }
}
