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

using Cosmos.BaseFrame;
using Cosmos.UserFrame;
using Cosmos.ServiceProvider;
using Cosmos.Common;
using Cosmos.CommonManager;
using Cosmos.UI;

using Cosmos.Win;

namespace Cosmos.Win
{
    public partial class frmTPay : frm_PayMainBack
    {
        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 IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스
        private IDataProcessUs m_cDataService = null;                               // 거래데이터 합계금액 계산 및 관리
        private IPaymentUs m_cTPayService = null;

        private IICReaderUs m_cDeviceICReader = null;
        private ISignPadUs m_cDeviceSignPad = null;
        private ITPaygleUs m_cDeviceTPaygle = null;

        /// <summary>
        /// 메뉴키
        /// </summary>
        public string PosMenuKey { set { m_posMenuKey = value; } }
        /// <summary>
        /// T페이 데이터 설정 
        /// </summary>
        /// <param name="inputType">입력구분 (PosConst.POS_VAN_MASTER.INPUT_TYPE)</param>
        /// <param name="entryMode">입력모드 (PosConst.POS_VAN_MASTER.TPAY_ENTRY_MODE)</param>
        /// <param name="inputData">입력데이터 </param>
        /// <param name="maskData">마스킹데이터 </param>
        /// <param name="encData">카드데이터(암호화)</param>
        /// <param name="destAmt">SKT 할인 대상금액</param>
        /// <param name="tradeType">T페이 결제구분 (통합/일반, PosConst.TPAY_TRADE_TYPE)</param>
        public void SetTPayData(string inputType= "", string entryMode ="", string inputData ="", string maskData ="", string encData = "", double destAmt = 0, string tradeType = "")
        {
            ClearCardData();

            this.m_inputType = inputType;
            this.m_entryMode = entryMode;
            this.m_inputData = inputData;
            this.m_inMaskData = maskData;
            this.m_inEncData = encData;
            this.m_destAmt = destAmt;
            this.m_tradeType = tradeType; 
        }


        /// <summary>
        /// 비밀번호 길이 
        /// </summary>
        private const int PASSWORD_LEN = 4;
        /// <summary>
        /// SKT(T맴버십) 할인대상 금액
        /// 할인대상 금액이 1,000원 이상일때 통합결제 
        /// 할인대상 금액이 1,000원 미만일때 일반결제 
        /// </summary>
        private const double MIN_DIS_AMT = 1000;

        /// <summary>
        /// 중복입력방지
        /// </summary>
        private bool isBusy = false;
        /// <summary>
        /// 메뉴키 (미사용)
        /// </summary>
        private string m_posMenuKey = string.Empty;
        /// <summary>
        /// 입력구분 (PosConst.POS_VAN_MASTER.INPUT_TYPE)
        /// </summary>
        private string m_inputType = string.Empty;
        /// <summary>
        /// 입력모드 (PosConst.POS_VAN_MASTER.TPAY_ENTRY_MODE)
        /// </summary>
        private string m_entryMode = string.Empty;
        /// <summary>
        /// 입력데이터
        /// </summary>
        private string m_inputData = string.Empty;
        /// <summary>
        /// 마스킹데이터
        /// </summary>
        private string m_inMaskData = string.Empty;
        /// <summary>
        /// 카드데이터(암호화)
        /// </summary>
        private string m_inEncData = string.Empty;
        /// <summary>
        /// SKT 할인 대상금액
        /// </summary>
        private double m_destAmt = 0;
        /// <summary>
        /// T페이 결제구분 (통합/일반, PosConst.TPAY_TRADE_TYPE)
        /// </summary>
        private string m_tradeType = string.Empty;

        //#20170906 T페이 고도화 작업 phj, start
        /// <summary>
        /// 선인증 데이터 담기
        /// </summary>
        string[] m_aParam = new string[2];
        //#20170906 T페이 고도화 작업 phj, end


        /// <summary>
        /// 생성자 
        /// </summary>
        public frmTPay()
        {
            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;        // POS 장치정보 

            delegatePos = new PosOLEDevice.DelegateOlePos(OnDeviceEvent);

            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
            m_cDataService = (IDataProcessUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_SERVICE);
            m_cTPayService = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.TPAY);

