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.Data;

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 해피 기프트 사용
// 작  성  자 :  
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Win
{
    public partial class frmHappyGiftUse : 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;                                                  //카드 입력 중복 방지
        private string m_sIcChip;                                                   //IC CHIP DATA(EMV)
        private string m_InputType = ""; //PosConst.POS_VAN_MASTER.VAN_KEYIN;       //입력구분
        private string m_sCardNo;                                                   //입력 카드 번호
        private string m_sFallDiv;                                                  //FallBack구분
        private string m_sServiceCode;                                              //서비스코드
        */
        //#20170918 IC 콜백 함수 변경 end

        private IDataProcessUs m_cDataService = null;
        private IPaymentUs m_cHappyGift = null;
        private IICReaderUs m_cDeviceICReader = null;
        private ISalePluItemUs m_cPluService = null;                                // 판매 등록 관리

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

        private IDataCommonUs m_cDataCommon = null;

        private string mPay_DC_Type = "";                                           // 결제 그룹 코드
        private string mPay_DC_CD = "";                                             // 결제 상세 코드

        private string m_sPosMenuKey;                                               // 입력값 할인
        /// <summary>
        /// 구분
        /// </summary>
        public string SetPosMenuKey { set { this.m_sPosMenuKey = value; } }

        /// <summary>
        /// 입력구분
        /// </summary>
        private string m_sInPutType = "";
        /// <summary>
        /// 입력데이터
        /// </summary>
        private string m_sInPutData = "";
        /// <summary>
        /// 카드데이터
        /// </summary>
        private string m_sInEncData = "";

        private string m_sMsrCard;                                               // 입력값 할인
        /// <summary>
        /// 구분
        /// </summary>
        public string SetMsrCard { set { this.m_sMsrCard = value; } }


        //#20180612 신용카드, 해피기프트(신) 화면에서 해피기프트(구) 카드번호 리딩되도록 수정 start
       
        /// <summary>
        /// 암호화카드번호
        /// </summary>
        private string m_sEncData;
        public string SetEncData { set { this.m_sEncData = value; } }

        /// <summary>
        /// 입력타입
        /// </summary>
        private string m_sNumInputType;
        public string SetInputType { set { this.m_sNumInputType = value; } }
        
        //#20180612 신용카드, 해피기프트(신) 화면에서 해피기프트(구) 카드번호 리딩되도록 수정 end

        public struct ITEM_PLU_CHECK
        {
            public string iTemCD;
            public double T_Qty;            // 구매해야될 건수
            public double S_Qty;            // 구매한 건수 
        }

        #endregion 변수 선언

        #region 생성자 & 소멸자 & 폼초기화
        public frmHappyGiftUse()
        {
            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_cPluService = (ISalePluItemUs)sManager.InitServiceInstance(ServiceLists.BSV_SALE.DLL, ServiceLists.BSV_SALE.SALE_PLU_ITEM);
            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
            m_cHappyGift = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.HAPPYGIFTUSE);

            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 frmhHappyGiftUse_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 frmhHappyGiftUse_Activated(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(delegatePos);
        }

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

        private void frmhHappyGiftUse_FormClosing(object sender, FormClosingEventArgs e)
        {
            tmrIcCard.Tag = "CLOSE";
            UnRegIcCallback();          // IC리더 콜백 해지
            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, "");

                //테마색상 적용!
                btnEnter.BackColor = CmUtil.GetColorToString(m_cPosStatus.ScnMst.ThemeColor);

                // 해피 기프트
                if (m_sPosMenuKey == PosKey.MENU_KEY.HAPPY_GIFTCARD) lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0351);

                lblPayAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0037);
                lblCardNo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0051);
                lblBeforeBalanceAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0352);
                lblSaleAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0049);
                lblAfterBalanceAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0353);

                btnMenu1.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0132);
                //btnRfCard.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0580);
                btnSearch.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0004);
                btnEnter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0057);

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

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

                m_sInPutType = "";                                              // 입력구분
                m_sInPutData = "";                                              // 입력데이터
                m_sInEncData = "";                                              // 카드데이터



                bNotDoubleClik = false;

                mPay_DC_Type = ItemConst.TR_ITEM_ID.PPCARD_ITEM;                // 결제 그룹 코드
                mPay_DC_CD = ItemConst.TR_ITEM_ID.PPCARD.HP_GIFT;               // 결제 상세 코드
                 
                txtCardNo.Value = m_sMsrCard; 
                txtCardNo.Select();

                //#20180612 신용카드, 해피기프트(신) 화면에서 해피기프트(구) 카드번호 리딩되도록 수정 start
                
                if (txtCardNo.Value != "")
                {
                    if (m_sMsrCard.IndexOf("*") > 0)
                    {
                        m_sInPutData = m_sMsrCard;
                        m_sInPutType = m_sNumInputType; 
                        m_sInEncData = m_sEncData;
                    }
                    else
                    {
                        m_sInPutData = m_sMsrCard;
                        m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_KEYIN;
                        m_sInEncData = "";
                    }

                    SearchTxtInPut();
                }
                m_sMsrCard = "";
                m_sEncData = "";
                m_sNumInputType = "";
                
                //#20180612 신용카드, 해피기프트(신) 화면에서 해피기프트(구) 카드번호 리딩되도록 수정 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);
            }
        }
        #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)               // 카드 등록
                {
                    if (GetIcCardData(e != null ? true : false) == true)
                        SearchTxtInPut();          // 카드정보 읽기
                }
                if (((Cosmos.UI.CsmButton)sender) == btnSearch)             // 조회
                {
                    if (txtCardNo.Value.Length <= 0)
                    {
                        if (GetIcCardData(true) != true)
                        {
                            bNotDoubleClik = false;
                            return;
                        }

                    }
                    SearchTxtInPut();
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnEnter)         // 승인
                {
                    if (txtCardNo.Value.Length <= 0)
                    {
                        if (GetIcCardData(true) != true)
                        {
                            bNotDoubleClik = false;
                            return;
                        }

                    }
                    CompleteTxtInPut();
                }
                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;
        }

        /// <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.Value.Trim() == "")               // 카드 등록
                        {
                            if (GetIcCardData(true) == true) SearchTxtInPut();          // 카드정보 읽기
                        }
                        SearchTxtInPut();

                    }
                    else if (((Cosmos.UI.CsmPosEditBox)sender) == txtSaleAmt)
                    {
                        if (txtCardNo.Value.Trim() == "")               // 카드 등록
                        {
                            if (GetIcCardData(true) == true) SearchTxtInPut();          // 카드정보 읽기
                        }

                        if (m_cTrnStatus.Head.TradeDiv == ItemConst.TRAN_DIV.NORMAL)
                        {
                            CompleteTxtInPut();             // 할인 승인 처리
                        }
                    }
                }
                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)
                    {
                        txtCardNo.Value = "";
                        tmrIcCard.Enabled = true;

                        //#20180612 신용카드, 해피기프트(신) 화면에서 해피기프트(구) 카드번호 리딩되도록 수정 start
                        Clear();
                        //#20180612 신용카드, 해피기프트(신) 화면에서 해피기프트(구) 카드번호 리딩되도록 수정 end
                    }
                }
                else if (sFuncValue == PosKey.MENU_KEY.ESC_PREVIOUS)
                {
                    this.DialogResult = DialogResult.Cancel;
                    this.Close();
                }
            }
            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)
        {
            txtBeforeBalanceAmt.Text = "0";
            txtSaleAmt.Value = "0";
            txtAfterBalanceAmt.Text = "0";

            m_sInPutType = "";                                                                                  // 입력구분
            m_sInPutData = "";                                                                                  // 입력데이터
            m_sInEncData = "";                                                                                  // 카드데이터
        }
        #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)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0037);
                        txtCardNo.Focus();
                        return false;
                    }
                }

                if (bSearchMode == false)
                {
                    if (txtBeforeBalanceAmt.Text.Trim() == "")
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0043);
                        txtCardNo.Focus();
                        return false;
                    }

                    if (txtSaleAmt.Value.Length > 10 || m_cDataService.LongParse(txtSaleAmt.Value) <= 0)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0036);
                        txtSaleAmt.Focus();
                        return false;
                    }

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

                    if (m_cDataService.DoubleParse(txtSaleAmt.Value.ToString()) > m_cDataService.DoubleParse(txtPayAmt.Text.ToString()))
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0039);
                        txtSaleAmt.Focus();
                        return false;
                    }

                    if (m_cDataService.DoubleParse(txtSaleAmt.Value.ToString()) > m_cDataService.DoubleParse(txtBeforeBalanceAmt.Text.ToString()))
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0246);
                        txtSaleAmt.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>
        /// <param name="nFlowMode"></param>
        /// <returns></returns>
        private bool CompleteTxtInPut()
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                if (CheckTxtInPut(null, false) == false) return false;

                string sInPutType = m_sInPutType;
                string sInPutData = m_sInPutData;
                string sInEncData = m_sInEncData;
                if (m_sInEncData == "")
                {
                    if (m_sInPutData == "")
                    {
                        sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_KEYIN;
                        sInPutData = txtCardNo.Value;
                    }
                    EncryptedCardNo(sInPutData, ref sInEncData, ref sInPutData);
                }

                Column.TR_PAYMENT.DATA m_cPayItem = (Column.TR_PAYMENT.DATA)m_cHappyGift.GetPayment(new string[] { });

                // 승인 처리
                sRet = m_cHappyGift.SetPayment(new string[] { m_sPosMenuKey, sInPutType, sInPutData, sInEncData, m_cDataService.DoubleParse(txtSaleAmt.Value).ToString(), m_cPayItem.OCCUR_ENTRY_02, m_cPayItem.OCCUR_ENTRY_03, m_cPayItem.OCCUR_ENTRY_04, mPay_DC_Type, mPay_DC_CD });
                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;
        }

        /// <summary>
        /// 조회 처리
        /// </summary>
        /// <returns></returns>
        private bool SearchTxtInPut()
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                if (CheckTxtInPut(null, true) == false) return false;

                string sInPutType = m_sInPutType;
                string sInPutData = m_sInPutData;
                string sInEncData = m_sInEncData;
                if (m_sInEncData == "")
                {
                    if (m_sInPutData == "")
                    {
                        sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_KEYIN;
                        sInPutData = txtCardNo.Value;
                    }
                    EncryptedCardNo(sInPutData, ref sInEncData, ref sInPutData);
                }

                // 조회
                string[] saRecvdData = null;

                txtSaleAmt.Value = "0";
                txtAfterBalanceAmt.Text = "0";
                txtBeforeBalanceAmt.Text = "0";

                //                sRet = m_cHappyGift.SearchPayment(new string[] { m_sPosMenuKey, sInPutType, sInPutData, sInEncData, m_cDataService.DoubleParse(txtPayAmt.Text).ToString(), "", "", "", mPay_DC_Type, mPay_DC_CD }, ref saRecvdData);
                sRet = m_cHappyGift.SearchPayment(new string[] { m_sPosMenuKey, sInPutType, sInPutData, sInEncData, CmUtil.IntParse(txtSaleAmt.Value).ToString(), "", "", "", mPay_DC_Type, mPay_DC_CD }, ref saRecvdData);
                if (sRet != UserCom.RST_OK) return false;

                Column.TR_PAYMENT.DATA m_cPayItem = (Column.TR_PAYMENT.DATA)m_cHappyGift.GetPayment(new string[] { });

                txtBeforeBalanceAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cPayItem.AMT_ENTRY_04);          // 거래전 잔액
                txtAfterBalanceAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cPayItem.AMT_ENTRY_04);           // 거래후 잔액

                if (m_cDataService.DoubleParse(txtPayAmt.Text) <= m_cDataService.DoubleParse(txtBeforeBalanceAmt.Text))
                {
                    // 잔액이 받을금액보다 큰 경우
                    txtSaleAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cDataService.DoubleParse(txtPayAmt.Text));
                    txtAfterBalanceAmt.Text = m_cPosStatus.Global.NumericTOCurrency(CmUtil.DoubleSubtraction(m_cDataService.DoubleParse(txtBeforeBalanceAmt.Text), m_cDataService.DoubleParse(txtPayAmt.Text)));
                }
                else if (m_cDataService.DoubleParse(txtPayAmt.Text) > m_cDataService.DoubleParse(txtBeforeBalanceAmt.Text))
                {
                    // 잔액이 받을금액보다 작은 경우
                    txtSaleAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cDataService.DoubleParse(txtBeforeBalanceAmt.Text));
                    txtAfterBalanceAmt.Text = "0";
                }

                txtSaleAmt.Select();
                txtSaleAmt.SelectText();

                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


        /// <summary>
        /// ZeroFill 초기화
        /// </summary>
        private void InDataToZeroFill()
        {
            try
            {
                //여전법 대응!
                //////////////////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref m_sInPutData);    //
                CmUtil.ZeroFillClear(ref m_sInEncData);    //
                //////////////////////////////////////////////////////////////////////////////////


                //#20180612 신용카드, 해피기프트(신) 화면에서 해피기프트(구) 카드번호 리딩되도록 수정 start
               
                CmUtil.ZeroFillClear(ref m_sEncData); 
                CmUtil.ZeroFillClear(ref m_sMsrCard);
                CmUtil.ZeroFillClear(ref m_sNumInputType); 
                
                //#20180612 신용카드, 해피기프트(신) 화면에서 해피기프트(구) 카드번호 리딩되도록 수정 end


                CmsEditBoxZeroFillClear(txtCardNo);
            }
            catch (Exception) { }

        }


        /// <summary>
        /// 컨트롤 ZeroFill 초기화
        /// </summary>
        /// <param name="txtbox"></param>
        private void CmsEditBoxZeroFillClear(Cosmos.UI.CsmPosEditBox txtbox)
        {
            try
            {
                if (string.IsNullOrEmpty(txtbox.Value)) return;
                int nLen = txtbox.Value.Length;

                string sFill = "";
                sFill = new string('A', nLen); txtbox.Value = sFill;
                sFill = new string('0', nLen); txtbox.Value = sFill;
                sFill = new string('X', nLen); txtbox.Value = sFill;
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            finally
            {
                txtbox.Value = string.Empty;
            }
        }


        #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)
        {
            try
            {
                string sMsrData = m_cDevStatus.Msr.Track2Data;
                if (sMsrData.Length > 0 && m_sInPutData == "")
                {
                    m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_SWIP;
                    m_sInPutData = sMsrData;

                    txtCardNo.Text = m_sInPutData;
                    //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="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_sInPutData == "")
                {
                    m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_BARCODE;
                    m_sInPutData = sScanData;

                    txtCardNo.Text = m_sInPutData;
                    //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
            {
                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);
                }

                if (txtCardNo.Value == "") 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)
        {
            try
            {
                if (bCancelCallBack == true) UnRegIcCallback(); // IC리더 콜백 해지

                m_sInPutType = "";
                m_sInPutData = "";
                m_sInEncData = "";
                txtCardNo.Value = "";
                txtCardNo.ReadOnly = false;

                string sRsvStr = "";
                if (m_cDeviceICReader.GetCardInfo_ICReader(PosConst.IC_READER_TRAN_TYPE.POINT, CmUtil.IntParse(txtSaleAmt.Value), ref sRsvStr, true) == true)
                {
                    if (CmUtil.MidH(sRsvStr, 0, 2) == "00")
                    {
                        txtCardNo.Value = CmUtil.MidH(sRsvStr, 1030, 37).Trim();

                        m_sInEncData = CmUtil.MidH(sRsvStr, 6, 512).Trim();
                        m_sInPutData = CmUtil.MidH(sRsvStr, 1030, 37).Trim();

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

                        //tmrIcCard.Enabled = true;       // IC리더 콜백 설정
                        return true;
                    }
                }
                if (txtCardNo.Value == "") 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 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(txtSaleAmt.Value), delegateReaderCardInfo);
                    //#20170918 IC 콜백 함수 변경 end
                }
                else if (tmrIcCard.Tag.ToString() == "MSR")
                {
                    // MSR 카드 읽기
                    tmrIcCard.Enabled = false;
                    tmrIcCard.Tag = "";
                    tmrIcCard.Interval = 500;

                    bNotDoubleClik = false;
                    txtEditBox_EditBoxKeyDownEvent(txtCardNo, PosKey.MENU_KEY.ENTER);

                    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)
                        {
                            m_sInPutType = "";                                              // 입력구분
                            m_sInPutData = "";                                              // 입력데이터
                            m_sInEncData = "";                                              // 카드데이터

                            txtCardNo.Value = CmUtil.MidH(str.ToString(), 512, 40).Trim();

                            m_sInEncData = CmUtil.MidH(str.ToString(), 0, 512).Trim();
                            m_sInPutData = CmUtil.MidH(str.ToString(), 512, 40).Trim();
                            m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_SWIP;

                            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
        //#20180612 신용카드, 해피기프트(신) 화면에서 해피기프트(구) 카드번호 리딩되도록 수정 start
        private void Clear()
        {
            m_sInPutType = "";
            m_sInPutData = "";
            m_sInEncData = "";
            m_sMsrCard = "";
            m_sEncData = "";
            m_sNumInputType = "";            
        }
        //#20180612 신용카드, 해피기프트(신) 화면에서 해피기프트(구) 카드번호 리딩되도록 수정 end
    }
}
