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 frmTMoney : 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 ICampaignUs m_cCampaingMain = null;                                 // 캠페인 관리

        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스
        private IDataProcessUs m_cDataService = null;
        private IICReaderUs m_cDeviceICReader = null;
        private ISignPadUs m_cDeviceSignPad = null;                                 // 서명패드 
        private ISalePluItemUs m_cPluService = null;                                // 판매 등록 관리
        private IPaymentUs m_cTMoney = null;

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

        private string m_sPosMenuKey;                                                
        /// <summary>
        ///  구분
        /// </summary>
        public string SetPosMenuKey { set { this.m_sPosMenuKey = value; } }

        private string m_sSaleAmount;
        /// <summary>
        ///  외부입력 결제금액
        /// </summary>
        public string SetSaleAmount { set { this.m_sSaleAmount = value; } }

        private string m_sSearchMode;                                               
        /// <summary>
        ///  조회모드
        /// </summary>
        public string SetSearchMode { set { this.m_sSearchMode = value; } } 
        
        /// <summary>
        /// 입력구분
        /// </summary>
        private string m_sInPutType = "";    
        /// <summary>
        /// 입력데이터
        /// </summary>
        private string m_sInPutData = "";    
        /// <summary>
        /// 카드데이터
        /// </summary>
        private string m_sInEncData = "";
        /// <summary>
        /// 카드구분
        /// </summary>
        private string m_sCardType = "";

        private string m_PAY_WAY_CD = "";
        private string m_PAY_DC_CD = "";


        #endregion 변수 선언

        #region 생성자 & 소멸자 & 폼초기화
        public frmTMoney()
        {
            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_cDeviceSignPad = (ISignPadUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_SIGNPAD);
            m_cTMoney = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.TMONEY);
            m_cCampaingMain = (ICampaignUs)sManager.InitServiceInstance(ServiceLists.ASV_CAMPAIGN.DLL, ServiceLists.ASV_CAMPAIGN.CAMPAIGN_MAIN);
            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);

            delegatePos = new PosOLEDevice.DelegateOlePos(OnDeviceEvent);
        }

        private void frmTMoney_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();
            
            // 고객화면 캠페인 컨텐츠 표시
            m_cCampaingMain.CustDisplayCampaign(m_sSearchMode == "S" ? ItemConst.CPI_CUST_PAY_TYPE.TMONEY : ItemConst.CPI_CUST_PAY_TYPE.CASHBEE);
        }

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

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

        private void frmTMoney_FormClosing(object sender, FormClosingEventArgs e)
        {
            InDataToZeroFill();

            //#20181015 결제창 엑박 관련 이미지 미사용 처리 start
            //티머니 영업메뉴에서오픈시 화면 깨지는 증상 수정
            if (m_sSearchMode == "S") FormManager.SetFormAllControlMove(this, 216, 123);
            //#20181015 결제창 엑박 관련 이미지 미사용 처리 end

            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_sSearchMode == "S")
                {
                    lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0403);
                }
                else
                {
                    if (m_sPosMenuKey == PosKey.MENU_KEY.T_MONEY) lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0415);
                    else if (m_sPosMenuKey == PosKey.MENU_KEY.CASHBEE) lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0416);
                }
                lblCardNo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0051);
                lblBalanceAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0352);
                lblSaleAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0049);
                lblDCAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0036);
                lblPayAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0066);

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

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

                txtSaleAmt.Text = m_cPosStatus.Global.NumericTOCurrency((m_cDataService.DoubleParse(m_sSaleAmount) > 0) ? m_cDataService.DoubleParse(m_sSaleAmount) : m_cTrnStatus.Sale.RemainPayAmt);                // 받을금액

                txtCardNo.Text = "";        
                txtBalanceAmt.Text = "0";
                txtPayAmt.Text = "0";
                txtDCAmt.Text = "0";
                
                m_sInPutType = "";      // 입력구분
                m_sInPutData = "";      // 입력데이터
                m_sInEncData = "";       // 카드데이터

                bNotDoubleClik = false;

                m_PAY_WAY_CD = "";
                m_PAY_DC_CD = "";

                btnEnter.Visible = true;
                lblPayAmt.Visible = true;
                txtPayAmt.Visible = true;
                //lblLineAppNo.Visible = true;
                lblDCAmt.Visible = true;
                txtDCAmt.Visible = true;
                //label3.Visible = true;
                lblBox4.Visible = true;
                lblBox5.Visible = true;

                if (m_sSearchMode == "S")
                {
                    // 잔액조회
                    btnEnter.Visible = false;
                    lblPayAmt.Visible = false;
                    txtPayAmt.Visible = false;
                    //lblLineAppNo.Visible = false;
                    lblDCAmt.Visible = false;
                    txtDCAmt.Visible = false;
                    //label3.Visible = false;
                    lblBox4.Visible = false;
                    lblBox5.Visible = false;

                    //#20181015 결제창 엑박 관련 이미지 미사용 처리 start
                    //티머니 영업메뉴에서오픈시 화면 깨지는 증상 수정
                    this.Size = new Size(788, 402);
                    FormManager.SetFormAllControlMove(this, -216, -123);
                    FormManager.MovePopUpForm(this, false, m_cPosStatus.Sale.ScreenSizeUser);
                    //#20181015 결제창 엑박 관련 이미지 미사용 처리 end
                }
                else if (m_sSearchMode == "A")
                {
                    // 자동처리
                    this.Hide();

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

                        if (GetIcCardData(m_sCardType) == true)          // 카드정보 읽기
                        {
                            if (CheckTxtInPut(null, false) == false)
                            {
                                this.DialogResult = DialogResult.Cancel;
                            }
                            else if (m_cDataService.DoubleParse(txtPayAmt.Text) > 0)
                            {
                                CompleteTxtInPut();

                                this.DialogResult = DialogResult.OK;
                            }
                            else
                            {
                                this.DialogResult = DialogResult.Cancel;
                            }
                        }
                        else
                        {
                            this.DialogResult = DialogResult.Cancel;
                        }
                    }
                    else
                    {
                        this.DialogResult = DialogResult.Cancel;
                    }
                    this.Close();

                    return;
                }

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

                ////승인 종류 버튼 테마색상 적용!
                if (string.IsNullOrEmpty(m_cPosStatus.ScnMst.ThemeColor) == false)
                {
                    if (m_cPosStatus.ScnMst.ThemeColor.Length == 9)
                        btnEnter.BackColor = CmUtil.GetColorToString(m_cPosStatus.ScnMst.ThemeColor);
                }

                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)               // 카드 등록
                {
                    GetIcCardData(m_sCardType);          // 카드정보 읽기
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnSearch)        // 조회
                {
                    GetIcCardData(m_sCardType);          // 카드정보 읽기
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnEnter)         // 승인
                {
                    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)
                    {
                        btnProc_Click(btnMenu1, null);
                        //GetIcCardData(m_sCardType);  // 카드정보 읽기
                    }
                }
                else if (sFuncValue == PosKey.MENU_KEY.CLEAR)
                {
                    ((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)
                {
                    // 켐페인 취소
                    ArrayList alPayItem = (ArrayList)StateObject.GetItemObject(Column.TR_PAYMENT.ITEM);
                    m_cCampaingMain.CancelCampaignPayment(alPayItem.Count.ToString(), "");

                    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)
        {
            txtBalanceAmt.Text = "0";
            txtPayAmt.Text = "0";
            txtDCAmt.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 (m_cDataService.DoubleParse(txtBalanceAmt.Text) <= 0)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0580);
                    txtPayAmt.Focus();
                    return false;
                }

                // 캠페인 처리 => 키값(취소시사용),카드번호,캠페인대상,지불구분,지불금액
                ArrayList alPayItem = (ArrayList)StateObject.GetItemObject(Column.TR_PAYMENT.ITEM);
                double nDisAmt = m_cCampaingMain.ExecuteCampaignPayment(alPayItem.Count.ToString(), txtCardNo.Text, (m_sCardType == "T") ? ItemConst.CPI_CUST_PAY_TYPE.TMONEY : ItemConst.CPI_CUST_PAY_TYPE.CASHBEE, m_cDataService.DoubleParse(txtSaleAmt.Text));
                txtDCAmt.Text = m_cPosStatus.Global.NumericTOCurrency(nDisAmt);                                                                         // 캠페인 할인금액

                double nSaleAmt = CmUtil.DoubleSubtraction(m_cDataService.DoubleParse(txtSaleAmt.Text), nDisAmt);

                if (m_cDataService.DoubleParse(txtBalanceAmt.Text) >= nSaleAmt)
                    txtPayAmt.Text = m_cPosStatus.Global.NumericTOCurrency(nSaleAmt);                                                                   // 승인금액
                else
                    txtPayAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cDataService.DoubleParse(txtBalanceAmt.Text));                                     // 승인금액

                if (bSearchMode != true)
                {
                    if (m_cDataService.LongParse(txtPayAmt.Text).ToString().Length > 10 || m_cDataService.LongParse(txtPayAmt.Text) <= 0)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0036);
                        txtPayAmt.Focus();
                        return false;
                    }

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

                    if (m_cDataService.DoubleParse(txtSaleAmt.Text) > m_cTrnStatus.Sale.RemainPayAmt)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0039);
                        return false;
                    }

                    nSaleAmt = CmUtil.DoubleSubtraction(m_cDataService.DoubleParse(txtSaleAmt.Text), m_cDataService.DoubleParse(txtDCAmt.Text));
                    if (m_cDataService.DoubleParse(txtPayAmt.Text) > nSaleAmt)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0039);
                        txtPayAmt.Focus();
                        return false;
                    }

                    if (m_cDataService.DoubleParse(txtPayAmt.Text) > m_cDataService.DoubleParse(txtBalanceAmt.Text))
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0246);
                        txtPayAmt.Focus();
                        return false;
                    }

                }
            }
            catch (Exception ex)
            {
               WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
                return false;
            }
            return true;
        }
        #endregion

        #region 텍스트박스 입력 완료 처리
        /// <summary>
        ///  승인 처리
        /// </summary>
        /// <param name="nFlowMode"></param>
        /// <returns></returns>
        private bool CompleteTxtInPut()
        {
            string sRet = UserCom.RST_ERR;
            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 (m_sSearchMode != "A")
                {
                    if (CheckTxtInPut(null, false) == false) return false;
                }

                // 승인금액 또는 결제 금액을 확인 하세요.
                if (m_cDataService.DoubleParse(txtPayAmt.Text) <= 0)
                {
                    MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0597);
                    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;
                        sInEncData = sInPutData;
                    }
                    //EncryptedCardNo(sInPutData, ref sInEncData, ref sInPutData);
                }

                // 승인  처리
                sRet = m_cTMoney.SetPayment(new string[] { m_sPosMenuKey, sInPutType, sInPutData, sInEncData, m_cDataService.DoubleParse(txtPayAmt.Text).ToString(), "", "", m_sCardType, m_cDataService.DoubleParse(txtDCAmt.Text).ToString(), m_cDataService.DoubleParse(txtBalanceAmt.Text).ToString() });
                if (sRet != UserCom.RST_OK) return false;

                if (m_cTrnStatus.Sale.RemainPayAmt > 0)
                    WinManager.ConfirmMessage(string.Format(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0462), m_cPosStatus.Global.NumericTOCurrency(m_cTrnStatus.Sale.RemainPayAmt)));

                // 캠페인 할인결제 확정 처리 => 키값
                ArrayList alPayItem = (ArrayList)StateObject.GetItemObject(Column.TR_PAYMENT.ITEM);
                m_cCampaingMain.CompleteCampaignPayment((alPayItem.Count - 1).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);
            }
            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;
                sRet = m_cTMoney.SearchPayment(new string[] { m_sPosMenuKey, sInPutType, sInPutData, sInEncData, m_cDataService.DoubleParse(txtBalanceAmt.Text).ToString() }, ref saRecvdData);
                if (sRet != UserCom.RST_OK) return false;

                Column.TR_PAYMENT.DATA m_cPayItem = (Column.TR_PAYMENT.DATA)m_cTMoney.GetPayment(new string[] { });
                txtBalanceAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cPayItem.AMT_ENTRY_04);          // 잔액

                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)
        {
            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_KEYIN;
                    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(string sCardType)
        { 
            int iRet = -1;

            try
            {
                m_sInPutType = "";
                m_sInPutData = "";
                m_sInEncData = "";
                //txtCardNo.ReadOnly = false;

                txtCardNo.Value = "";
                txtBalanceAmt.Text = "0";
                m_PAY_WAY_CD = "";
                m_PAY_DC_CD = "";

                string sRet = "";

                // 요청 - 승인로그 저장   (판매구분, [0]결제수단, [1]결제상세코드, [2]전문구분, [3]요청구분, [4]카드번호, [5]결제금액, [6]승인번호, [7]승인일자, [8]승인시간, [9]응답상태값, [10]응답메시지, [11]전문)
                m_cDataCommon.SetSaleApprLog(PosConst.CANCEL_DIV.NORMAL, new string[] { ItemConst.TR_ITEM_ID.MOBILECASH_ITEM, ItemConst.TR_ITEM_ID.MOBILECASH.T_MONEY, "T", "S", "", txtSaleAmt.Value.ToString(), "", "", "", "", "", "TMoneyInfo" });
                //#20170919 T머니 잔액조회 호출시 첫번째 파라미터 값 변경. " " -> "0" start
                //기존
                //iRet = m_cDeviceSignPad.TMoneyInfo(" ", ref sRet, "Y");
                //변경
                iRet = m_cDeviceSignPad.TMoneyInfo("0", ref sRet, "Y");
                //#20170919 T머니 잔액조회 호출시 첫번째 파라미터 값 변경. " " -> "0" end
                // 응답 - 승인로그 저장   (판매구분, [0]결제수단, [1]결제상세코드, [2]전문구분, [3]요청구분, [4]카드번호, [5]결제금액, [6]승인번호, [7]승인일자, [8]승인시간, [9]응답상태값, [10]응답메시지, [11]전문)
                m_cDataCommon.SetSaleApprLog(PosConst.CANCEL_DIV.NORMAL, new string[] { ItemConst.TR_ITEM_ID.MOBILECASH_ITEM, ItemConst.TR_ITEM_ID.MOBILECASH.T_MONEY, "T", "R", "", txtSaleAmt.Value.ToString(), "", "", "", iRet.ToString(), "", sRet });

                if (sRet.Length > 10)
                {
                    if (CmUtil.MidH(sRet, 0, 1) == "E")
                    {
                        lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0795);
                        m_sPosMenuKey = PosKey.MENU_KEY.CASHBEE;
                        m_sCardType = "E";

                        m_PAY_WAY_CD = ItemConst.TR_ITEM_ID.MOBILECASH_ITEM;
                        m_PAY_DC_CD = ItemConst.TR_ITEM_ID.MOBILECASH.CASHBEE;
                    }   
                    else if (CmUtil.MidH(sRet, 0, 1) == "T")
                    {
                        lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0795);

                        m_sPosMenuKey = PosKey.MENU_KEY.T_MONEY;
                        m_sCardType = "T";

                        m_PAY_WAY_CD = ItemConst.TR_ITEM_ID.MOBILECASH_ITEM;
                        m_PAY_DC_CD = ItemConst.TR_ITEM_ID.MOBILECASH.T_MONEY;
                    }   
                    else
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0355);
                        return false;
                    }

                    txtCardNo.Value = CmUtil.MidH(sRet, 11, 16);
                    txtBalanceAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cDataService.DoubleParse(CmUtil.MidH(sRet, 1, 10)));

                    if (m_cDataService.DoubleParse(txtBalanceAmt.Text) > 0)
                    {
                        txtSaleAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cDataService.DoubleParse(m_sSaleAmount));         // 받을금액
                    }

                    // 특정 문자값 제거
                    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 { }

                    // 캠페인 처리 => 키값(취소시사용),카드번호,캠페인대상,지불구분,지불금액
                    ArrayList alPayItem = (ArrayList)StateObject.GetItemObject(Column.TR_PAYMENT.ITEM);
                    double nDisAmt = m_cCampaingMain.ExecuteCampaignPayment(alPayItem.Count.ToString(), txtCardNo.Text, (m_sCardType == "T") ? ItemConst.CPI_CUST_PAY_TYPE.TMONEY : ItemConst.CPI_CUST_PAY_TYPE.CASHBEE, m_cDataService.DoubleParse(txtSaleAmt.Text));
                    txtDCAmt.Text = m_cPosStatus.Global.NumericTOCurrency(nDisAmt);                                                                         // 캠페인 할인금액

                    double nSaleAmt = CmUtil.DoubleSubtraction(m_cDataService.DoubleParse(txtSaleAmt.Text), nDisAmt);

                    if (m_cDataService.DoubleParse(txtBalanceAmt.Text) >= nSaleAmt)
                        txtPayAmt.Text = m_cPosStatus.Global.NumericTOCurrency(nSaleAmt);                                                                   // 승인금액
                    else
                        txtPayAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cDataService.DoubleParse(txtBalanceAmt.Text));                                     // 승인금액
                    txtSaleAmt.Select();
                    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);
            }
        }

    }
}
