using System;
using System.Drawing;
using System.Windows.Forms;

using Cosmos.BaseFrame;
using Cosmos.UserFrame;
using Cosmos.ServiceProvider;
using Cosmos.Common;
using Cosmos.CommonManager;
using System.Collections;

using System.Data;


namespace Cosmos.Win
{

    /// <summary>
    /// CAT 단말기 사용하지 않는 점포 승인, 임의 등록
    ///     > 기능 추가 : 2017.11.07;임의 등록 시 카드사명 선택 할 수 있도록 노출;girak.kim
    /// </summary>
    public partial class frmMenualAppr : 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 IPaymentUs m_cCreditCard = null;                                    // 신용카드 결제 클래스
        private IDataProcessUs m_cDataService = null;                               // 거래데이터 합계금액 계산 및 관리
        private ISignPadUs m_cSignPad = null;                                       // 사인패드
        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스

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

        private string m_sDspAppAmt;
        /// <summary>
        /// 승인금액
        /// </summary>
        public string SetAppAmt { set { this.m_sDspAppAmt = value; } }

        private string m_sPosMenuKey;
        /// <summary>
        /// POS 기능키
        /// </summary>
        public string SetPosMenuKey { set { this.m_sPosMenuKey = value; } }

        private string m_sDspDcAmt;
        /// <summary>
        /// 할인금액
        /// </summary>
        public string SetDcAmt { set { this.m_sDspDcAmt = value; } }

        private string m_sDspDcCode;
        /// <summary>
        /// 할인코드
        /// </summary>
        public string SetDcCode { set { this.m_sDspDcCode = value; } }
        
        /// <summary>
        /// 카드사 코드
        /// </summary>
        private string m_sCardCmp = "";

        /// <summary>
        /// 카드사 명
        /// </summary>
        private string m_sCardCmpNM = "";

        #endregion 변수 선언

        #region 생성자 & 소멸자
        public frmMenualAppr()
        {
            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);
#if !DEVICE_MSR_VER                       
            m_cCreditCard = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.CREDITCARD);
#else
            m_cCreditCard = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.MSRCARD);
