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;

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : SPC 임직원 할인
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Win
{
    public partial class frmSPCEmployeeDC : 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 IDataProcessUs m_cDataService = null;
        private IPaymentUs m_cSPCEmployeeDC = null;
        private IICReaderUs m_cDeviceICReader = null;
        private ISalePluItemUs m_cPluService = 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_sInPutType = "";    
        /// <summary>
        /// 입력데이터
        /// </summary>
        private string m_sInPutData = "";    
        /// <summary>
        /// 카드데이터
        /// </summary>
        private string m_sInEncData = "";

        #endregion 변수 선언

        #region 생성자 & 소멸자 & 폼초기화
        public frmSPCEmployeeDC()
        {
            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_cSPCEmployeeDC = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.SPCEMPLOYEEDC);

            delegatePos = new PosOLEDevice.DelegateOlePos(OnDeviceEvent);
        }

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

            //#15169 임직원 해피App 바코드리딩 시 자동할인적용 개선요청 start
            #region 임직원 할인 선리딩 처리
            if (m_cPosStatus.Sale.strHappyPointCardNo != "" &&
                m_cPosStatus.Sale.strEmpInfo == "3A")
            {
                //==============================================================
                // 오버로딩된 임직원 할인 이벤트 함수 호출
                //--------------------------------------------------------------
                // - 파라미터 : sender, 임직원 할인 카드번호, 승인까지 실행할지 여부
                //==============================================================
                #region 오버로딩된 임직원 할인 승인 함수 호출
                txtEditBox_EditBoxKeyDownEvent(null, m_cPosStatus.Sale.strHappyPointCardNo, btnSearch);    // 조회까지 수행 : 임직원할인은 정상 조회시 승인까지 진행됨
                #endregion
            }
            #endregion 임직원 할인 선리딩 처리
            //#15169 임직원 해피App 바코드리딩 시 자동할인적용 개선요청 end

        }

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

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

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

        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            try
            {
                // 이미지 로딩 처리
                //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 = "";

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

                // SPC 임직원 할인
                if (m_sPosMenuKey == PosKey.MENU_KEY.SPC_EMPLOYEE_DC) lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0158);
                else if (m_sPosMenuKey == PosKey.MENU_KEY.SPC_EMPLOYEE_DC_PAY) lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1008);
                
                lblCardNo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0051);
                lblPayAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0098);
                lblUsablePoint.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0070);

                btnSearch.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0004);
                btnEnter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0057);
                //btnCard.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0132);
                
                txtCardNo.Text = "";                
                txtPayAmt.Text = "";
                txtUsablePoint.Text = "0";

                // 결제인 경우 모바일쿠폰을 제외하고 결제후 불가 처리 
                ArrayList alPayItem = (ArrayList)StateObject.GetItemObject(Column.TR_PAYMENT.ITEM);
                foreach (Column.TR_PAYMENT.DATA cPayItem in alPayItem)
                {
                    if (cPayItem.CANCEL_DIV != PosConst.CANCEL_DIV.NORMAL) continue;

                    if (   (cPayItem.PAY_WAY_CD == ItemConst.TR_ITEM_ID.EMP_DC_ITEM && cPayItem.PAY_DTL_CD_01 == ItemConst.TR_ITEM_ID.EMP_DC.SPC)
                        || (cPayItem.PAY_WAY_CD == ItemConst.TR_ITEM_ID.EMP_DC_ITEM && cPayItem.PAY_DTL_CD_01 == ItemConst.TR_ITEM_ID.EMP_DC.SPC_PAY)
                      )
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0198);
                        this.DialogResult = DialogResult.Cancel;
                        this.Close();

                        return;
                    }

                    if (cPayItem.PAY_WAY_CD != ItemConst.TR_ITEM_ID.MOBILECON_ITEM)      // 통신사할인 모바일쿠폰과 중복 가능
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0392);
                        this.DialogResult = DialogResult.Cancel;
                        this.Close();

                        return;
                    }
                }

                txtSaleAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cTrnStatus.Sale.RemainPayAmt);             // 받을금액
                //txtPayAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cTrnStatus.Sale.RemainPayAmt);             // 대상금액
                //txtPayAmt.Text = m_cPosStatus.Global.NumericTOCurrency(GetDCTargetAmount());                        // 대상금액
                txtPayAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cDataService.GetPluTagetAmount(m_sPosMenuKey));      // 대상 금액

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

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

                bNotDoubleClik = false;

                // 무결성 실패후 진행시 오류 메시지 표시
                if (m_cDevStatus.ICReader.UseYn == true)     // 여신전문금융업법 적용여부 체크
                {
                    if (m_cDevStatus.ICReader.Integrity_IC_Status != true && m_cDevStatus.ICReader.UseYn == true) WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0384);
                }

                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_2, "");

                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)               // 카드 등록
                {
                    if (GetIcCardData() == true)
                    {
                        if (SearchTxtInPut() == true)
                        {
                            // 조회 정상후 바로 승인처리
                            bNotDoubleClik = false;
                            btnProc_Click(btnEnter, null);
                        }
                    }
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnSearch)        // 조회
                {
                    if (txtCardNo.Value.Length <= 0)
                    {
                        if (GetIcCardData() != true)
                        {
                            bNotDoubleClik = false;
                            return;
                        }
                    }

                    if (SearchTxtInPut() == true)
                    {
                        // 조회 정상후 바로 승인처리
                        bNotDoubleClik = false;
                        btnProc_Click(btnEnter, null);
                    }
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnEnter)         // 할인승인
                {
                    if (txtCardNo.Value.Length <= 0)
                    {
                        if (GetIcCardData() != 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 (SearchTxtInPut() == true)
                        {
                            // 조회 정상후 바로 승인처리
                            btnProc_Click(btnEnter, null);
                        }

                        //if (txtCardNo.Value.Length <= 0)
                        //{
                        //    if ( GetIcCardData() == true)    // 카드정보 읽기
                        //    {
                        //        SearchTxtInPut();
                        //    }
                        //    return;
                        //}
                        //if (CheckTxtInPut(sender, false) == false) return;

                        //if (m_cTrnStatus.Head.TradeDiv == ItemConst.TRAN_DIV.NORMAL)
                        //{
                        //    CompleteTxtInPut();             // 할인 승인 처리
                        //}
                    }

                    //if (CheckTxtInPut(sender, false) == false) return;
                    //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)
                    {
                        m_sInPutType = "";    
                        m_sInPutData = "";
                        m_sInEncData = "";    
                        txtCardNo.ReadOnly = false;
                    }
                }
                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)
        {
            txtUsablePoint.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.Select();
                        txtCardNo.SelectText();
                        return false;
                    }
                }

                if (bSearchMode != true)
                {
                    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;
                    }

                    //#20170808 임직원할인 조회 안하고 할인승인 할수 있도록 수정 start
                    //해당 조건 주석 처리.
                    /*
                    if (m_cDataService.DoubleParse(txtUsablePoint.Text) <= 0)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0272);
                        txtPayAmt.Select();
                        txtPayAmt.SelectText();
                        return false;
                    }
                    */
                    //#20170808 임직원할인 조회 안하고 할인승인 할수 있도록 수정 end

                    //if (m_cDataService.DoubleParse(txtPayAmt.Text) > m_cDataService.DoubleParse(txtSaleAmt.Text))
                    //{
                    //    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0039);
                    //    txtPayAmt.Select();
                    //    txtPayAmt.SelectText();
                    //    return false;
                    //}

                    //if (m_cDataService.DoubleParse(txtPayAmt.Text) > m_cDataService.DoubleParse(txtUsablePoint.Text))
                    //{
                    //    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0135);
                    //    txtPayAmt.Select();
                    //    txtPayAmt.SelectText();
                    //    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;

            string sInPutType = "";
            string sInPutData = "";
            string sInEncData = "";

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

                sInPutType = m_sInPutType;
                sInPutData = m_sInPutData;
                sInEncData = m_sInEncData;

                if (m_sInEncData == "")
                {
                    if (m_sInPutData == "")
                    {
                        //sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_MOBILE_SWIP;
                        sInPutData = txtCardNo.Value.Trim();
                        if (sInPutData.Contains("=") == true)
                        {
                            sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_SWIP;
                        }
                        else if (sInPutData.Length > 16 && CmUtil.IsNumber(sInPutData.Substring(16, 1)) == false)
                        {
                            if (CmUtil.CheckHappyMobileCard(sInPutData) == false)
                            {
                                WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0037);
                                txtCardNo.Focus();
                                txtCardNo.SelectText();
                                return false;
                            }
                            sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_MOBILE_SWIP;
                        }
                        else
                        {
                            sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_KEYIN;
                        }
                    }
                    EncryptedCardNo(sInPutData, ref sInEncData, ref sInPutData);
                }

                // SPC 임직원 할인 처리
                sRet = m_cSPCEmployeeDC.SetPayment(new string[] { m_sPosMenuKey, sInPutType, sInPutData, sInEncData, m_cDataService.DoubleParse(txtPayAmt.Value).ToString(), "", "", txtCardNo.Value.Trim() });
                if (sRet != UserCom.RST_OK) return false;

                // 해피포인트 적립카드 등록 처리(2017.04.13)
                SetHappyPointSave(sInPutType, sInPutData, sInEncData, txtCardNo.Value);

                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 sInPutData);
                CmUtil.ZeroFillClear(ref sInEncData);
                //////////////////////////////////////////////////////////////////////////////////
            }
            return false;
        }

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

            string sInPutType = "";
            string sInPutData = "";
            string sInEncData = "";

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

                sInPutType = m_sInPutType;
                sInPutData = m_sInPutData;
                sInEncData = m_sInEncData;

                if (m_sInEncData == "")
                {
                    if (m_sInPutData == "")
                    {
                        sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_MOBILE_SWIP;
                        sInPutData = txtCardNo.Value;
                    }
                    EncryptedCardNo(sInPutData, ref sInEncData, ref sInPutData);
                }
                // 조회
                string[] saRecvdData = null;
                sRet = m_cSPCEmployeeDC.SearchPayment(new string[] { m_sPosMenuKey, sInPutType, sInPutData, sInEncData, lblUsablePoint.Text }, ref saRecvdData);
                if (sRet != UserCom.RST_OK) return false;

                Column.TR_PAYMENT.DATA m_cPayItem = (Column.TR_PAYMENT.DATA)m_cSPCEmployeeDC.GetPayment(new string[] { });
                txtUsablePoint.Text = m_cPosStatus.Global.NumericTOCurrency(m_cPayItem.AMT_ENTRY_03);          // 가용포인트

                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;
            }
            finally
            {
                //여전법 대응!
                //////////////////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref sInPutData);
                CmUtil.ZeroFillClear(ref sInEncData);
                //////////////////////////////////////////////////////////////////////////////////
            }
        }
        #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_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);
            }
            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_sInPutData == "")
                {
                    m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_MOBILE_SWIP;
                    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
            {
                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);
                }
            }
            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()
        {
            try
            {
                //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(txtPayAmt.Text), ref sRsvStr) == 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();
                //        m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_MOBILE_SWIP;

                //        //txtCardNo.ReadOnly = true;
                //        return 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 여전법 대응
        /// <summary>
        /// ZeroFill 초기화
        /// </summary>
        private void InDataToZeroFill()
        {
            try
            {

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

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

        }
        #endregion 여전법 대응

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

        #region 할인 대상금액 조회
        private double GetDCTargetAmount()
        {
            double nDCAmount = 0;
            try
            {
                ArrayList alSaleItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);
                for (int i = 0; i < alSaleItem.Count; i++)
                {
                    Column.TR_PLU.DATA cPluItem = (Column.TR_PLU.DATA)alSaleItem[i];

                    if (cPluItem.CANCEL_DIV == PosConst.CANCEL_DIV.CANCEL || cPluItem.CANCEL_DIV_MAIN == PosConst.CANCEL_DIV.CANCEL) continue;    // 지정취소
                    if (cPluItem.DC_PRMT_YN != "0") continue;
                    if (cPluItem.EMP_DC_AMT > 0) continue;

                    nDCAmount = CmUtil.DoubleAdd(nDCAmount, cPluItem.BILL_AMT);
                }

                nDCAmount = CmUtil.DoubleSubtraction(nDCAmount, m_cTrnStatus.Sale.RecvedPayAmt);
            }
            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 nDCAmount;
        }
        #endregion

        /// <summary>
        /// 해피포인트 적립카드 등록(2017.04.13)
        /// </summary>
        /// <param name="sInPutType"></param>
        /// <param name="sInPutData"></param>
        /// <param name="sInEncData"></param>
        /// <param name="sInCardNo">실카드번호</param>
        private void SetHappyPointSave(string sInPutType, string sInPutData, string sInEncData, string sInCardNo)
        {
            try
            {
                // 해피포인트 카드만 자동등록 처리
                if (sInPutData.StartsWith(PosConst.HP_CARD_PRIFIX) == false) return;

                IDataCommonUs m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
                IPaymentExpUs m_cHappyPoint = (IPaymentExpUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.POINTHAPPYPOINT);

                // 결제할인 마스터의 결제할인 중복 가능 여부 체크
                if (m_cDataCommon.PayDcDuplicationCheck(ItemConst.TR_ITEM_ID.ETC_INFO_ITEM, ItemConst.TR_ITEM_ID.ETC_INFO.SAVEPOINT, false) == false) return;

                // 해피포인트 카드 기등록 여부 체크
                ArrayList alEtcItem = (ArrayList)StateObject.GetItemObject(Column.TR_ETC.ITEM);     // 기타 내역 받아 오기
                foreach (Column.TR_ETC.DATA cEtcItemHp in alEtcItem)
                {
                    if (cEtcItemHp.CANCEL_DIV == PosConst.CANCEL_DIV.CANCEL) continue;

                    // OKCASHBACK
                    if (cEtcItemHp.ETC_WAY_CD == ItemConst.TR_ITEM_ID.ETC_INFO_ITEM && cEtcItemHp.ETC_DTL_CD_01 == ItemConst.TR_ITEM_ID.ETC_INFO.OCB_SAVE) return;
                    // HP
                    if (cEtcItemHp.ETC_WAY_CD == ItemConst.TR_ITEM_ID.ETC_INFO_ITEM && cEtcItemHp.ETC_DTL_CD_01 == ItemConst.TR_ITEM_ID.ETC_INFO.SAVEPOINT) return;
                }

                if (sInCardNo.Contains("*") == true) sInCardNo = "";

                // 해피 포인트 적립카드 조회
                string[] saRecvdData = null;
                string sRet = m_cHappyPoint.SearchPayment(new string[] { sInPutType, sInPutData, sInEncData, "0", "", sInCardNo }, ref saRecvdData);
                if (sRet != UserCom.RST_OK) return;

                // 조회 데이터 획득
                Column.TR_ETC.DATA cEtcItem = (Column.TR_ETC.DATA)m_cHappyPoint.GetPayment(new string[] { });
                if (sInPutData.StartsWith(PosConst.HP_CARD_PRIFIX) == false && cEtcItem.HP_ADD_INFO_SCH.Trim() != "")     // 제휴카드 조회
                {
                    int nNowPos = 0;
                    string[] aIrtRsp = new string[Column.POINT_ADD_INFO_SEARCH.LEN.Length];
                    ItemColumn.ParseMessage(Column.POINT_ADD_INFO_SEARCH.LEN, Column.POINT_ADD_INFO_SEARCH.TYPE, Encoding.Default.GetBytes(cEtcItem.HP_ADD_INFO_SCH), ref nNowPos, ref aIrtRsp);

                    // 고객정보 중에서 첫번째 카드 선택
                    string sMemInfo = aIrtRsp[Column.POINT_ADD_INFO_SEARCH.SEQ.pointMEMINFO].Trim();
                    if (sMemInfo.Length >= 17 && CmUtil.LongParse(sMemInfo.Substring(0, 1)) > 0)
                    {
                        string sSchInPutData = sMemInfo.Substring(1, 16).Trim();        // 카드번호
                        string sSchInMaskData = "", sSchInEncData = "";
                        EncryptedCardNo(sSchInPutData, ref sSchInMaskData, ref sSchInEncData);
                        cEtcItem.CanFiller1 = sSchInEncData;
                        cEtcItem.OCCUR_ENTRY_14 = sSchInPutData;                        // 승인카드번호
                    }
                }

                if (cEtcItem.OCCUR_ENTRY_12 == "Y") m_cTrnStatus.Sale.HappyBuzzMemNo = sInPutData;
                cEtcItem.CanFiller3 = sInPutData;

                // 해피포인트 적립카드 아이템 등록 설정
                cEtcItem.SEQ = alEtcItem.Count + 1;
                alEtcItem.Add(cEtcItem);
            }
            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 sInPutData);
                CmUtil.ZeroFillClear(ref sInEncData);
                CmUtil.ZeroFillClear(ref sInCardNo);
                //////////////////////////////////////////////////////////////////////////////////
            }
        }

        //#15169 임직원 해피App 바코드리딩 시 자동할인적용 개선요청 start
        #region 임직원 할인 선리딩 처리를 위한 이벤트 오버로딩
        public void txtEditBox_EditBoxKeyDownEvent(object sender, string _strHappyPointCardNo, object _strDiv)
        {

            #region 구분(_strDiv) 값이 ''(공백)일 경우 카드 번호만 표시한다.
            if (_strDiv == null)
            {
                // 카드 번호 설정
                txtCardNo.Value = _strHappyPointCardNo;
                // 카드 번호 설정 후 clear
                //m_cPosStatus.Sale.strHappyPointCardNo = "";
                //m_cPosStatus.Sale.strEmpInfo = "";
            }
            #endregion

            #region 구분(_strDiv) 값이 '조회'일 경우 카드 번호 표시후 조회까지 처리한다.
            else if (((Cosmos.UI.CsmButton)_strDiv) == btnSearch)
            {
                // 카드 번호 설정 -----
                txtCardNo.Value = _strHappyPointCardNo;
                // 카드 번호 설정 후 clear
                //m_cPosStatus.Sale.strHappyPointCardNo = "";
                //m_cPosStatus.Sale.strEmpInfo = "";
                // 카드 조회 이벤트 호출 -----
                txtEditBox_EditBoxKeyDownEvent(txtCardNo, PosKey.MENU_KEY.ENTER);
            }
            #endregion

            #region 구분(_strDiv) 값이 '승인'일 경우 제휴할인 카드 번호 표시후 승인까지 처리한다.
            else if (((Cosmos.UI.CsmButton)_strDiv) == btnEnter)
            {
                // 카드 번호 설정
                txtCardNo.Value = _strHappyPointCardNo;
                // 카드 번호 설정 후 clear
                //m_cPosStatus.Sale.strHappyPointCardNo = "";
                //m_cPosStatus.Sale.strEmpInfo = "";
                // 카드 조회 이벤트 호출
                txtEditBox_EditBoxKeyDownEvent(txtCardNo, PosKey.MENU_KEY.ENTER);

                // 카드 승인 이벤트 호출
                btnProc_Click(btnEnter, null);
            }
            #endregion
        }

        #endregion 임직원 할인 선리딩 처리를 위한 이벤트 오버로딩
        //#15169 임직원 해피App 바코드리딩 시 자동할인적용 개선요청 end

    }
}