            m_cDeviceICReader = (IICReaderUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_ICREADER);
            m_cDeviceSignPad = (ISignPadUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_SIGNPAD);
            m_cDeviceTPaygle = (ITPaygleUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_TPAYGLE);
        }

        private void Form_Load(object sender, EventArgs e)
        {
            try
            {
                UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "");
                InitControl();
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                            System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                            ex.Message);
            }
        }

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

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

        private void Form_Closing(object sender, FormClosingEventArgs e)
        {
            try
            {
                m_destAmt = 0;
                m_posMenuKey = string.Empty;
                m_tradeType = string.Empty;
                ClearCardData();

                UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", lblTitle.Text);
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                            System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                            ex.Message);
            }
        }

        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            try
            {
                // 이미지 로딩 처리
                //this.picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_S);
                //this.picBack.Location = new Point(216, 123);
                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 = "";

                base.InitPayMainBack(m_cPosStatus, m_cDataCommon, m_posMenuKey, PosConst.MOT_MSG_TYPE.PAY_STEP_3, "");

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

                //if (m_posMenuKey == PosKey.MENU_KEY.T_PAY)
                base.lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0835);

                lblCardNo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0051);
                lblRemainAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0049);
                lblDestAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0098);
                lblPayAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0066);
                lblPassword.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0013);

                btnMenu1.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0097);
                btnMenu2.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0836);

                btnMenu1.Visible = true;
                btnMenu2.Visible = PosMstManager.GetPosOption(POS_OPTION.OPT319) == "1" ? true : false;     // Paygle 사용 옵션처리
                btnMenu3.Visible = false;
                btnMenu4.Visible = false;

                btnAppComplex.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0866);
                btnAppNormal.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0865);

                //#20170906 T페이 고도화 작업 phj, start
                //패스워드 필수 여부 컴포넌트 초기화 
                txtPasswordMsg.Visible = false;
                txtPasswordMsg.Text = string.Empty;
                //#20170906 T페이 고도화 작업 phj, end

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

                // 입력컨트롤 초기화 
                foreach (Control ctrl in this.Controls)
                {
                    if (ctrl is CsmPosEditBox)
                    {
                        CsmPosEditBox txt = (CsmPosEditBox)ctrl;
                        txt.Tag = txt.Value = string.Empty;
                    }
                }

                isBusy = false;
                if (m_destAmt < 0) m_destAmt = 0;       // 통신사(SKT) 할인 대상 금액

                //#20170906 T페이 고도화 작업 phj, start 
                //결제내역조회
                //결제내역있으면대상금액0으로초기화
                bool PayList = false;
                ArrayList alTrPayItem = (ArrayList)StateObject.GetItemObject(Column.TR_PAYMENT.ITEM);       // 결제아이템
                foreach (Column.TR_PAYMENT.DATA cPayItem in alTrPayItem)
                {
                    if (cPayItem.CANCEL_DIV == ItemConst.PAY_CANCEL_DIV.CANCEL) continue;
                    //#20171113 해피포인트사용, 모바일결제 있는 경우 T_PAY 할인대상금액 0원 현상 수정 start
                    if (cPayItem.PAY_WAY_CD == ItemConst.TR_ITEM_ID.POINT_ITEM && cPayItem.PAY_DTL_CD_01 == ItemConst.TR_ITEM_ID.POINT_USE.HAPPY_POINT) continue;
                    if (cPayItem.PAY_WAY_CD == ItemConst.TR_ITEM_ID.MOBILECON_ITEM) continue;
                    //#20171113 해피포인트사용, 모바일결제 있는 경우 T_PAY 할인대상금액 0원 현상 수정 end
                    PayList = true;
                }
                if (PayList == true) m_destAmt = 0;
                //#20170906 T페이 고도화 작업 phj, end 

                lblRemainAmout.Text = m_cPosStatus.Global.NumericTOCurrency(m_cTrnStatus.Sale.RemainPayAmt);
                lblDestAmount.Text = m_cPosStatus.Global.NumericTOCurrency(m_destAmt);

                txtCardNo.Value = m_inputData;
                txtPayAmt.Value = m_cTrnStatus.Sale.RemainPayAmt.ToString();
                txtPassword.Value = string.Empty;

                if (string.IsNullOrWhiteSpace(m_inputData))
                {
                    txtCardNo.Select();
                }
                else 
                {
                    txtPayAmt.Select();
                }

                //#20170906 T페이 고도화 작업 phj, start
                //반품이 아니고, 카드번호가 있으면 OTB 체크한다.
                if (m_cTrnStatus.Head.TradeDiv != ItemConst.TRAN_DIV.REFUND)
                {
                    if (m_inputData != String.Empty)
                    {
                        OTBCheck(m_inputData, out m_aParam);
                    }
                }
                //#20170906 T페이 고도화 작업 phj, 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);
            }
        }

        /// <summary>
        /// 카드데이터 초기화
        /// </summary>
        private void ClearCardData()
        {
            try
            {
                this.m_inputType = string.Empty;
                this.m_entryMode = string.Empty; 
                CmUtil.ZeroFillClear(ref m_inputData);
                CmUtil.ZeroFillClear(ref m_inMaskData);
                CmUtil.ZeroFillClear(ref m_inEncData);
            }
            catch { }
        }

        /// <summary>
        /// 버튼 입력 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, EventArgs e)
        {
            if (isBusy) return;

            try
            {
                if (sender == btnExit)                  // 닫기 
                {
                    EditBox_KeyDownEvent(null, PosKey.MENU_KEY.ESC_PREVIOUS);
                    return;
                }
                else if (sender == btnAppNormal)        // 일반결제
                {
                    m_tradeType = PosConst.TPAY_TRADE_TYPE.NORMAL;
                    EditBox_KeyDownEvent(txtPassword, PosKey.MENU_KEY.ENTER);
                }
                else if (sender == btnAppComplex)       // 통합결제
                {
                    m_tradeType = PosConst.TPAY_TRADE_TYPE.COMPLEX;
                    EditBox_KeyDownEvent(null, PosKey.MENU_KEY.ENTER);
                }
                else if (sender == btnMenu1)            // 핀패드
                {
                    if (GetPinPadData())
                    {
                        EditBox_KeyDownEvent(null, PosKey.MENU_KEY.ENTER);
                    }
                }
                else if (sender == btnMenu2)            // BLE 결제 
                {
                    frmTPayConnectList frm = (frmTPayConnectList)FormManager.GetForm(FormManager.FORM_PAY_TPAY_CONNECT_LIST);
                    if (frm == null)
                    {
                        frm = new frmTPayConnectList();
                        FormManager.AddForm(FormManager.FORM_PAY_TPAY_CONNECT_LIST, frm);
                    }
                    if (frm.ShowDialog() != DialogResult.OK)
                    {
                        ClearCardData();
                    }
                    else
                    {
                        m_inputData = frm.OTB;
                        m_inputType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_KEYIN;
                        m_entryMode = PosConst.POS_VAN_MASTER.TPAY_ENTRY_MODE.BLE;
                        txtCardNo.Value = m_inputData;
                        //txtCardNo.ReadOnly = true;
                        frm.ClearOTB();

                        EditBox_KeyDownEvent(txtCardNo, PosKey.MENU_KEY.ENTER);
                    }
                }
                
                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);
            }
        }

        private void btnMenu_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                Control ctrl = (Control)sender;
                if (string.IsNullOrWhiteSpace(ctrl.Text)) return; 
                ctrl.BackColor = Color.FromArgb(70, 86, 98);
                ctrl.ForeColor = Color.White;
            }
            catch { }
        }

        private void btnMenu_MouseUp(object sender, MouseEventArgs e)
        {
            try
            {
                Control ctrl = (Control)sender;
                if (string.IsNullOrWhiteSpace(ctrl.Text)) return; 
                ctrl.BackColor = Color.White;
                ctrl.ForeColor = Color.FromArgb(70, 86, 98); 
            }
            catch { }
        }

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

                switch (sFuncValue)
                {
                    case PosKey.MENU_KEY.ENTER:
                        if (CheckTxtInput(sender) == false) return;
                        if (sender == txtCardNo) txtPayAmt.Select();
                        if (sender == txtPayAmt) txtPassword.Select();
                        if (sender == txtPassword || sender == null)
                        {
                            if (CompleteTxtInput() == false) return;
                            this.DialogResult = System.Windows.Forms.DialogResult.OK;
                            this.Close();
                            return;
                        }
                        break;
                    case PosKey.MENU_KEY.CLEAR:
                        CsmPosEditBox editBox = (CsmPosEditBox)sender;
                        if (editBox.Visible == false || editBox.ReadOnly == true) return;
                        if (sender == txtCardNo)
                        {
                            ClearCardData();
                            txtCardNo.Tag = txtCardNo.Value = string.Empty;

                            //#20170906 T페이 고도화 작업 phj, start                            
                            m_aParam = null;
                            txtPasswordMsg.Visible = false;
                            txtPasswordMsg.Text = string.Empty;
                            //#20170906 T페이 고도화 작업 phj, end
                        }
                        else
                        {
                            editBox.Tag = editBox.Value = string.Empty;
                        }
                        break;
                    case PosKey.MENU_KEY.ESC_PREVIOUS:
                        this.DialogResult = DialogResult.Cancel;
                        this.Close();
                        return;
                }
            }
            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
            {
                isBusy = false; 
            }
        }

        /// <summary>
        /// 텍스트박스 활성화 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EditBox_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>
        /// <returns></returns>
        private bool CheckTxtInput(object sender)
        {
            try
            {
                string value = string.Empty;

                // 특정 문자값 제거
                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 || sender == txtCardNo)
                {
                    value = txtCardNo.Value.Trim();

                    // 카드번호 길이 확인 
                    if (value.Trim().Length < 6)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0037);
                        txtCardNo.Focus();
                        txtCardNo.SelectText();
                        return false;
                    }
                    if (value != m_inputData) 
                    {
                        ClearCardData();

                        // Card Bin Check 
                        string[] aRet = new string[10];
                        string ret = m_cTPayService.SearchPayment(new string[] { PosConst.TPAY_SEARCH_TYPE.PREFIX, value }, ref aRet);
                        if (ret != UserCom.RST_OK)
                        {
                            WinManager.ErrorMessage(ret);
                            txtCardNo.Focus();
                            txtCardNo.SelectText();
                            return false;
                        }

                        m_inputData = value;
						m_inputType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_KEYIN;
                        m_entryMode = PosConst.POS_VAN_MASTER.TPAY_ENTRY_MODE.KEYIN;

                        //#20170906 T페이 고도화 작업 phj, start
                        if (m_cTrnStatus.Head.TradeDiv != ItemConst.TRAN_DIV.REFUND)
                        {
                            OTBCheck(m_inputData, out m_aParam);
                        }
                        //#20170906 T페이 고도화 작업 phj, end
                    }
                }

                // 승인금액 
                if (sender == null || sender == txtPayAmt)
                {
                    value = txtPayAmt.Value.Trim();

                    double payAmt = m_cDataService.DoubleParse(value);
                    if (payAmt == 0)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0038);
                        txtPayAmt.Focus();
                        txtPayAmt.SelectText();
                        return false;
                    }
                    if (payAmt > m_cTrnStatus.Sale.RemainPayAmt)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0039);
                        txtPayAmt.Focus();
                        txtPayAmt.SelectText();
                        return false; 
                    }
                }

                // 비밀번호 
                if (sender == null || sender == txtPassword)
                {
                    //#20170906 T페이 고도화 작업 phj, start
                    //기존
                    /*
                    value = txtPassword.Value.Trim();
                    if (string.IsNullOrWhiteSpace(value))
                    {
                        if (GetPinPadData() == false) return false;
                        value = txtPassword.Value.Trim();
                    }

                    // 비밀번호 길이, 암호화 여부 확인 
                    if (value.Length < PASSWORD_LEN)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0074);
                        txtCardNo.Focus();
                        txtCardNo.SelectText();
                        return false;
                    }
                    */

                    //변경
                    if ((m_cTrnStatus.Head.TradeDiv != ItemConst.TRAN_DIV.REFUND) && (m_aParam[2] == "1"))
                    {
                        // 반품이 아니고 비밀번호가 불필요하면
                        // 패스워드 체크하지 않음.
                        txtPassword.Text = string.Empty;
                        txtPassword.Value = string.Empty;
                    }
                    else
                    {
                        value = txtPassword.Value.Trim();
                        if (string.IsNullOrWhiteSpace(value))
                        {
                            if (GetPinPadData() == false) return false;
                            value = txtPassword.Value.Trim();
                        }

                        // 비밀번호 길이, 암호화 여부 확인 
                        if (value.Length < PASSWORD_LEN)
                        {
                            WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0074);
                            txtCardNo.Focus();
                            txtCardNo.SelectText();
                            return false;
                        }
                    }
                    //#20170906 T페이 고도화 작업 phj, start
                }

                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 CompleteTxtInput()
        {
            try
            {
                if (CheckTxtInput(null) == false) return false;

                // 카드번호 암호화 
                if (string.IsNullOrWhiteSpace(m_inEncData))
                {
                    if (EncryptedCardNo(m_inputData, ref m_inMaskData, ref m_inEncData) == false) return false;
                }



                //#20170906 T페이 고도화 작업 phj, start
                //기존
                /*
                // 비밀번호 암호화
                string encPassword = m_cDeviceTPaygle.GetHashPassword(txtPassword.Value.Trim());
                if (string.IsNullOrWhiteSpace(encPassword))
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0545);
                    return false; 
                }
                */

                //변경
                // 반품이 아니고 
                // 비밀번호 필수 여부 (-1 : 에러 , 0 : 필요, 1 : 불필요)
                // 비밀번호가 불필요하면 패스워드 체크하지 않음.
                string encPassword = string.Empty;
                if ((m_cTrnStatus.Head.TradeDiv != ItemConst.TRAN_DIV.REFUND) &&
                    (m_aParam[2] == "1"))
                {
                    txtPassword.Text = string.Empty;
                    txtPassword.Value = string.Empty;
                }
                else
                {
                    // 비밀번호 암호화
                    encPassword = m_cDeviceTPaygle.GetHashPassword(txtPassword.Value.Trim());
                    if (string.IsNullOrWhiteSpace(encPassword))
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0545);
                        return false;
                    }
                }

                if (m_cTrnStatus.Head.TradeDiv != ItemConst.TRAN_DIV.REFUND)
                {
                    if (OTBPayStatusCheck(Convert.ToInt32(m_aParam[0]), m_aParam[1], m_tradeType) == false)
                    {
                        return false;
                    }
                }
                //#20170906 T페이 고도화 작업 phj, end

                // 통합결제/일반결제 확인
                switch (m_tradeType)
                { 
                    case PosConst.TPAY_TRADE_TYPE.COMPLEX:      // 통합결제 선택 시 
                        if (this.m_destAmt < MIN_DIS_AMT) 
                        {
                            string err = string.Format(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0542)
                                                     , m_cPosStatus.Global.NumericTOCurrency(MIN_DIS_AMT));
                            WinManager.ErrorMessage(err);
                            return false;                        
                        }
                        break; 

                    case PosConst.TPAY_TRADE_TYPE.NORMAL:       // 일반결제 선택 시 
                        //if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0543) == false) return false;
                        //m_tradeType = PosConst.TPAY_TRADE_TYPE.NORMAL;
                        break;

                    default:
                        if (this.m_destAmt < MIN_DIS_AMT)
                        {
                            if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0543) == false) return false;
                            m_tradeType = PosConst.TPAY_TRADE_TYPE.NORMAL;
                        }
                        else
                        {
                            if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0544) == false) return false;
                            m_tradeType = PosConst.TPAY_TRADE_TYPE.COMPLEX;
                        }
                        break;
                }

                double tmpDestAmt = m_tradeType == PosConst.TPAY_TRADE_TYPE.COMPLEX ? this.m_destAmt : 0;

                // T페이 결제 
                // TPAY 실바코드번호 설정 오류 수정(2017.07.17)
                string ret = m_cTPayService.SetPayment(new string[] { PosKey.MENU_KEY.T_PAY     // 0:메뉴키			(PosKey.MENU_KEY.T_PAY)
                                                                    , m_tradeType               // 1:T페이 결제구분	(PosConst.TPAY_TRADE_TYPE, 0:통합결제, 1:일반결제)
                                                                    , m_inputType               // 2:입력구분       (PosConst.POS_VAN_MASTER.INPUT_TYPE)
                                                                    , m_entryMode               // 3:입력모드		(PosConst.POS_VAN_MASTER.TPAY_ENTRY_MODE)
                                                                    , m_inputData              // 4:카드데이터		
                                                                    , m_inEncData               // 5:암호화카드번호	
                                                                    , encPassword               // 6:암호화비밀번호
                                                                    , tmpDestAmt.ToString()     // 7:할인대상금액
                                                                    , txtPayAmt.Value});        // 8:T페이결제금액
                //string ret = m_cTPayService.SetPayment(new string[] { PosKey.MENU_KEY.T_PAY     // 0:메뉴키			(PosKey.MENU_KEY.T_PAY)
                //                                                    , m_tradeType               // 1:T페이 결제구분	(PosConst.TPAY_TRADE_TYPE, 0:통합결제, 1:일반결제)
                //                                                    , m_inputType               // 2:입력구분       (PosConst.POS_VAN_MASTER.INPUT_TYPE)
                //                                                    , m_entryMode               // 3:입력모드		(PosConst.POS_VAN_MASTER.TPAY_ENTRY_MODE)
                //                                                    , m_inMaskData              // 4:카드데이터		
                //                                                    , m_inEncData               // 5:암호화카드번호	
                //                                                    , encPassword               // 6:암호화비밀번호
                //                                                    , tmpDestAmt.ToString()     // 7:할인대상금액
                //                                                    , txtPayAmt.Value});        // 8:T페이결제금액
                return ret == UserCom.RST_OK ? true : 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;
            }
            finally
            {
                m_tradeType = string.Empty;
            }
            
        }

        /// <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.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>
        /// 스캐너 이벤트 처리
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnScannerEvent(object source, EventArgs e)
        {
            try
            {
                ClearCardData();

                string scanData = m_cDevStatus.Scanner.DataLabel.Trim();
                if (string.IsNullOrWhiteSpace(scanData))
                {
                    m_inputData = "";
                    m_inputData = scanData;
                    if (m_inputData.Length > 16 && CmUtil.IsNumber(m_inputData.Substring(16, 1)) == false)
                    {
                        m_inputType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_MOBILE_SWIP;
                        m_entryMode = PosConst.POS_VAN_MASTER.TPAY_ENTRY_MODE.BARCODE;
                        txtCardNo.Value = m_inputData.Substring(0, 16);
                    }
                    else
                    {
                        m_inputType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_KEYIN;
                        m_entryMode = PosConst.POS_VAN_MASTER.TPAY_ENTRY_MODE.BARCODE;
                        txtCardNo.Value = m_inputData;
                    }
                    EditBox_KeyDownEvent(txtCardNo, PosKey.MENU_KEY.ENTER);
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                            System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                            ex.Message);
            }
            finally
            {
                m_cDevStatus.Scanner.DataClear();
            }
        }
        
        private bool GetPinPadData()
        {
            try
            {
                txtPassword.Value = string.Empty;

                string password = string.Empty;
                bool ret = m_cDeviceSignPad.GetMsg_SignPad(false, MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0074), ref password, PASSWORD_LEN);
                if (ret == false) return false; 
                
                txtPassword.Value = password;
                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; 
            }
        }

        private bool EncryptedCardNo(string inData, ref string maskData, ref string encData)
        {
            string tmpData = inData;

            try
            {
                tmpData = m_cDeviceICReader.GetEncryptedCardNo(inData).Trim();
                if (CmUtil.MidH(tmpData, 0, 2) == "00")
                {
                    encData = CmUtil.MidH(tmpData, 2, 512).Trim();
                    maskData = CmUtil.MidH(tmpData, 514, tmpData.Length - 514).Trim();     // 마스킹 데이터
                    return true;
                }
                else
                {
                    //암호화 처리 실패!
                    UserLog.WriteLogFile(UserCom.LOG_ERROR, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                                            System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                                            "Fail =>" + inData);
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0280); 
                    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;
            }
            finally
            {
                CmUtil.ZeroFillClear(ref tmpData);
                CmUtil.ZeroFillClear(ref inData);
            }
        }


        //#20170906 T페이 고도화 작업 phj, start
        #region ## OTBPasswordCheck
        //결제 비밀번호 필수 여부 체크
        //return 값 -1 : 에러 , 0 : 필요, 1 : 불필요
        private int OTBPasswordCheck(int pOTB)
        {
            if ((pOTB == 10) || (pOTB == 20) || (pOTB == 30))
            {
                txtPasswordMsg.Visible = true;
                txtPasswordMsg.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1030); //"* 결제비밀번호 필요"; 

                return 0;
            }
            else if ((pOTB == 21) || (pOTB == 31))
            {
                txtPasswordMsg.Visible = true;
                txtPasswordMsg.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1031); //"* 결제비밀번호 불필요"; 

                return 1;
            }
            else
            {
                WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0037);
                txtCardNo.Focus();
                txtCardNo.SelectText();

                return -1;
            }
        }
        #endregion
        //#20170906 T페이 고도화 작업 phj, end

        //#20170906 T페이 고도화 작업 phj, start
        #region ## OTBPayStatusCheck
        //pOTB : 카드번호
        //pMsg : 메세지
        //pPaytype : 결제 타입 (0: 통합결제, 1: 일반결제) 
        private bool OTBPayStatusCheck(int pOTB, string pMsg, string pPaytype)
        {
            if (PosConst.TPAY_TRADE_TYPE.COMPLEX == pPaytype)
            {
                // 통합결제 시도 시 
                // OTB 선인증 체크 결과 값이 10,20,21 이 아니면 통합결제 결제하지 못함.
                if ((pOTB == 10) || (pOTB == 20) || (pOTB == 21))
                {
                    if (((pOTB == 10) || (pOTB == 20)) && ((txtPassword.Text == string.Empty) || (txtPassword.Value == string.Empty)))
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0074);
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                else
                {
                    WinManager.ConfirmMessage(pMsg);
                    return false;
                }
            }
            else if (PosConst.TPAY_TRADE_TYPE.NORMAL == pPaytype)
            {
                // 일반결제 시도 시 
                // OTB 선인증 체크 결과 값이 10,30,31 이 아니면 일반결제 결제하지 못함.
                if ((pOTB == 10) || (pOTB == 30) || (pOTB == 31))
                {
                    if (((pOTB == 10) || (pOTB == 30)) && ((txtPassword.Text == string.Empty) || (txtPassword.Value == string.Empty)))
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0074);
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                else
                {
                    WinManager.ConfirmMessage(pMsg);
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        #endregion
        //#20170906 T페이 고도화 작업 phj, end

        //#20170906 T페이 고도화 작업 phj, start
        #region ## OTBCheck
        /// <summary>
        /// pOTB : 카드번호 
        /// param : 0 : 카드번호, 1 : 메세지, 2 : 결제 비밀번호 필수 여부 
        /// </summary>
        private void OTBCheck(string pOTB, out string[] param)
        {
            m_aParam = null;

            int iPasswordInput = 0;
            int iOTBCheckValue = 0;
            string sOTBCheckMsg = string.Empty;

            txtPassword.Text = string.Empty;    // 패스워드 
            txtPassword.Value = string.Empty;   // 패스워드 
            txtPasswordMsg.Visible = false;     // 패스워드 입력 여부 메세지 표시
            txtPasswordMsg.Text = string.Empty; // 패스워드 입력 여부 메세지 표시

            iOTBCheckValue = m_cDeviceTPaygle.ClassifyOTBCheck(pOTB);                       // OTB 체크
            sOTBCheckMsg = m_cDeviceTPaygle.ClassifyOTBCheckMsg(iOTBCheckValue.ToString()); // OTB 메세지 처리

            iPasswordInput = OTBPasswordCheck(iOTBCheckValue); //결제 비밀번호 필수 여부(-1 : 에러 , 0 : 필요, 1 : 불필요)

            param = new string[3];
            param[0] = iOTBCheckValue.ToString(); // OTB 체크
            param[1] = sOTBCheckMsg; // OTB 메세지 처리 
            param[2] = iPasswordInput.ToString(); //결제 비밀번호 필수 여부(-1 : 에러 , 0 : 필요, 1 : 불필요)
        }
        #endregion
        //#20170906 T페이 고도화 작업 phj, end
    }
}
