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

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

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 식권 
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Win
{
    public partial class frmMealTicket : Form
    {

        #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 IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스
        private IDataProcessUs m_cDataService = null;
        private IPaymentUs m_cMealTicket = null;

        private string m_sPosMenuKeyIn;
        public string PosMenuKeyIn { set { m_sPosMenuKeyIn = value; } get { return m_sPosMenuKeyIn; } }
        private string m_sPosMenuKeyOut;
        public string PosMenuKeyOut { set { m_sPosMenuKeyOut = value; } get { return m_sPosMenuKeyOut; } }

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

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

        /// <summary>
        /// 입력구분
        /// </summary>
        private string m_sInPutType = "";
        /// <summary>
        /// 입력데이터
        /// </summary>
        private string m_sInPutData = "";
        /// <summary>
        /// 카드데이터
        /// </summary>
        private string m_sInEncData = "";
        /// <summary>
        /// 결제구분
        /// </summary>
        private string m_sPay_DC_Grp_Type = "";
        /// <summary>
        /// 결제상세구분
        /// </summary>
        private string m_sPay_DC_CD = "";

        /// <summary>
        /// 잔액교환권 금액
        /// </summary>
        private double nExchangeTicketAmt = 0;
        /// <summary>
        /// 잔액교환권 발행구분
        /// </summary>
        private string sExchange_Ticket_Type = "";
        /// <summary>
        /// 잔액교환권 번호
        /// </summary>
        private string sExchange_Ticket_No = "";

        /// <summary>
        /// 식권구분 - 교환권 가능여부
        /// </summary>
        private string m_sMealTicketType = "0";
        /// <summary>
        /// 거스름 가능여부
        /// </summary>
        private string m_sChange_Paymnt_YN = "0";
        /// <summary>
        /// 번호필수
        /// </summary>
        private string m_sMNDTRY_INPUT_YN = "0";
        /// <summary>
        /// 식권권종
        /// </summary>
        private string m_sMealTicketDiv = ""; 

        #endregion 변수 선언

        #region 생성자 & 소멸자 & 폼초기화
        public frmMealTicket()
        {
            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_cDataService = (IDataProcessUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_SERVICE);
            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
            m_cMealTicket = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.MEALTICKET);
        }

        private void frmMealTicket_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 frmMealTicket_Activated(object sender, EventArgs e)
        { 
        }

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

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

        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            try
            {
                // 이미지 로딩 처리
                this.Size = new Size(800, 578);
                this.Location = new Point(1024 - 800 - 10, 768 - 600);
                picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_800X578);
                picBack.Location = new Point(0, 0);

                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);

                //테마색상 적용!
                btnComplete.BackColor = CmUtil.GetColorToString(m_cPosStatus.ScnMst.ThemeColor);
                padInPut.ThemeColor = m_cPosStatus.ScnMst.ThemeColor;
                padInPut.ClearBtnText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0817);
                padInPut.SearchBtnText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1018);

                //버튼이미지 적용
                btnAllUp.DefaultImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_210X48_UP1_BASIC);
                btnAllUp.ClickImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_210X48_UP1_PRESS);
                btnAllDw.DefaultImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_210X48_DOWN1_BASIC);
                btnAllDw.ClickImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_210X48_DOWN1_PRESS);    
            
                btnExit.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BTN_CLOSE);
                if (btnExit.Image != null) btnExit.Text = "";

                // 타이틀
                if (m_sPosMenuKey == PosKey.MENU_KEY.MEAL_TICKET) lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0258);

                m_sPay_DC_Grp_Type = ItemConst.TR_ITEM_ID.PAYETC_ITEM;
                m_sPay_DC_CD = ItemConst.TR_ITEM_ID.PAYETC.MEAL_TIKET;

                lblCardNo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0259);
                lblCardNM.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0260);
                lblAmount.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0261);
                lblQty.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0262);
                lblPayAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0037);
                lblSaleAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0267);

                btnAdd.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0224);                           // 추가
                btnDelete.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0021);                        // 삭제
                btnComplete.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0263);                      // 결제
                btnExchangeTicket.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0266);                // 교환권

                txtCardNo.Text = "";
                txtCardNM.Text = "";
                txtAmount.Text = "0";
                txtQty.Text = "0";
                txtPayAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cTrnStatus.Sale.RemainPayAmt);             // 받을금액
                txtSaleAmt.Text = "0";
                
                m_sInPutType = "";                                                                                  // 입력구분
                m_sInPutData = "";                                                                                  // 입력데이터
                m_sInEncData = "";                                                                                  // 카드데이터

                m_sMealTicketType = "0";                                                                            // 교환권 가능 여부
                m_sChange_Paymnt_YN = "0";                                                                          // 거스름 가능 여부
                m_sMNDTRY_INPUT_YN = "0";                                                                                 // 번호필수여부
                m_sMealTicketDiv = "";                                                                              // 식권권종

                nExchangeTicketAmt = 0;                                                                             // 잔액교환권 금액
                sExchange_Ticket_Type = "";                                                                         // 잔액교환권 발행구분
                sExchange_Ticket_No = "";                                                                           // 잔액교환권 번호
                
                bNotDoubleClik = false;

                // 한국인 경우만 잔액교환권 활성화
                btnExchangeTicket.Visible = true;
                if (m_cPosStatus.Mst.CntryDiv != ItemConst.CNTRY_DIV.KR)
                {
                    btnExchangeTicket.Visible = false;
                }

                LoadFuncMaster();           // 기능키 설정

                DataGridSetting(0);         // 그리드 초기화

                txtQty.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)
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                if (bNotDoubleClik) return;
                bNotDoubleClik = true;

                if ((UI.CsmButton)sender == btnAllUp)                               // 상단 그리드 Up
                {
                    if (dgvData.Rows.Count == 0)
                    {
                        bNotDoubleClik = false;
                        return;
                    }
                    if (dgvData.CurrentRow.Index > 0)
                    {
                        for (int iLoop = dgvData.CurrentRow.Index - 1; iLoop >= 0; iLoop--)
                        {
                            if (dgvData.Rows[iLoop].Visible == false) continue;

                            dgvData.Rows[iLoop].Selected = true;
                            dgvData.Rows[iLoop].Cells[dgvData.CurrentCell.ColumnIndex].Selected = true;
                            break;
                        }
                    }
                }
                else if ((UI.CsmButton)sender == btnAllDw)                          // 상단 그리드 Down
                {
                    if (dgvData.Rows.Count == 0)
                    {
                        bNotDoubleClik = false;
                        return;
                    }
                    if (dgvData.CurrentRow.Index < dgvData.Rows.Count - 1)
                    {
                        for (int iLoop = dgvData.CurrentRow.Index + 1; iLoop <= dgvData.Rows.Count - 1; iLoop++)
                        {
                            if (dgvData.Rows[iLoop].Visible == false) continue;

                            dgvData.Rows[iLoop].Selected = true;
                            dgvData.Rows[iLoop].Cells[dgvData.CurrentCell.ColumnIndex].Selected = true;
                            break;
                        }
                    }
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnAdd)                    // 추가
                {
                    // 식권추가
                    DataGridSetting(1);
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnDelete)            // 삭제
                {
                    // 식권삭제
                    DataGridSetting(2);
                }
                if (((Cosmos.UI.CsmButton)sender) == btnExchangeTicket)         // 교환권
                {
                    // 잔액교환권
                    sRet = CompleteTxtInPut(true);

                    bNotDoubleClik = false;
                    if (sRet != UserCom.RST_OK) return;

                    this.DialogResult = DialogResult.OK;
                    this.Close();
                    return;
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnComplete)          // 결제
                {                    
                    // 결제
                    sRet = CompleteTxtInPut(false);

                    bNotDoubleClik = false;
                    if (sRet != UserCom.RST_OK) return;

                    this.DialogResult = DialogResult.OK;
                    this.Close();
                    return;
                }
                //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>
        /// <returns>성공/실패</returns>
        public bool LoadFuncMaster()
        {
            try
            {
                // 식권 List 조회
                btnMenu.ClearMenuButtonInfo();

                DataTable dtMemu = m_cDataCommon.SeletMealTicketFuncKey(m_sPay_DC_Grp_Type, m_sPay_DC_CD);
                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_MEALTICKET_KEY.DATA.SEQ);                                                                // SEQ
                    cMenuInfo.sClassCode = CmUtil.GetDataRowStr(dr, PosMst.MST_MEALTICKET_KEY.DATA.STOR_CD);                                                        // 점포코드
                    cMenuInfo.sGroupCode = "1";                                                                                                                     // SUB 그룹

                    string sMenuCode = null;
                    sMenuCode = CmUtil.RPadH(CmUtil.GetDataRowStr(dr, PosMst.MST_MEALTICKET_KEY.DATA.MEALTICKET_TYPE), 1)                                           // 잔액교환권 가능 여부
                              + CmUtil.LPadH(CmUtil.GetDataRowStr(dr, PosMst.MST_MEALTICKET_KEY.DATA.CHANGE_PAYMNT_YN), 1)                                          // 거스름 가능 여부
                              + CmUtil.LPadH(CmUtil.GetDataRowStr(dr, PosMst.MST_MEALTICKET_KEY.DATA.NO_INPUT_YN), 1)                                               // 번호필수 여부
                              + CmUtil.RPadH(CmUtil.GetDataRowStr(dr, PosMst.MST_MEALTICKET_KEY.DATA.MEALTICKET_CD), 40)                                            // 식권구분코드
                              + CmUtil.LPadH(CmUtil.GetDataRowStr(dr, PosMst.MST_MEALTICKET_KEY.DATA.MEALTICKET_AMOUNT), 20)                                        // 금액
                              + CmUtil.RPadH(CmUtil.GetDataRowStr(dr, PosMst.MST_MEALTICKET_KEY.DATA.MEALTICKET_NM), 80);                                           // 식권명

                    cMenuInfo.sMenuCode = sMenuCode;                                                                                                                // 메뉴 코드
                    cMenuInfo.sMenuName = CmUtil.GetDataRowStr(dr, PosMst.MST_MEALTICKET_KEY.DATA.MEALTICKET_NM);                                                   // 메뉴 명
                    cMenuInfo.sMenuPrice = m_cPosStatus.Global.NumericTOCurrency(CmUtil.GetDataRowDouble(dr, PosMst.MST_MEALTICKET_KEY.DATA.MEALTICKET_AMOUNT));    // 메뉴 가격

                    cMenuInfo.cBackColor = CmUtil.GetColorToString(CmUtil.GetDataRowStr(dr, PosMst.MST_MEALTICKET_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_MEALTICKET_KEY.DATA.FONT_SIZE);                                                 // 메뉴명 폰트 사이즈
                    cMenuInfo.fFontSizePrice = CmUtil.GetDataRowFloat(dr, PosMst.MST_MEALTICKET_KEY.DATA.FONT_SIZE);                                                // 메뉴 가격 폰트 사이즈
                    cMenuInfo.nButtonSize = CmUtil.GetDataRowInt(dr, PosMst.MST_MEALTICKET_KEY.DATA.BTN_SIZE);                                                      // 메뉴버튼 사이즈(0:일반,1:가로확대,2:세로확대,3:가로세로확대)

                    cMenuInfo.sMenuEtc = "";
                    if (CmUtil.GetDataRowStr(dr, PosMst.MST_MEALTICKET_KEY.DATA.NO_INPUT_YN) == "1")
                        cMenuInfo.sMenuEtc = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0999);
                    cMenuInfo.cForeColorEtc = Color.Blue;
                    cMenuInfo.fFontSizeEtc = CmUtil.GetDataRowFloat(dr, PosMst.MST_MEALTICKET_KEY.DATA.FONT_SIZE) - 2;

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

                btnMenu.SetMenuButtonCount(3, 3);
                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) + 거스름가능여부(1) + 번호필수구분(1) + 식권구분코드(40) + 금액(20) + 식권명(80) 
                m_sMealTicketType = CmUtil.MidH(sMenuCode, 0, 1).Trim();
                m_sChange_Paymnt_YN = CmUtil.MidH(sMenuCode, 1, 1).Trim();
                m_sMNDTRY_INPUT_YN = CmUtil.MidH(sMenuCode, 2, 1).Trim();
                m_sMealTicketDiv = CmUtil.MidH(sMenuCode, 3, 40).Trim();
                if (m_sMNDTRY_INPUT_YN == "1")
                {
                    // 번호필수
                    txtCardNo.Text = "";
                    txtCardNo.ReadOnly = false;
                    txtQty.ReadOnly = true;
                    txtQty.Text = "1";
                    txtCardNo.Focus();
                }
                else
                {
                    txtCardNo.Text = CmUtil.MidH(sMenuCode, 3, 40).Trim();
                    txtCardNo.ReadOnly = true;
                    txtQty.ReadOnly = false;
                    txtQty.Text = "0";
                    txtQty.Focus();
                }

                txtCardNM.Text = CmUtil.MidH(sMenuCode, 63, 80).Trim();
                txtAmount.Text = m_cPosStatus.Global.NumericTOCurrency(m_cDataService.DoubleParse(CmUtil.MidH(sMenuCode, 43, 20).Trim()));
                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>
        /// <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) == txtQty)
                    {
                        DataGridSetting(1);
                    }

                }
                else if (sFuncValue == PosKey.MENU_KEY.CLEAR)
                {
                    if (((Cosmos.UI.CsmPosEditBox)sender) == txtQty)
                    {
                        txtQty.Text = "0";                    }
                }
                else if (sFuncValue == PosKey.MENU_KEY.ESC_PREVIOUS)
                {
                    this.DialogResult = DialogResult.Cancel;
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        /// <summary>
        /// 텍스트박스 활성화 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtEditBox_EnterEvent(object sender, EventArgs e)
        {
            try
            {
                padInPut.SetActiveControl = (Control)sender;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion

        #region 텍스트박스 입력 유효성 체크
        /// <summary>
        /// 텍스트박스 입력 유효성 체크
        /// </summary>
        /// <param name="sender"></param>
        /// <returns></returns>
        private bool CheckTxtInPut(object sender)
        {
            try
            {
                // 식권 체크
                if (sender == null || ((Cosmos.UI.CsmPosEditBox)sender) == txtCardNo)
                {
                    if (m_sMNDTRY_INPUT_YN == "1" && txtCardNo.Text.Length != 16)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0646);
                        txtCardNo.Select();
                        txtCardNo.SelectText();
                        return false;
                    }
                    else
                    {
                        if (txtCardNo.Text.Length <= 0)
                        {
                            WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0177);
                            return false;
                        }
                    }
                }

                // 수량 체크
                if (sender == null || ((Cosmos.UI.CsmPosEditBox )sender) == txtQty)
                {
                    if (m_cDataService.DoubleParse(txtQty.Value) <= 0) txtQty.Text = "1";
                }

                // 추가 금액 체크
                if (m_cDataService.DoubleParse(txtSaleAmt.Text) >= m_cDataService.DoubleParse(txtPayAmt.Text))
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0208);
                    if (m_sMNDTRY_INPUT_YN == "1")
                    {
                        txtCardNo.Select();
                        txtCardNo.SelectText();
                    }
                    else
                    {
                        txtQty.Select();
                        txtQty.SelectText();
                    }
                    return false;
                }

                //////// 받은금액과 식권금액 체크
                //////double nSaleAmount = CmUtil.DoubleMultiplication(m_cDataService.DoubleParse(txtAmount.Text.Trim()), m_cDataService.DoubleParse(txtQty.Text.Trim()));
                //////nSaleAmount = CmUtil.DoubleAdd(nSaleAmount, DataGridSetting(4));

                //////if (m_cDataService.DoubleParse(txtPayAmt.Text) < nSaleAmount)
                //////{
                //////    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0039);
                //////    txtQty.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 string CompleteTxtInPut(bool bExchangeMode)
        {
            string sRet = UserCom.RST_ERR;
            double nExchangeAmount = 0;
            double nChangeMoney = 0;

            string[] aRspRet = null;

            try
            {
                if (dgvData.RowCount <= 0) return sRet;

                if (bExchangeMode == true)
                {
                    // 잔액교환권
                    if (m_cDataService.DoubleParse(txtPayAmt.Text.ToString()) < m_cDataService.DoubleParse(txtSaleAmt.Text.ToString()))
                    {
                        // 잔액교환 가능한 금액 조회
                        nExchangeAmount = DataGridSetting(3);

                        if (nExchangeAmount <= 0)
                        {
                            WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0209);
                            return sRet;
                        }

                        // 결제할 금액보다 식권금액이 큰경우 차액을 잔액교환권으로 생성한다.
                        sExchange_Ticket_Type = ItemConst.EXCHANGE_TICKET_ISSUE_TYPE.MAKE;
                        // 잔액교환권번호 = 일자 + 점코드 + posno + 시간(초+1/100초) + 발행구분(1)
                        //sExchange_Ticket_No = CmUtil.RightH(m_cPosStatus.Base.SaleDate, 4) + m_cPosStatus.Base.StoreNo.PadLeft(10, '0') + m_cPosStatus.Base.PosNo.PadLeft(2, '0') + string.Format("{0:00000}", DateTime.Now.ToString("ssfff")) + ItemConst.EXCHANGE_TICKET_MAKE_TYPE.MEAL_TICKET.PadLeft(1, '0');
                        sExchange_Ticket_No = m_cPosStatus.Base.SaleDate.PadLeft(8, '0') + m_cPosStatus.Base.PosNo.PadLeft(2, '0') + string.Format("{0:00000}", DateTime.Now.ToString("ssfff")) + ItemConst.EXCHANGE_TICKET_MAKE_TYPE.MEAL_TICKET.PadLeft(1, '0');
                        // 잔액교환 금액
                        nExchangeTicketAmt = CmUtil.DoubleSubtraction(m_cDataService.DoubleParse(txtSaleAmt.Text.ToString()), m_cDataService.DoubleParse(txtPayAmt.Text.ToString()));

                        if (nExchangeTicketAmt > 0)
                        {
                            if (nExchangeTicketAmt > nExchangeAmount)
                            {
                                // 거스름 = 잔액교환할 금액 - 잔액교환 가능한금액
                                nChangeMoney = CmUtil.DoubleSubtraction(nExchangeTicketAmt, nExchangeAmount);
                                
                                // 잔액교환권 금액 = 잔액교환 가능한 금액 
                                nExchangeTicketAmt = nExchangeAmount;
                            }
                            else
                            {
                                // 거스름 0
                                nChangeMoney = 0;
                            }

                            sRet = m_cMealTicket.SearchPayment(new string[] { m_sPosMenuKey, m_sPay_DC_Grp_Type, m_sPay_DC_CD, sExchange_Ticket_Type, sExchange_Ticket_No, nExchangeTicketAmt.ToString() }, ref aRspRet);
                            if (sRet != UserCom.RST_OK)
                            {
                                sExchange_Ticket_Type = "";
                                sExchange_Ticket_No = "";
                                nExchangeTicketAmt = 0;
                                return sRet;
                            }
                        }
                    }
                    else
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0209);
                        return sRet;
                    }
                }
                else
                {
                    // 거스름
                    nChangeMoney = 0; 

                    if (m_cDataService.DoubleParse(txtPayAmt.Text.ToString()) < m_cDataService.DoubleParse(txtSaleAmt.Text.ToString()))
                    {
                        nChangeMoney = CmUtil.DoubleSubtraction(m_cDataService.DoubleParse(txtSaleAmt.Text.ToString()), m_cDataService.DoubleParse(txtPayAmt.Text.ToString()));
                    }
                    sExchange_Ticket_Type = "";
                }

                // 결제
                for (int iLoop = 0; iLoop < dgvData.RowCount; iLoop++)
                {
                    string sMealTicketCD = dgvData.Rows[iLoop].Cells[1].Value.ToString();                                           // 코드 
                    string sMealTicketQty = m_cDataService.LongParse(dgvData.Rows[iLoop].Cells[3].Value.ToString()).ToString();   // 수량
                    string sMealTicketAmt = m_cDataService.DoubleParse(dgvData.Rows[iLoop].Cells[4].Value.ToString()).ToString();   // 금액
                    string sMealTicketNM = dgvData.Rows[iLoop].Cells[2].Value.ToString();                                           // 식권명
                    string sMealTicketType = dgvData.Rows[iLoop].Cells[5].Value.ToString();                                         // 잔액교환권 가능 여부
                    string sChangePayYN = dgvData.Rows[iLoop].Cells[6].Value.ToString();                                            // 거스름 가능 여부
                    string sNoInputYn = dgvData.Rows[iLoop].Cells[7].Value.ToString();                                              // 번호필수여부
                    string sMealTicketDiv = dgvData.Rows[iLoop].Cells[8].Value.ToString();                                          // 식권권종

                    string sChangeMoney = "0";
                    string sExchange_Ticket_No_Save = "";
                    if (m_cDataService.DoubleParse(sMealTicketAmt) >= nChangeMoney)
                    {
                        // 거스름
                        sChangeMoney = nChangeMoney.ToString();
                        nChangeMoney = 0;
                    }

                    // 잔액교환권 가능 여부
                    string sExchangeTicketAmt = "0";
                    if (sMealTicketType.ToString() == "1")
                    {
                        if (m_cDataService.DoubleParse(sMealTicketAmt) >= nExchangeTicketAmt)
                        {
                            sExchange_Ticket_No_Save = sExchange_Ticket_No;
                            sExchangeTicketAmt = nExchangeTicketAmt.ToString();
                        }
                    }

                    string sMake_Type = ItemConst.EXCHANGE_TICKET_MAKE_TYPE.NORMAL;
                    if (sExchange_Ticket_No != "")                                                                           
                        sMake_Type = ItemConst.EXCHANGE_TICKET_MAKE_TYPE.MEAL_TICKET;                                                  // 잔액교환권 발생구분

                    // 저장
                    sRet = m_cMealTicket.SetPayment(new string[] { m_sPosMenuKey, m_sPay_DC_Grp_Type, m_sPay_DC_CD, sMealTicketCD, sMealTicketQty, sMealTicketAmt, sExchange_Ticket_Type, sExchange_Ticket_No_Save, sExchangeTicketAmt, sMake_Type, sChangeMoney, sChangePayYN, sMealTicketNM, sNoInputYn, sMealTicketDiv });
                    if (sRet != UserCom.RST_OK) return sRet;

                    if (sExchange_Ticket_No.Trim() != "" && sExchangeTicketAmt != "0")
                    { 
                        // 잔액교환권 첫 식권에만 저장하고 이후는 삭제
                        sMake_Type = ItemConst.EXCHANGE_TICKET_MAKE_TYPE.NORMAL;
                        sExchange_Ticket_Type = "";
                        sExchange_Ticket_No = "";
                        nExchangeTicketAmt = 0;
                    }
                }

                // 결제 합계금액 재계산 처리
                m_cDataService.UpdatePayAmount();

                sRet = UserCom.RST_OK;

            }
            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;
        }
        #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)
        {

        }
        /// <summary>
        /// 스캐너 이벤트 처리
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnScannerEvent(object source, EventArgs e)
        {

        }

        /// <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
            {
                 
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            return sEncData;
        }

        /// <summary>
        /// IC 카드 정보 입력 처리
        /// </summary>
        /// <returns></returns>
        private bool GetIcCardData()
        {
            try
            {
 
            }
            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 그리드 설정 및 사용
        private double DataGridSetting(int iWorkMode)
        {
            try
            {
                if (iWorkMode == 0)
                {
                    // 초기화
                    dgvData.Rows.Clear();

                    dgvData.AllowUserToAddRows = false;
                    dgvData.EnableHeadersVisualStyles = false;
                    dgvData.RowsDefaultCellStyle.BackColor = Color.White;
                    dgvData.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(249, 249, 249);

                    dgvData.Font = new Font(m_cPosStatus.Base.FONT, 10);
                    dgvData.RowHeadersDefaultCellStyle.Font = new Font(m_cPosStatus.Base.FONT, 10);

                    // 타이틀 설정
                    dgvData.Columns[0].HeaderText ="No";
                    dgvData.Columns[1].HeaderText = "MEALTICKET_ID";
                    dgvData.Columns[2].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0260);
                    dgvData.Columns[3].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0017);
                    dgvData.Columns[4].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0019);
                }
                else if (iWorkMode == 1)
                {
                    // 추가

                    if (CheckTxtInPut(null) != true) return 0;

                    // 등록가능수량 체크 제거(2017.05.20)
                    //if (DataGridSetting(6) + m_cDataService.DoubleParse(txtQty.Text.Trim()) > 4)
                    //{
                    //    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0620);
                    //    return 0;
                    //}

                    int iRow = dgvData.Rows.Add();

                    dgvData.Rows[iRow].Visible = true;

                    dgvData.Rows[iRow].Cells[0].ReadOnly = false;
                    dgvData.Rows[iRow].DefaultCellStyle.ForeColor = Color.Black;
                    dgvData.Rows[iRow].DefaultCellStyle.SelectionForeColor = Color.Black;

                    dgvData.Rows[iRow].Cells[0].Value = (iRow + 1).ToString();                                                                  // No
                    dgvData.Rows[iRow].Cells[1].Value = txtCardNo.Text.Trim();                                                                  // 식권코드
                    dgvData.Rows[iRow].Cells[2].Value = txtCardNM.Text.Trim();                                                                  // 식권명칭
                    dgvData.Rows[iRow].Cells[3].Value = m_cPosStatus.Global.NumericTOCurrency(m_cDataService.LongParse(txtQty.Text.Trim()));  // 수량

                    double nSaleAmount = CmUtil.DoubleMultiplication(m_cDataService.DoubleParse(txtAmount.Text.Trim()), m_cDataService.DoubleParse(txtQty.Text.Trim()));
                    dgvData.Rows[iRow].Cells[4].Value = m_cPosStatus.Global.NumericTOCurrency(nSaleAmount);                                     // 금액
                    dgvData.Rows[iRow].Cells[5].Value = m_sMealTicketType;                                                                      // 교환권 가능여부
                    dgvData.Rows[iRow].Cells[6].Value = m_sChange_Paymnt_YN;                                                                    // 거스름 가능여부
                    dgvData.Rows[iRow].Cells[7].Value = m_sMNDTRY_INPUT_YN;                                                                           // 번호필수여부
                    dgvData.Rows[iRow].Cells[8].Value = m_sMealTicketDiv;                                                                       // 식권권종
                }
                else if (iWorkMode == 2)
                {
                    // 삭제
                    if (dgvData.RowCount <= 0) return 0;
                    if (dgvData.CurrentCell.RowIndex < 0) return 0;

                    dgvData.Rows.RemoveAt(dgvData.CurrentCell.RowIndex);


                    for (int iRow = 0; iRow < dgvData.RowCount; iRow++)
                    {
                        dgvData.Rows[iRow].Cells[0].Value = (iRow + 1).ToString();
                    }
                }
                else if (iWorkMode == 3)
                {
                    // 잔액교환권 가능 상품의 계
                    double nSumAmount = 0;

                    for (int iLoop = 0; iLoop < dgvData.RowCount; iLoop++)
                    {
                        // 잔액교환권 가능 여부 체크
                        if (dgvData.Rows[iLoop].Cells[5].Value.ToString() != "1") continue;
                        // 거스름 가능 여부 체크
                        if (dgvData.Rows[iLoop].Cells[6].Value.ToString() != "1") continue;

                        nSumAmount = CmUtil.DoubleAdd(nSumAmount, m_cDataService.DoubleParse(dgvData.Rows[iLoop].Cells[4].Value.ToString()));
                    }

                    return nSumAmount;
                }
                else if (iWorkMode == 4)
                {
                    // 식권 합계 조회
                    double nSumAmount = 0;

                    for (int iLoop = 0; iLoop < dgvData.RowCount; iLoop++)
                    {
                        nSumAmount = CmUtil.DoubleAdd(nSumAmount, m_cDataService.DoubleParse(dgvData.Rows[iLoop].Cells[4].Value.ToString()));
                    }

                    return nSumAmount;
                }
                else if (iWorkMode == 5)
                {
                    // 거스름 가능 상품의 계
                    double nSumAmount = 0;

                    for (int iLoop = 0; iLoop < dgvData.RowCount; iLoop++)
                    {
                        // 거스름 가능 여부 체크
                        if (dgvData.Rows[iLoop].Cells[6].Value.ToString() != "1") continue;

                        nSumAmount = CmUtil.DoubleAdd(nSumAmount, m_cDataService.DoubleParse(dgvData.Rows[iLoop].Cells[4].Value.ToString()));
                    }

                    return nSumAmount;
                }
                else if (iWorkMode == 6)
                {
                    // 식권 수량 조회
                    double nSumQty = 0;

                    for (int iLoop = 0; iLoop < dgvData.RowCount; iLoop++)
                    {
                        nSumQty = CmUtil.DoubleAdd(nSumQty, m_cDataService.DoubleParse(dgvData.Rows[iLoop].Cells[3].Value.ToString()));
                    }

                    return nSumQty;
                }
                dgvData.Refresh();

                txtCardNo.Text = "";
                txtCardNM.Text = "";
                txtAmount.Text = "0";
                txtQty.Text = "0";
                m_sMealTicketType = "0";
                m_sChange_Paymnt_YN = "0";
                m_sMNDTRY_INPUT_YN = "0";
                m_sMealTicketDiv = "";

                txtSaleAmt.Text = m_cPosStatus.Global.NumericTOCurrency(DataGridSetting(4));            // 식권 계

                return 0;
            }
            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 0;
        }

        #endregion


    }

}