#endif            
            m_cSignPad = (ISignPadUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_SIGNPAD);
            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);

            delegatePos = new PosOLEDevice.DelegateOlePos(OnDeviceEvent);
        }

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

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

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

        #endregion 생성자 & 소멸자
        
        #region 폼 컨트롤 초기화
        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            try
            {
                this.Location = new Point(0, 50);
                this.Size = new Size(1024, 525);
                
                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);

                ////테마색상 적용!
                btnEnter.BackColor = CmUtil.GetColorToString(m_cPosStatus.ScnMst.ThemeColor);
                
                btnExit.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BTN_CLOSE);
                if (btnExit.Image != null) btnExit.Text = "";

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0364);
                lblCardNo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0051);
                lblDspAppAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0066);
                lblCardComp.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0196);
                lblAppNo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0053);
                lblDivMonth.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0050);
                btnEnter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0126);
                                
                btnCardListKeyin.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0364);//임의 등록

                txtDspAppAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cDataService.DoubleParse(m_sDspAppAmt));
                
                bNotDoubleClik = false;

                txtCardNo.Value = "";
                txtDivMonth.Value = "";
                txtAppNo.Value = "";
                txtCardComp.Text = "";

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

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

                //Start 2017.11.07.001;임의 등록 시 카드사명 선택 할 수 있도록 노출;girak.kim
                #region
                if (m_cPosStatus.Base.CmpCd.ToUpper().Equals(PosConst.POS_COMPANY_CODE.PCCN))
                {
                    panCardCmp.Location = new Point(238, 271);
                    panCardCmp.Visible = true;

                    btnCardListKeyin.Location = new Point(3, 3);
                    btnCardListKeyin.BackColor = Color.FromArgb(22, 187, 238);

                    txtCardNo.InputType = UI.InputType.None;
                    txtCardNo.ReadOnly = true;

                    LoadFuncMaster("N");

                    //Start 2017.11.06;승인번호 자동 입력;girak.kim;(기존에 6~8자리로 정해져 있어 길이를 늘이지는 않음)
                    //string StoreNo = m_cPosStatus.Base.StoreNo;
                    //if (StoreNo.Length < 3) StoreNo = StoreNo.PadLeft(3, '0');
                    //txtAppNo.Text = StoreNo.Substring(StoreNo.Length - 3) + ran.Next(99999).ToString().PadLeft(5, '0');

                    var ran = new Random();
                    txtAppNo.Text = DateTime.Now.ToString("MMdd") + ran.Next(9999).ToString().PadLeft(4, '0');
                    //End 2017.11.06;승인번호 자동 입력;girak.kim;

                }                    
                else if (m_cPosStatus.Base.CmpCd.ToUpper().Equals(PosConst.POS_COMPANY_CODE.PCUS))
                {
                    //2018.01.17;미주일 경우 승인번호 자동 입력;girak.kim
                    var ran = new Random();
                    txtAppNo.Text = DateTime.Now.ToString("MMdd") + ran.Next(9999).ToString().PadLeft(4, '0');
                }
                else
                {
                    panCardCmp.Visible = false;
                }
                #endregion
                //End 2017.11.07.001;임의 등록 시 카드사명 선택 할 수 있도록 노출;girak.kim

               


                txtAppNo.Select();
                //txtCardNo.Select();

            }
            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) == btnEnter)             // 카드입력
                {
                    if (CompleteTxtInPut() == true)
                    {
                        MenualApproval();
                    }
                }
            }
            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;
        }
        private void btnExit_Click(object sender, EventArgs e)
        {
            try
            {
                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);
            }
        }
        #endregion

        #region 텍스트박스 입력 이벤트 처리
        /// <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="sFuncValue"></param>
        private void txtEditBox_EditBoxKeyDownEvent(object sender, string sFuncValue)
        {
            try
            {
                if (sFuncValue == PosKey.MENU_KEY.ENTER)
                {
                    #region
                    if (((Cosmos.UI.CsmPosEditBox)sender) == txtCardNo)
                    {
                        if (CheckTxtInPut(txtCardNo) == false) return;
                        CardDataDisplay();
                        txtDivMonth.Select();
                    }
                    else if (((Cosmos.UI.CsmPosEditBox)sender) == txtDivMonth)
                    {
                        if (CheckTxtInPut(txtDivMonth) == false) return;
                        txtAppNo.Select();
                    }
                    else if (((Cosmos.UI.CsmPosEditBox)sender) == txtAppNo)
                    {
                        if (CheckTxtInPut(null) == false) return;

                        if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0130) == true)
                        {
                            MenualApproval();
                        }
                    }
                    #endregion
                }
                else if (sFuncValue == PosKey.MENU_KEY.CLEAR)
                {
                    if (((Cosmos.UI.CsmPosEditBox)sender).ReadOnly == false) ((Cosmos.UI.CsmPosEditBox)sender).Text = "";
                }
                else if (sFuncValue == PosKey.MENU_KEY.ESC_PREVIOUS)
                {
                    bNotDoubleClik = false;

                    this.DialogResult = DialogResult.Cancel;
                    this.Close();
                }
                //Start 2017.11.07.001;임의 등록 추가;girak.kim
                else if (sFuncValue == PosKey.MENU_KEY.CNVN_REG)
                {
                   // panCardCmp.Visible = false;
                }
                //End 2017.11.07.001;임의 등록 추가;girak.kim
            }
            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>
        /// <returns></returns>
        private bool CheckTxtInPut(object sender)
        {
            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 { }

                //Start 2017.11.07.001;임의 등록 카드사를 선택하지 않은 경우 리턴 false;girak.kim
                if (m_cPosStatus.Base.CmpCd.ToUpper().Equals(PosConst.POS_COMPANY_CODE.PCCN))
                {
                    if (string.IsNullOrEmpty(m_sCardCmp) || string.IsNullOrEmpty(m_sCardCmp))
                    {
                        panCardCmp.Visible = true;
                        return false;
                    }
                }

                //End 2017.11.07.001;임의 등록 카드사를 선택하지 않은 경우 리턴 false;girak.kim

                if (sender == null || ((Cosmos.UI.CsmPosEditBox)sender) == txtCardNo)
                {
                    // 카드번호 길이 체크
                    //if (txtCardNo.Text.Length < 6)
                    //{
                    //    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0037);
                    //    txtAppNo.Text = "";
                    //    return false;
                    //}
                }
                if (sender == null || ((Cosmos.UI.CsmPosEditBox)sender) == txtDivMonth)
                {
                    #region
                    if (txtDivMonth.Value == "")
                    {
                        txtDivMonth.Value = "00";
                    }
                    else
                    {
                        txtDivMonth.Value = txtDivMonth.Value.ToString().PadLeft(2, '0');
                    }

                    //#13341 신용카드 할부 개월 수 제한 기능 적용 start, phj
                    // 1. 신용카드 할부 개월 수 제한 기능 적용
                    // 2. 공통코드에 [신용카드 허용 할부개월 수] 추가 후 해당 개월 수 이상 입력 시
                    string sDivMonth = string.Empty;
                    sDivMonth = m_cDataCommon.MstCmmSearch("T0033", "1");
                    if (sDivMonth != "")
                    {
                        if (int.Parse(sDivMonth, 0) < int.Parse(txtDivMonth.Value, 0))
                        {
                            WinManager.ConfirmMessage(string.Format(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0766), sDivMonth));
                            txtDivMonth.Value = "00";
                            return false;
                        }
                    }
                    //#13341 신용카드 할부 개월 수 제한 기능 적용 end, phj
                    #endregion
                }
                if (sender == null || ((Cosmos.UI.CsmPosEditBox)sender) == txtAppNo)
                {
                    #region
                    // 승인번호 길이 체크
                    if (txtAppNo.Text.Length < 6 || txtAppNo.Text.Length > 8)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0040);
                        txtAppNo.Text = "";
                        return false;
                    }
                    #endregion
                }

                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 User Method

        /// <summary>
        /// 등록 처리
        /// </summary>
        /// <param name="nFlowMode"></param>
        /// <returns></returns>
        private bool CompleteTxtInPut()
        {
            try
            {
                if (CheckTxtInPut(null) == false) 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;
        }

        #region 임의 등록 처리
        /// <summary>
        /// 임의 등록 처리
        /// <param name=""></param>
        /// </summary>
        /// <returns></returns>
        private string MenualApproval()
        {

            string sRet = UserCom.RST_ERR;
            string m_sSign = "";
            string sPath = BaseCom.NxDataPath + "SIGN\\";

            CmUtil.CreateDirectory(sPath);

            // 정상 승인 거래만 전자서명 처리(2017.05.27)
            #region
            //싸인 받기
            //if (m_cDevStatus.SignPad.UseYn == true)
            //{
            //    if (m_cDataService.DoubleParse(m_sDspAppAmt) > m_cDataService.DoubleParse(CmUtil.IsNull(PosMstManager.GetPosOption(POS_OPTION.OPT007), "50000")))
            //    {
            //        if (m_cSignPad.GetSign_SignPadEx(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0557), string.Format(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0583)
            //                    , m_cPosStatus.Global.NumericTOCurrency(m_cDataService.DoubleParse(m_sDspAppAmt))), "", "", sPath, "SIGN.BMP", ref m_sSign) == false)
            //        {
            //            m_sSign = "";
            //        }
            //    }
            //}
            //else
            //{
            //    UserLog.WriteLogFile(UserCom.LOG_DEBUG,
            //                    System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
            //                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
            //                    System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
            //                    "Not Use SingPad Skip!");
            //}
            #endregion

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

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

            try
            {

                txtCardComp.Text =  MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0364);//임의등록
                txtCardComp.Tag = "99";//고정값

                //임의 등록 처리
                sRet = m_cCreditCard.SetMenualPayment(new string[] { 
                      txtCardNo.Value // 대상카드 번호 , 0
                    , PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_KEYIN //,1
                    , "" //2
                    , txtDivMonth.Value//3
                    , m_sDspAppAmt // 승인 금액,4
                    , "0", "0", "", "", ""//5,6,7,8,9
                    , m_sSign//10
                    , "", "0"//11,12
                    , txtAppNo.Value //승인 번호,13
                    ,"",""//14,15
                    ,txtCardComp.Tag.ToString() //임의등록시 코드값 99 value,16
                    ,txtCardComp.Text //임의 등록,17
                    , m_sDspDcCode //카드 할인 타입,18
                    , m_sDspDcAmt //카드 할인 금액,19
                    ,ItemConst.PAY_APP_DIV.COMPULSION,"",""//20,21,22
                    , m_sCardCmp ,m_sCardCmpNM  // 2017.11.07.001;임의 등록에서 선택된 카드사 코드명, 카드사명;girak.kim
                });//20,21,22
                
                if (sRet == UserCom.RST_OK)
                {
                    this.DialogResult = DialogResult.OK;
                    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);
                return sRet;
            }
            return sRet;
        }
        #endregion 임의 등록 처리


        #region  //Start 2017.11.07;임의 등록 시 카드사명 선택 할 수 있도록 노출;girak.kim
        /// <summary>
        /// 기능키 컨트롤 초기화 및 기능키 마스터 로딩
        /// </summary>
        /// <returns>성공/실패</returns>
        public bool LoadFuncMaster(string sCardDiv)
        {
            try
            {
                // List 조회 
               // m_sCardCmp = "";
                //if (sCardDiv == PosConst.CAT_MODEL_DIV._CHN_SAND) sCardDiv = "S";
                //if (sCardDiv == PosConst.CAT_MODEL_DIV._CHN_UNION) sCardDiv = "U";
                
                DataTable dtMemu = m_cDataCommon.SeletCardCmp(sCardDiv);
                if (dtMemu == null || dtMemu.Rows.Count <= 0)
                {
                    //WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0059); // 메뉴키 마스터가 없습니다
                    return false;
                }

                // 우측 상단 기능키 초기화
                btnMenu.BackColor = CmUtil.GetColorToString("223223223");
                btnMenu.VisibleUpDown = true;
                btnMenu.BackColorUpDown = Color.White;
                btnMenu.ForeColorUpDown = Color.Black;
                btnMenu.ClearMenuButtonInfo();                     // 설정된 메뉴정보 초기화

                // 메뉴정보 설정
                foreach (DataRow dr in dtMemu.Rows)
                {
                    Cosmos.UI.CsmMenu.MenuBtnInfo cMenuInfo = new Cosmos.UI.CsmMenu.MenuBtnInfo();

                    cMenuInfo.nSeqNo = CmUtil.GetDataRowInt(dr, PosMst.MST_CARD_CMP_KEY.DATA.SEQ);                                                                  // SEQ
                    cMenuInfo.sClassCode = CmUtil.GetDataRowStr(dr, PosMst.MST_CARD_CMP_KEY.DATA.STOR_CD);                                                          // 점포코드
                    cMenuInfo.sGroupCode = "1";                                                                                                                     // SUB 그룹

                    string sMenuCode = null;
                    sMenuCode = CmUtil.RPadH(CmUtil.GetDataRowStr(dr, PosMst.MST_CARD_CMP_KEY.DATA.TERM_DIV), 1)                                                    // 구분
                              + CmUtil.RPadH(CmUtil.GetDataRowStr(dr, PosMst.MST_CARD_CMP_KEY.DATA.CARD_CMP_CD), 2)                                                 // 코드 
                              + CmUtil.RPadH(CmUtil.GetDataRowStr(dr, PosMst.MST_CARD_CMP_KEY.DATA.CARD_CMP_NM), 100);                                              // 명

                    cMenuInfo.sMenuCode = sMenuCode;                                                                                                                // 메뉴 코드
                    cMenuInfo.sMenuName = CmUtil.GetDataRowStr(dr, PosMst.MST_CARD_CMP_KEY.DATA.CARD_CMP_NM);                                                       // 메뉴 명 

                    cMenuInfo.cBackColor = CmUtil.GetColorToString(CmUtil.GetDataRowStr(dr, PosMst.MST_CARD_CMP_KEY.DATA.BACKGR_COLOR));                            // 버튼 BACK 컬러
                    cMenuInfo.cForeColorName = Color.FromArgb(51, 51, 51);                                                                                          // 메뉴명 컬러
                    cMenuInfo.cForeColorPrice = Color.Red; //Color.FromArgb(102, 102, 102);                                                                         // 메뉴가격 컬러
                    cMenuInfo.fFontSizeName = CmUtil.GetDataRowFloat(dr, PosMst.MST_CARD_CMP_KEY.DATA.FONT_SIZE);                                                   // 메뉴명 폰트 사이즈
                    cMenuInfo.fFontSizePrice = CmUtil.GetDataRowFloat(dr, PosMst.MST_CARD_CMP_KEY.DATA.FONT_SIZE);                                                  // 메뉴 가격 폰트 사이즈
                    cMenuInfo.nButtonSize = CmUtil.GetDataRowInt(dr, PosMst.MST_CARD_CMP_KEY.DATA.BTN_SIZE);  // 버튼 사이즈(0:일반,1:가로확대,2:세로확대,3:가로세로확대)                                                       // 메뉴버튼 사이즈(0:일반,1:가로확대,2:세로확대,3:가로세로확대)

                    cMenuInfo.cMenuImage = null;
                    //if (CmUtil.GetDataRowStr(dr, PosMst.MST_COUPON_DC_KEY.DATA.BTN_ITEM_IMG) != "")
                    //{
                    //    //cMenuInfo.cMenuImage = CmUtil.LoadImage(BaseCom.NxCDPPath + @"ITEM\" + CmUtil.GetDataRowStr(dr, PosMst.MST_COUPON_DC_KEY.DATA.BTN_ITEM_IMG));   // 메뉴 이미지
                    //}
                    btnMenu.AddMenuButtonInfo(cMenuInfo);
                }

                //btnMenu.SetMenuButtonCount(4, 4);
                btnMenu.SetMenuButtonCount(3, 4);
                btnMenu.DisplayMenuButton(m_cPosStatus.Base.StoreNo, "1");              // 버튼 표시

                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>
        /// <param name="sender"></param>
        /// <param name="sMenuCode"></param>
        private void btnMenu_MenuClickHandler(object sender, string sMenuCode)
        {
            try
            {
                if (sMenuCode == "") return;

                // 메뉴 키 값 = 구분(1) + 코드(2) + 명(100) 

                m_sCardCmp = CmUtil.MidH(sMenuCode, 1, 2).Trim();
                m_sCardCmpNM = CmUtil.MidH(sMenuCode, 3, 100).Trim();
                txtCardNo.Text = m_sCardCmp;

                if (CmUtil.MidH(sMenuCode, 0, 1).Trim() == "N")
                {
                    // 임의등록
                    txtEditBox_EditBoxKeyDownEvent(null, PosKey.MENU_KEY.CNVN_REG);
                }               
                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);
            }
        }

        #endregion

        #region 카드데이터 화면 표시
        /// <summary>
        /// 카드데이터 화면 표시
        /// </summary>
        /// <returns></returns>
        private void CardDataDisplay()
        {
            try
            {
                txtCardComp.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0364);
                txtCardComp.Tag = "99";
            }
            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

        #endregion User Method
        
        #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
            {
            }
            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
            {
            }
            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
    }
}
