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;

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 삼성포인트 사용
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Win
{
    public partial class frmSamsungPoint : 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;
        private PosOLEDevice.DelegateIcReader delegateReader;                       // IC리더 콜백
        //#20170918 IC 콜백 함수 변경 start
        //포인트창에서 해피제휴 신용카드 리딩시 IC 우선 거래로 인해 '카드를 읽혀 주세요' 팝업 나오는 현상 수정.
        /*
        private PosOLEDevice.CallbackIc delegateReaderCardInfo;                     // IC리더 콜백(CardInfo)
        private bool m_bCardInPut;                                                  //카드 입력 중복 방지
        */
        //#20170918 IC 콜백 함수 변경 end
        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스

        private IDataProcessUs m_cDataService = null;
        private IPaymentUs m_cCreditCard = null;
        private IICReaderUs m_cDeviceICReader = null;

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

        private string m_sPosMenuKey;                                               // SPC 임직원 할인
        /// <summary>
        /// 할인 구분
        /// </summary>
        public string SetPosMenuKey { set { this.m_sPosMenuKey = value; } } 
        
        /// <summary>
        /// 입력구분
        /// </summary>
        private string m_InputType = "";    
        /// <summary>
        /// 입력데이터
        /// </summary>
        private string m_sIcChip = "";    
        /// <summary>
        /// 카드데이터
        /// </summary>
        private string m_sCardNo = "";
        /// <summary>
        /// FALLBACK 구분
        /// </summary>
        private string m_sFallDiv = "";
        /// <summary>
        /// 서비스구분
        /// </summary>
        private string m_sServiceCode = "";
        /// <summary>
        /// 서명 데이터
        /// </summary>
        private string m_sSign = "";

        #endregion 변수 선언

        #region 생성자 & 소멸자 & 폼초기화
        public frmSamsungPoint()
        {
            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_cDataService = (IDataProcessUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_SERVICE);            
            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);

            if (m_cDevStatus.ICReader.UseYn == true)     // 여신전문금융업법 적용여부 체크
                m_cCreditCard = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.CREDITCARD);
            else
                m_cCreditCard = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.MSRCARD);

            delegatePos = new PosOLEDevice.DelegateOlePos(OnDeviceEvent);
            delegateReader = new PosOLEDevice.DelegateIcReader(OnIcReaderCallBack);     // IC리더 콜백
            //#20170918 IC 콜백 함수 변경 start
            //포인트창에서 해피제휴 신용카드 리딩시 IC 우선 거래로 인해 '카드를 읽혀 주세요' 팝업 나오는 현상 수정.
            //delegateReaderCardInfo = new PosOLEDevice.CallbackIc(OnIcReaderCallBackCardInfo);     // IC리더 콜백(CardInfo)
            //#20170918 IC 콜백 함수 변경 end
        }

        private void frmSamsungPoint_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();

            tmrIcCard.Tag = "";
            tmrIcCard.Enabled = true;   // IC리더 콜백 설정
        }

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

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

        private void frmSamsungPoint_FormClosing(object sender, FormClosingEventArgs e)
        {
            tmrIcCard.Tag = "CLOSE";

            UnRegIcCallback();          // IC리더 콜백 해지
            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
            {
                // 이미지 로딩 처리
                //picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_S);
                //this.Size = new Size(788, 402);
                //this.Location = new Point(216, 173);
                //picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_S);
                this.Location = new Point(0, 50);
                this.Size = new Size(1024, 525);

                //this.BackColor = Color.FromArgb(114, 114, 114);

                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 = "";

                IDataCommonUs m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
                InitPayMainBack(m_cPosStatus, m_cDataCommon, m_sPosMenuKey, PosConst.MOT_MSG_TYPE.PAY_STEP_3, "");
                
                //테마색상 적용!
                btnPoint.BackColor = CmUtil.GetColorToString(m_cPosStatus.ScnMst.ThemeColor); 
                //btnEnter.BackColor = CmUtil.GetColorToString(m_cPosStatus.ScnMst.ThemeColor);                

                //#16745 신용카드 포인트 결제 시 해피포인트 취소되는 현상 확인요청 start, 20181115
                //신한포인트 사용시 포인트 버튼 눌러서 진행시 신용승인 되는 증상 수정
                //아래 소스 주석
                /*
                //*** MoonSeokWoo 2017.12.12
                if (m_sPosMenuKey == PosKey.MENU_KEY.SHINHANCARD_POINT)
                {
                    btnEnter.BackColor = CmUtil.GetColorToString(m_cPosStatus.ScnMst.ThemeColor);
                }
                //*** MoonSeokWoo 2017.12.12
                */
                //#16745 신용카드 포인트 결제 시 해피포인트 취소되는 현상 확인요청 end, 20181115

                // 포인트
                if (m_sPosMenuKey == PosKey.MENU_KEY.SAMSUNG_POINTS) lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0111);
                else if (m_sPosMenuKey == PosKey.MENU_KEY.WOORIMORE_POINTS) lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0905);
                else if (m_sPosMenuKey == PosKey.MENU_KEY.HYUNDAI_M_POINTS) lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0906);
                //*** MoonSeokWoo 2017.12.12 Add
                else if (m_sPosMenuKey == PosKey.MENU_KEY.SHINHANCARD_POINT) lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1081);
                //*** MoonSeokWoo 2017.12.12 Ed 
                
                lblCardNo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0051);
                lblPayAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0037);
                lblUsablePoint.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0070);
                lblValidDate.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0052);

                btnSearch.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0004);
                btnPoint.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0252);
                btnEnter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0253);
                btnMenu1.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0132);
                btnCatApp.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0854);

                //#16745 신용카드 포인트 결제 시 해피포인트 취소되는 현상 확인요청 start, 20181115
                //신한포인트 사용시 포인트 버튼 눌러서 진행시 신용승인 되는 증상 수정
                //아래 소스 주석
                /*
                //*** MoonSeokWoo 2017.12.12 Add
                if (m_sPosMenuKey == PosKey.MENU_KEY.SHINHANCARD_POINT)
                {
                    btnEnter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0252);
                }
                //*** MoonSeokWoo 2017.12.12 End
                */
                //#16745 신용카드 포인트 결제 시 해피포인트 취소되는 현상 확인요청 end, 20181115

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

                txtCardNo.Text = "";                
                txtUsablePoint.Text = "0";
                txtPayAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cTrnStatus.Sale.RemainPayAmt);             // 받을금액
                txtValidDate.Text = "";

                m_InputType = "";      // 입력구분
                m_sIcChip = "";      // 입력데이터
                m_sCardNo = "";       // 카드데이터
                m_sFallDiv = "";
                m_sServiceCode = "";
                m_sSign = "";

                btnPoint.Visible = false;

                bNotDoubleClik = false;

                txtCardNo.ReadOnly = false;
                btnCatApp.Visible = false;


                btnSearch.Visible = true;
                btnPoint.Visible = true;
                btnEnter.Visible = true;

                //*** MoonSeokWoo 2017.12.12 Add
                if (m_sPosMenuKey == PosKey.MENU_KEY.SHINHANCARD_POINT)
                {
                    btnSearch.Visible = false;

                    //#16745 신용카드 포인트 결제 시 해피포인트 취소되는 현상 확인요청 start, 20181115
                    //신한포인트 사용시 포인트 버튼 눌러서 진행시 신용승인 되는 증상 수정
                    //기존
                    //btnPoint.Visible = false;
                    //변경
                    btnEnter.Visible = false;
                    //#16745 신용카드 포인트 결제 시 해피포인트 취소되는 현상 확인요청 end, 20181115
                }
                //*** MoonSeokWoo 2017.12.12 End 


                if (m_cDevStatus.CatTerminal.UseYn == true)
                {
                    btnCatApp.Visible = true;

                    btnSearch.Visible = false;
                    btnPoint.Visible = false;
                    btnEnter.Visible = false;

                    if (m_cPosStatus.Base.OlePosCATModel == PosConst.CAT_MODEL_DIV._KOR_SPCN)
                    {
                        txtCardNo.ReadOnly = true;
                    }
                }
                
                // 무결성 실패후 진행시 오류 메시지 표시
                if (m_cDevStatus.ICReader.UseYn == true)     // 여신전문금융업법 적용여부 체크
                {
                    txtCardNo.MaxLength = 40;

                    if (m_cDevStatus.ICReader.Integrity_IC_Status != true && m_cDevStatus.ICReader.UseYn == true) WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0384);

                    lblUsablePoint.Location = new Point(238, 269);
                    txtUsablePoint.Location = new Point(376, 276);

                    lblValidDate.Visible = false;
                    txtValidDate.Visible = false;
                    lblBox4.Visible = false;

                    //*** MoonSeokWoo 2017.12.12 Add
                    if (m_sPosMenuKey == PosKey.MENU_KEY.SHINHANCARD_POINT)
                    {
                        lblUsablePoint.Visible = false;
                        txtUsablePoint.Visible = false;
                        lblBox3.Visible = false;
                    }
                    //*** MoonSeokWoo 2017.12.12 End
                }
                else
                {
                    txtCardNo.MaxLength = 40;

                    lblUsablePoint.Location = new Point(238, 308);
                    txtUsablePoint.Location = new Point(376, 315);

                    lblValidDate.Location = new Point(238, 269);
                    txtValidDate.Location = new Point(376, 276);

                    lblValidDate.Visible = true;
                    txtValidDate.Visible = true;
                    lblBox4.Visible = true;

                    //*** MoonSeokWoo 2017.12.12 Add
                    if (m_sPosMenuKey == PosKey.MENU_KEY.SHINHANCARD_POINT)
                    {
                        lblBox4.Visible = false;
                    }
                    //*** MoonSeokWoo 2017.12.12 End
                    
                    //*** MoonSeokWoo 2017.12.12 Add
                    if (m_sPosMenuKey == PosKey.MENU_KEY.SHINHANCARD_POINT)
                    {
                        lblUsablePoint.Visible = false;
                        txtUsablePoint.Visible = false;
                    }
                    //*** MoonSeokWoo 2017.12.12 End
                }

                txtCardNo.Select();
                txtCardNo.SelectText();
            }
            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) == btnMenu1)               // 카드 등록
                {
                    //*** MoonSeokWoo 2017.12.12 Edit

                    // grayber@20180102 우리모아포인트 추가 start - 버튼 입력에 따른 분기 추가 ( 신한카드 포인트와 동일하게 처리 )
                    if (m_sPosMenuKey == PosKey.MENU_KEY.SHINHANCARD_POINT
                        || m_sPosMenuKey == PosKey.MENU_KEY.WOORIMORE_POINTS
                        )
                    // grayber@20180102 우리모아포인트 추가 end
                    {
                        if (GetIcCardData(e != null ? true : false, CmUtil.IntParse(txtPayAmt.Text)) == true)
                        {
                            CompleteTxtInPut(1);       // 신한카드는 조회가 없음 바로 승인.
                        }
                    }
                    else
                    {
                        if (GetIcCardData(e != null ? true : false, 1) == true)
                        {
                            SearchTxtInPut();          // 카드정보 읽기 
                        }
                    }
                    //*** MoonSeokWoo 2017.12.12 End
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnPoint)         // 포인트
                {
                    //if (txtCardNo.Value.Length <= 0)
                    //{
                        if (GetIcCardData(true, CmUtil.IntParse(txtPayAmt.Text)) != true)
                        {
                            bNotDoubleClik = false;
                            return;
                        }
                    //}
                    CompleteTxtInPut(1); 
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnEnter)         // 신용
                {
                    //if (txtCardNo.Value.Length <= 0)
                    //{
                        if (GetIcCardData(true, CmUtil.IntParse(txtPayAmt.Text)) != true)
                        {
                            bNotDoubleClik = false;
                            return;
                        }
                    //}
                    CompleteTxtInPut(0); 
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnCatApp)         // Cat단말기 승인
                {
                    CatTerminalApproval();
                }
                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;
            }
            finally
            {
                if (txtCardNo.Value == "") tmrIcCard.Enabled = true;       // IC리더 콜백 설정
            }
            bNotDoubleClik = false;
        }

        /// <summary>
        /// 닫기
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            try
            {
                txtEditBox_EditBoxKeyDownEvent(null, PosKey.MENU_KEY.ESC_PREVIOUS);
            }
            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="sFuncValue"></param>
        private void txtEditBox_EditBoxKeyDownEvent(object sender, string sFuncValue)
        {
            try
            {
                if (sFuncValue == PosKey.MENU_KEY.ENTER)
                {
                    if (((Cosmos.UI.CsmPosEditBox)sender) == txtCardNo)
                    {
                        if ( txtCardNo.Text == "")
                        {
                            if ( GetIcCardData(true, 1) != true)    // 카드정보 읽기
                            //{
                            //    SearchTxtInPut();
                            //}
                            //return;
                            {
                                return;
                            }
                        }

                        if (CheckTxtInPut(sender, false) == false) return;
                        // grayber@20180102 우리모아포인트 추가 start - 텍스트박스 입력 이벤트 처리 추가 ( 신한카드 포인트와 동일하게 처리 )
                        if(m_sPosMenuKey == PosKey.MENU_KEY.SHINHANCARD_POINT
                            || m_sPosMenuKey == PosKey.MENU_KEY.WOORIMORE_POINTS
                            )
                        // grayber@20180102 우리모아포인트 추가 end
                        {
                            CompleteTxtInPut(1);

                        }
                        else
                        {
                            SearchTxtInPut();
                        }
                    }
                }
                else if (sFuncValue == PosKey.MENU_KEY.CLEAR)
                {
                    if (((Cosmos.UI.CsmPosEditBox)sender).ReadOnly == false) ((Cosmos.UI.CsmPosEditBox)sender).Text = "";
                    if (((Cosmos.UI.CsmPosEditBox)sender) == txtCardNo)
                    {
                        m_InputType = "";    
                        m_sIcChip = "";
                        m_sCardNo = "";
                        m_sFallDiv = "";
                        m_sServiceCode = "";
                        m_sSign = "";

                        txtCardNo.ReadOnly = false;
                        tmrIcCard.Enabled = true;
                    }
                }
                else if (sFuncValue == PosKey.MENU_KEY.ESC_PREVIOUS)
                {
                    this.DialogResult = DialogResult.Cancel;
                    this.Close();
                }
                else if (((Cosmos.UI.CsmPosEditBox)sender) == txtPayAmt)
                {
                    txtCardNo.Select();
                    txtCardNo.SelectText();
                }
            }
            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="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);
            }
        }

        /// <summary>
        /// 번호 변경시 기존 조회값 초기화
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtCardNo_EditBoxTextChangedEvnet(object sender, EventArgs e)
        {
            txtUsablePoint.Text = "0";
            btnPoint.Visible = false;

            m_InputType = "";                                                                                  // 입력구분
            m_sIcChip = "";                                                                                  // 입력데이터
            m_sCardNo = "";                                                                                  // 카드데이터
            m_sFallDiv = "";
            m_sServiceCode = "";
            m_sSign = "";
        }
        #endregion   

        #region 텍스트박스 입력 유효성 체크
        /// <summary>
        /// 텍스트박스 입력 유효성 체크
        /// </summary>
        /// <param name="sender"></param>
        /// <returns></returns>
        private bool CheckTxtInPut(object sender, bool bSearchMode)
        {
            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 { }

                // 카드번호 길이 체크
                if (sender == null || ((Cosmos.UI.CsmPosEditBox)sender) == txtCardNo)
                {
                    if (txtCardNo.Value.Length < 6)
                    {
                        if (m_cDevStatus.CatTerminal.UseYn == true && m_cPosStatus.Base.OlePosCATModel == PosConst.CAT_MODEL_DIV._KOR_SPCN)
                        {
                            WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0682);
                        }
                        else
                        {
                            WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0037);
                        }

                        txtCardNo.Select();
                        txtCardNo.SelectText();
                        return false;
                    }
                }

                if (m_cDataService.DoubleParse(txtPayAmt.Value) > m_cTrnStatus.Sale.RemainPayAmt)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0039);
                    txtPayAmt.Select();
                    txtPayAmt.SelectText();
                    return false;
                }

                if (txtPayAmt.Value.Length > 10 || m_cDataService.LongParse(txtPayAmt.Value) <= 0)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0036);
                    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_cDevStatus.ICReader.UseYn == false)     // 여신전문금융업법 적용여부 체크(2017.05.20)
                {
                    // 유효기간 입력 여부
                    if (txtCardNo.Value != "")
                    {
                        string sCardNo = m_cDataCommon.MSR_CardNoCheck(txtCardNo.Value, txtValidDate.Value, ref m_InputType);

                        int index = sCardNo.IndexOf("=");

                        if (index > 0 && sCardNo.Trim().Length >= index + 5)
                        {
                            txtValidDate.Value = CmUtil.MidH(sCardNo, index + 1, 4);
                        }
                    }
                }
                
            }
            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>
        /// <param name="nFlowMode"></param>
        /// <returns></returns>
        private bool CompleteTxtInPut(int iPointMode)
        {
            string sRet = UserCom.RST_ERR;
            string sCardNo = "";

            try
            {
                if (CheckTxtInPut(null, false) == false) return false;

                string m_sService = "";
                string sinSign = "";
                string m_sTax = "0";
                string m_sPassWord = "";
                string m_sCardKind = "";
                string m_sItemCode = "";
                double m_dCreditCardDcAtm = 0;
                string m_sCreditCardDcTy = "";
                string m_sMediaType = "";

                if (m_cDevStatus.ICReader.UseYn == true)     // 여신전문금융업법 적용여부 체크
                {
                    sCardNo = txtCardNo.Value;
                }
                else
                {
                    m_sCardNo = m_cDataCommon.MSR_CardNoCheck(txtCardNo.Value, txtValidDate.Value, ref m_InputType);
                    m_sIcChip = m_sCardNo;

                    if (txtValidDate.Value.Length != 4)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0581);
                        //SeokWoo Moon 2017.09.16
                        txtValidDate.Value = "";
                        txtCardNo.Value = "";
                        txtCardNo.Select();                        
                        //txtValidDate.Select();
                        return false;
                    }
                    else
                    {
                        txtValidDate.Value = txtValidDate.Value.ToString().PadLeft(4, '0');
                        txtValidDate.Update();
                    }
                }


                // 할부개월 
                //1.     우리 모아 포인트 60개월
                //2.     삼성 포인트 60개월
                //3.     MPOINT 80개월
                string sMonDiv = "00";

                if (iPointMode == 1)
                {
                    if (m_sPosMenuKey == PosKey.MENU_KEY.SAMSUNG_POINTS)
                    {
                        sMonDiv = "60";
                        m_sCreditCardDcTy = ItemConst.CREDITCARD_DC_TY.CREDIT_SPNT;
                    }
                    else if (m_sPosMenuKey == PosKey.MENU_KEY.WOORIMORE_POINTS)
                    {
                        sMonDiv = "60";
                        m_sCreditCardDcTy = ItemConst.CREDITCARD_DC_TY.WOORIMORE_POINTS;
                    }
                    else if (m_sPosMenuKey == PosKey.MENU_KEY.HYUNDAI_M_POINTS)
                    {
                        sMonDiv = "80";
                        m_sCreditCardDcTy = ItemConst.CREDITCARD_DC_TY.HYUNDAI_M_POINTS;
                    }
                    //*** MoonSeokWoo 2017.12.12 Add
                    else if (m_sPosMenuKey == PosKey.MENU_KEY.SHINHANCARD_POINT)
                    {
                        sMonDiv = "60";
                        m_sCreditCardDcTy = ItemConst.CREDITCARD_DC_TY.SHINHAN_CARD_POINT;
                    }
                    //*** MoonSeokWoo 2017.12.12 End

                    //#13207 PB 학익풍림_해피포인트+삼성 결합카드로 결제 시 해피포인트 적립 안되도록 수정 요청. start, phj
                    //if (int.Parse(sMonDiv) >= 60) m_sCreditCardDcTy = "";
                    //#13207 PB 학익풍림_해피포인트+삼성 결합카드로 결제 시 해피포인트 적립 안되도록 수정 요청. end, phj
                }

                // 서명
                LF_MakeSign();
                sinSign = m_sSign;

                //승인처리
                sRet = m_cCreditCard.SetPayment(new string[] { 
                        txtCardNo.Value, m_InputType, m_sCardNo, sMonDiv, m_cDataService.DoubleParse(txtPayAmt.Text).ToString(), m_sService, m_sTax, m_sPassWord, m_sCardKind, m_sIcChip
                      , m_sSign, m_sFallDiv, "0", "", "", m_sItemCode, "","",m_sCreditCardDcTy, m_dCreditCardDcAtm.ToString()
                      ,ItemConst.PAY_APP_DIV.NORMAL, m_sMediaType, m_sServiceCode });


                if (sRet != UserCom.RST_OK)
                {
                    InDataToZeroFill();

                    if (sRet != UserCom.RST_ERR)   //에러 코드만일때는 메세지 표기 안함!
                        WinManager.ErrorMessage(sRet);
                    txtCardNo.Focus();
                    padInPut.SetActiveFocus();
                    return false;
                }

                ////카드 호출
                //sRet = WinPay.ShowForm(new string[] { FormManager.FORM_PAY_CREDITCARD, PosKey.MENU_KEY.CREDIT_CARD, ItemConst.CREDITCARD_DC_TY.CREDIT_SPNT, iPointMode.ToString(), "" });
 
                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);
            }
            finally
            {
                //여전법 대응!
                //////////////////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref m_sCardNo);
                CmUtil.ZeroFillClear(ref m_sIcChip);
                //////////////////////////////////////////////////////////////////////////////////
            }
            return false;
        }


        /// <summary>
        /// cat단말기
        /// </summary>
        /// <returns></returns>
        private string CatTerminalApproval()
        {

            string sRet = UserCom.RST_ERR;
            try
            {

                if (CheckTxtInPut(txtPayAmt, false) == false) return sRet;

                //string sMsg = string.Format(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0594), m_cPosStatus.Global.NumericTOCurrency(m_dCreditCardDcAtm), m_cPosStatus.Global.NumericTOCurrency(m_nRemainPayAmt));

                //if (WinManager.QuestionMessage(sMsg) == true)
                //{
                    //InParam
                    // 0.전문구분,1.거래유형, 2.할부개월, 3.승인금액 , 4.봉사료, 5.세금, 6.원승인번호, 7.원거래일자, 8.포인트거래구분, 9.상품코드,
                    //10.전표인쇄여부, 11.추가항목, 12.제휴할인코드, 13.제휴할인금액, 14.예비1, 15.예비2

                    string sMonDiv = "00";
                    string m_sCreditCardDcTy = "";

                    if (m_sPosMenuKey == PosKey.MENU_KEY.SAMSUNG_POINTS)
                    {
                        sMonDiv = "60";
                        m_sCreditCardDcTy = ItemConst.CREDITCARD_DC_TY.CREDIT_SPNT;
                    }
                    else if (m_sPosMenuKey == PosKey.MENU_KEY.WOORIMORE_POINTS)
                    {
                        sMonDiv = "60";
                        m_sCreditCardDcTy = ItemConst.CREDITCARD_DC_TY.WOORIMORE_POINTS;
                    }
                    else if (m_sPosMenuKey == PosKey.MENU_KEY.HYUNDAI_M_POINTS)
                    {
                        sMonDiv = "80";
                        m_sCreditCardDcTy = ItemConst.CREDITCARD_DC_TY.HYUNDAI_M_POINTS;
                    }
                    //*** MoonSeokWoo 2017.12.12 Add
                    else if (m_sPosMenuKey == PosKey.MENU_KEY.SHINHANCARD_POINT)
                    {
                        sMonDiv = "60";
                        m_sCreditCardDcTy = ItemConst.CREDITCARD_DC_TY.SHINHAN_CARD_POINT;
                    }
                    //*** MoonSeokWoo 2017.12.12 End

                    //#13207 PB 학익풍림_해피포인트+삼성 결합카드로 결제 시 해피포인트 적립 안되도록 수정 요청. start, phj
                    //if (int.Parse(sMonDiv) >= 60) m_sCreditCardDcTy = "";
                    //#13207 PB 학익풍림_해피포인트+삼성 결합카드로 결제 시 해피포인트 적립 안되도록 수정 요청. end, phj

                    //승인처리                                                   0,                                           1,                          2,            3,       4,  5,  6,  7,  8,  9, 10, 11,         12,         13,  14, 15 
                    sRet = m_cCreditCard.SetPayment(new string[] { PosConst.POS_CAT_MASTER.TRAN_TYPE, PosConst.POS_CAT_MASTER.TRADE_ID.CAT_CARD_AGREE, sMonDiv, txtPayAmt.Value, "", "", "", "", "", "", "", "", m_sCreditCardDcTy, "0", "", "","","" });

                    if (sRet == UserCom.RST_OK)
                    {
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        if (sRet != UserCom.RST_ERR)   //에러 코드만일때는 메세지 표기 안함!
                            WinManager.ErrorMessage(sRet);

                        sRet = UserCom.RST_ERR;
                    }
                //}
            }
            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 sRet;
        }


        /// <summary>
        /// 조회 처리
        /// </summary>
        /// <returns></returns>
        private bool SearchTxtInPut()
        {
            string sRet = UserCom.RST_ERR;
            string sCardNo = "";

            //string sInPutType = "";
            //string sInPutData = "";
            //string sInEncData = "";
            //string sInFallback = "";
            //string sinServiceCode = "";
            //string sinSign = "";

            try
            {
                if (CheckTxtInPut(null, true) == false) return false;

                //sInPutType = m_InputType;
                //sInPutData = m_sIcChip;
                //sInEncData = m_sCardNo;
                //sInFallback = m_sFallDiv;
                //sinServiceCode = m_sServiceCode;

                if (m_cDevStatus.ICReader.UseYn != true)     // 여신전문금융업법 적용여부 체크
                {
                    if (txtValidDate.Value.Length != 4)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0581);
                        //SeokWoo Moon 2017.09.14
                        txtValidDate.Value = "";
                        txtCardNo.Value = "";
                        txtCardNo.Select();
                        //txtValidDate.Select();
                        return false;
                    }
                    else
                    {
                        txtValidDate.Value = txtValidDate.Value.ToString().PadLeft(4, '0');
                        txtValidDate.Update();
                    }
                }

                if (m_cDevStatus.ICReader.UseYn == true)     // 여신전문금융업법 적용여부 체크
                {
                    sCardNo = txtCardNo.Value;
                }
                else
                {
                    m_sCardNo = m_cDataCommon.MSR_CardNoCheck(txtCardNo.Value, txtValidDate.Value, ref m_InputType);
                    m_sIcChip = "";
                }

                if (m_cDevStatus.ICReader.UseYn == true)     // 여신전문금융업법 적용여부 체크
                {
                    if (m_sCardNo == "")
                    {
                        if (m_sIcChip == "")
                        {
                            m_InputType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_KEYIN;
                            m_sCardNo = sCardNo;
                            m_sIcChip = sCardNo;
                            m_sFallDiv = "0";
                        }
                        EncryptedCardNo(m_sCardNo, ref m_sIcChip, ref m_sCardNo);
                    }
                }
                string[] aRet = new string[1];
                
                // 할부개월 
                //1.     우리 모아 포인트 60개월
                //2.     삼성 포인트 60개월
                //3.     MPOINT 80개월
                string sMonDiv = "00";
                string m_sCreditCardDcTy = "";
                string sPayAmt = "0";
                m_sSign = "";

                //if (m_sPosMenuKey == PosKey.MENU_KEY.SAMSUNG_POINTS) sMonDiv = "60";
                //else if (m_sPosMenuKey == PosKey.MENU_KEY.WOORIMORE_POINTS) sMonDiv = "60";
                //else if (m_sPosMenuKey == PosKey.MENU_KEY.HYUNDAI_M_POINTS) sMonDiv = "80";

                if (m_sPosMenuKey == PosKey.MENU_KEY.SAMSUNG_POINTS)
                {
                    sMonDiv = "60";
                    m_sCreditCardDcTy = ItemConst.CREDITCARD_DC_TY.CREDIT_SPNT;
                    sPayAmt = "1";
                }
                else if (m_sPosMenuKey == PosKey.MENU_KEY.WOORIMORE_POINTS)
                {
                    sMonDiv = "60";
                    m_sCreditCardDcTy = ItemConst.CREDITCARD_DC_TY.WOORIMORE_POINTS;
                    sPayAmt = "1";
                }
                else if (m_sPosMenuKey == PosKey.MENU_KEY.HYUNDAI_M_POINTS)
                {
                    sMonDiv = "80";
                    m_sCreditCardDcTy = ItemConst.CREDITCARD_DC_TY.HYUNDAI_M_POINTS;
                    sPayAmt = "1";
                }

                //0:마스킹 카드번호 1:입력구분 2:카드번호 3:할부개월 4:총금액 5:봉사료
                //6:세금 7:비밀번호 8:신용카드종류 9:칩데이터 10:사인
                //11:Fallback구분 12:제휴할인금액 13:원승인번호 14:원승인일자 15:아이템코드
                //16:매입사코드 17:매입사명

                // 조회요청                                                          0            1          2        3        4    5    6  7   8           9  10          11  12   13  14  15  16  17  18  19  20  21                
                //string[] aParam = new string[] { PosConst.CREDITCARD_SEARCH_TYPE.POINT, m_InputType, m_sCardNo, sMonDiv, sPayAmt, "0", "0", "", "", m_sIcChip, "", m_sFallDiv, "0", "", "", "", "", "", "", "", "", "" };
                string[] aParam = new string[] { PosConst.CREDITCARD_SEARCH_TYPE.POINT, m_InputType, m_sCardNo, sMonDiv, sPayAmt, "0", "0", "", "", m_sIcChip, "", m_sFallDiv, "0", "", "", "", "", "", m_sCreditCardDcTy, "", "", "" };

                txtUsablePoint.Text = "0";
                btnPoint.Visible = false;

                // 조회처리
                sRet = m_cCreditCard.SearchPayment(aParam, ref aRet);
                if (sRet != UserCom.RST_OK)
                {
                    WinManager.ErrorMessage(sRet);
                    padInPut.SetActiveFocus();

                    txtCardNo.Value = "";
                    txtValidDate.Value = "";
                    txtCardNo.Select();
                    return false;
                }
                else
                {
                    txtUsablePoint.Text = m_cPosStatus.Global.NumericTOCurrency(m_cDataService.DoubleParse(aRet[0].Trim()));     // 가용포인트

                    if (m_cDataService.DoubleParse(txtUsablePoint.Text.Trim()) > 0)  
                        btnPoint.Visible = 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;
        }
        #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
            {
                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);
            }
        }

        /// <summary>
        /// MSR Event
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnMSREvent(object source, EventArgs e)
        {

            string sMsrData = "";

            try
            {                
                sMsrData = m_cDevStatus.Msr.Track2Data;
                if (sMsrData.Length > 0 && m_sIcChip == "")
                {
                    m_InputType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_SWIP;
                    if (m_cDevStatus.ICReader.UseYn == true)     // 여신전문금융업법 적용여부 체크
                        m_sIcChip = sMsrData;

                    txtCardNo.Text = sMsrData;
                    //txtCardNo.ReadOnly = true;

                    if (m_cTrnStatus.Head.TradeDiv == ItemConst.TRAN_DIV.NORMAL) SearchTxtInPut();
                }
            }
            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
            {
                //여전법 대응!
                //////////////////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref sMsrData);
                //////////////////////////////////////////////////////////////////////////////////
            }
        }
        /// <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_sIcChip == "")
                {
                    m_InputType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_KEYIN;
                    if (m_cDevStatus.ICReader.UseYn == true)     // 여신전문금융업법 적용여부 체크
                        m_sIcChip = sScanData;

                    txtCardNo.Text = sScanData;
                    //txtCardNo.ReadOnly = true;

                    if (m_cTrnStatus.Head.TradeDiv == ItemConst.TRAN_DIV.NORMAL) SearchTxtInPut();
                }
            }
            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="sCardData"></param>
        /// <param name="sCardNo"></param>
        /// <returns></returns>
        private string EncryptedCardNo(string sInData, ref string sCardData, ref string sCardNo)
        {
            string sEncData = sInData;

            try
            {
                if (m_cDevStatus.ICReader.UseYn == true)     // 여신전문금융업법 적용여부 체크
                {
                    UnRegIcCallback();              // IC리더 콜백 해지
                }

                sEncData = m_cDeviceICReader.GetEncryptedCardNo(sInData).Trim();

                if (CmUtil.MidH(sEncData, 0, 2) == "00")
                {
                    sCardData = CmUtil.MidH(sEncData, 2, 512).Trim();
                    sCardNo = CmUtil.MidH(sEncData, 514, sEncData.Length - 514).Trim();
                }
                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);
                    sEncData = "";
                }

                if (m_cDevStatus.ICReader.UseYn == true)     // 여신전문금융업법 적용여부 체크
                {

                    //tmrIcCard.Enabled = true;    // IC리더 콜백 설정
                }
            }
            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 sEncData;
        }

        /// <summary>
        /// IC 카드 정보 입력 처리
        /// </summary>
        /// <returns></returns>
        private bool GetIcCardData(bool bCancelCallBack, int nSaleAmt)
        {
            string sRsvStr = "";
            try
            {
                m_sCardNo = "";
                m_sIcChip = "";
                m_InputType = "";
                m_sFallDiv = "";
                m_sServiceCode = "";
                m_sSign = "";

                if (m_cDevStatus.ICReader.UseYn == true)     // 여신전문금융업법 적용여부 체크
                {
                    if (bCancelCallBack == true) UnRegIcCallback(); // IC리더 콜백 해지
                    txtCardNo.Value = "";
                    txtCardNo.ReadOnly = false;
                }
                else
                {
                    // MSR
                    return true;
                }

                if (m_cDeviceICReader.GetCardInfo_ICReader(PosConst.IC_READER_TRAN_TYPE.CREDIT, nSaleAmt, ref sRsvStr) == true)
                {
                    if (CmUtil.MidH(sRsvStr, 0, 2) == "00")
                    {
                        txtCardNo.Value = CmUtil.MidH(sRsvStr, 1030, 37).Trim();
                        m_sCardNo = CmUtil.MidH(sRsvStr, 6, 512).Trim();
                        m_sIcChip = CmUtil.MidH(sRsvStr, 518, 512).Trim();

                        if (CmUtil.MidH(sRsvStr, 4, 2).Trim() == "02")
                        {
                            m_InputType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_SWIP;
                        }
                        else
                        {
                            m_InputType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_IC;
                        }

                        m_sServiceCode = CmUtil.MidH(sRsvStr, 1067, 5).Trim();
                        m_sFallDiv = CmUtil.MidH(sRsvStr, 3, 1); // == "3" ? "0" : "1";

                        //tmrIcCard.Enabled = true;       // IC리더 콜백 설정
                        return true;
                    }
                }

                if (m_cDevStatus.ICReader.UseYn == true)     // 여신전문금융업법 적용여부 체크
                {
                    //tmrIcCard.Enabled = true;       // IC리더 콜백 설정
                }
            }
            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 여전법 대응
        /// <summary>
        /// ZeroFill 초기화
        /// </summary>
        private void InDataToZeroFill()
        {
            try
            {

                //여전법 대응!
                //////////////////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref m_sIcChip);
                CmUtil.ZeroFillClear(ref m_sCardNo);
                //////////////////////////////////////////////////////////////////////////////////

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

        }
        #endregion 여전법 대응

        #region IC리더 콜백 관련
        /// <summary>
        /// IC리더 콜백 설정
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tmrIcCard_Tick(object sender, EventArgs e)
        {
            try
            {
                if (m_cDevStatus.ICReader.UseYn != true)             // 여전법 인증여부(0:MSR, 1:IC)
                {
                    tmrIcCard.Enabled = false;
                    return;
                }

                if (tmrIcCard.Tag == null || tmrIcCard.Tag.ToString() == "")
                {
                    // IC리더 콜백 설정
                    if (bNotDoubleClik) return;

                    tmrIcCard.Enabled = false;

                    //#20170918 IC 콜백 함수 변경 start
                    //포인트창에서 해피제휴 신용카드 리딩시 IC 우선 거래로 인해 '카드를 읽혀 주세요' 팝업 나오는 현상 수정.
                    //기존
                    m_cDeviceICReader.RegIcCallback(delegateReader);
                    //변경
                    //string sApprID = PosMstManager.GetMstVan(ItemConst.TR_ITEM_ID.CREDITCARD_ITEM, ItemConst.TR_ITEM_ID.CREDITCARD.CREDIT_CARD, PosMst.MST_VAN.DATA.APPR_ID);
                    //m_cDeviceICReader.RegIcCallbackCardInfo(sApprID, m_cDataService.IntParse(txtPayAmt.Value), delegateReaderCardInfo);
                    //#20170918 IC 콜백 함수 변경 end
                }
                else if (tmrIcCard.Tag.ToString() == "MSR")
                {
                    // MSR 카드 읽기
                    tmrIcCard.Enabled = false;
                    tmrIcCard.Tag = "";
                    tmrIcCard.Interval = 500;

                    SearchTxtInPut();          // 카드정보 읽기

                    tmrIcCard.Enabled = true;
                }
                else if (tmrIcCard.Tag.ToString() == "IC")
                {
                    // IC리더 카드 읽기
                    tmrIcCard.Enabled = false;
                    tmrIcCard.Tag = "";
                    tmrIcCard.Interval = 500;

                    bNotDoubleClik = false;
                    btnProc_Click(btnMenu1, null);
                }
                else
                    tmrIcCard.Enabled = 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);
            }
        }

        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
            {
                if (txtCardNo.InvokeRequired)
                {
                    DelegateIcReaderCallBack d = new DelegateIcReaderCallBack(OnIcReaderCallBack);
                    this.Invoke(d, new object[] { num, str });
                }
                else
                {
                    if (bNotDoubleClik) return;
                    bNotDoubleClik = true;

                    if (num == 1)
                    {
                        // IC 카드
                        tmrIcCard.Tag = "IC";
                        tmrIcCard.Interval = 100;
                    }
                    else
                    {
                        // MSR 카드
                        if (str.ToString().StartsWith("EN") == true)
                        {
                            txtCardNo.Value = CmUtil.MidH(str.ToString(), 512, 40).Trim();
                            m_InputType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_SWIP;
                            m_sCardNo = CmUtil.MidH(str.ToString(), 0, 512).Trim();
                            m_sServiceCode = CmUtil.MidH(str.ToString(), 552, 5).Trim();
                            m_sFallDiv = "0";

                            tmrIcCard.Tag = "MSR";
                            tmrIcCard.Interval = 100;
                        }
                        else
                        {
                            tmrIcCard.Interval = 500;
                        }
                    }
                    tmrIcCard.Enabled = true;

                    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>
        /// IC리더 콜백 해지
        /// </summary>
        private void UnRegIcCallback()
        {
            try
            {
                if (m_cDevStatus.ICReader.UseYn == true)     // 여신전문금융업법 적용여부 체크
                {
                    tmrIcCard.Enabled = false;

                    //#20170918 IC 콜백 함수 변경 start
                    //포인트창에서 해피제휴 신용카드 리딩시 IC 우선 거래로 인해 '카드를 읽혀 주세요' 팝업 나오는 현상 수정.
                    //기존
                    m_cDeviceICReader.UnRegIcCallback();
                    //변경
                    //m_cDeviceICReader.UnRegIcCallbackCardInfo();
                    //#20170918 IC 콜백 함수 변경 end
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        //#20170918 IC 콜백 함수 변경 start
        //포인트창에서 해피제휴 신용카드 리딩시 IC 우선 거래로 인해 '카드를 읽혀 주세요' 팝업 나오는 현상 수정.
        /*
        delegate void DelegateWriteLog(int returnValue, StringBuilder returnData);
        /// <summary>
        /// IC리더 콜백 함수(CardInfo)
        /// </summary>
        /// <param name="returnValue"></param>
        /// <param name="returnData"></param>
        public void OnIcReaderCallBackCardInfo(int returnValue, StringBuilder returnData)
        {
            if (txtCardNo.InvokeRequired)
            {
                DelegateWriteLog d = new DelegateWriteLog(OnIcReaderCallBackCardInfo);
                this.Invoke(d, new object[] { returnValue, returnData });
            }
            else
            {
                if (m_bCardInPut) return;
                m_bCardInPut = true;

                if (returnValue > 0)
                {
                    string sRsvStr = returnData.ToString();
                    if (CmUtil.MidH(sRsvStr, 0, 2) == "00")
                    {
                        m_sCardNo = CmUtil.MidH(sRsvStr, 6, 512).Trim();
                        txtCardNo.Value = CmUtil.MidH(sRsvStr, 1030, 37).Trim();
                        m_sIcChip = CmUtil.MidH(sRsvStr, 518, 512).Trim();
                        if (CmUtil.MidH(sRsvStr, 4, 2).Trim() == "02")
                        {
                            m_InputType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_SWIP;
                        }
                        else
                        {
                            m_InputType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_IC;
                        }
                        m_sServiceCode = CmUtil.MidH(sRsvStr, 1067, 5).Trim();
                        m_sFallDiv = CmUtil.MidH(sRsvStr, 3, 1); // == "3" ? "0" : "1";

                        // IC 카드(CardInfo)
                        tmrIcCard.Tag = "ICREADER";
                        tmrIcCard.Interval = 100;
                        tmrIcCard.Enabled = true;

                        m_bCardInPut = false;
                    }
                }
            }

        }
        */
        //#20170918 IC 콜백 함수 변경 end

        #endregion

        #region 서명
        /// <summary>
        /// 사인 데이터 받기
        /// </summary>
        /// <returns></returns>
        private string LF_MakeSign()
        {

            string sRet = UserCom.RST_OK;

            try
            {
                m_sSign = "";

                //싸인 받기
                if (m_cTrnStatus.Sale.RemainPayAmt > m_cDataService.DoubleParse(CmUtil.IsNull(PosMstManager.GetPosOption(POS_OPTION.OPT007), "50000")))
                {
                    //전자 서명 사용 유무!
                    if (m_cDevStatus.SignPad.UseYn == true)
                    {
                        string sPath = BaseCom.NxDataPath + "SIGN\\";

                        CmUtil.CreateDirectory(sPath);

                        ISignPadUs m_cSignPad = (ISignPadUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_SIGNPAD);
                        if (m_cSignPad.GetSign_SignPadEx(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0557), string.Format(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0583)
                            , m_cPosStatus.Global.NumericTOCurrency(m_cTrnStatus.Sale.RemainPayAmt)), "", "", sPath, "SIGN.BMP", ref m_sSign) == false)
                        {
                            if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0550) == false)
                            {
                                return UserCom.RST_ERR;
                            }

                            m_sSign = "";
                        }
                    }
                    else
                    {
                        UserLog.WriteLogFile(UserCom.LOG_DEBUG,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     "Not Use SingPad Skip!");
                    }

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

        }
        #endregion

        private void txtPayAmt_EditBoxTextChangedEvnet(object sender, EventArgs e)
        {
            txtCardNo.Text = "";
        }


    }
}
