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 frmMultiSlectItemDc : 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 PosOLEDevice.DelegateOlePos delegatePos;

        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스
        private IDataProcessUs m_cDataService = null;
        private ISalePluItemUs m_cPluService = null;                                // 판매 등록 관리
        private IPaymentUs m_cCouponDC = 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; } }

        #endregion 변수 선언

        #region 생성자 & 소멸자 & 폼초기화
        public frmMultiSlectItemDc()
        {
            InitializeComponent();

            base.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw, true);

            m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
            m_cTrnStatus = (TranStatus)StateObject.TRAN;    // POS 거래정보 
            m_cDevStatus = (DeviceStatus)StateObject.DEVICE;

            m_cDataService = (IDataProcessUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_SERVICE);
            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
            m_cPluService = (ISalePluItemUs)sManager.InitServiceInstance(ServiceLists.BSV_SALE.DLL, ServiceLists.BSV_SALE.SALE_PLU_ITEM);

            delegatePos = new PosOLEDevice.DelegateOlePos(OnDeviceEvent);
        }

        private void frmMultiSlectItemDc_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 frmMultiSlectItemDc_Activated(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(delegatePos);
        }

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

        private void frmMultiSlectItemDc_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.Location = new Point(0,0);
                picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_800X578);
                FormManager.MovePopUpForm(this, false, m_cPosStatus.Sale.ScreenSizeUser);


                //버튼이미지 적용
                btnAllUp.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_14X9_UP2_BASIC);
                btnAllUp.ImageAlign = ContentAlignment.MiddleCenter;
                btnAllUp.BorderStyle = BorderStyle.None;
                btnAllDw.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_14X9_DOWN2_BASIC);
                btnAllDw.ImageAlign = ContentAlignment.MiddleCenter;
                btnAllDw.BorderStyle = BorderStyle.None;

                if (btnAllUp.Image != null) btnAllUp.Text = "";
                if (btnAllDw.Image != null) btnAllDw.Text = "";

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

                btnRate.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0163);
                btnAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0036);

                btnExit.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BTN_CLOSE);
                if (btnExit.Image != null) btnExit.Text = "";

                // 쿠폰할인
                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1022);

                if (m_cTrnStatus.Sale.RecvedPayAmt > 0)
                {
                    // 임의 할인 중복 등록 체크
                    WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0112);          // 결제 진행 중 처리 할 수 없는 기능 입니다
                    this.DialogResult = DialogResult.Cancel;
                    this.Close();
                    return;
                }

                lblSaleAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0374);
                lblDcType.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1021);
                lblAppAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0163);
                btnSearch.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0161);            // 할인취소
                btnEnter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0047);             // 할인적용
                btnComplete.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0248);    //2018.01.18;승인 버튼 다국어 처리;girak.kim                  

                txtAppAmt.Text = "";
                lblAppAmt.Tag = "";
                txtAppAmt.Tag = "0";
                txtSaleAmt.Text = "0";

                DcBtnDisp("1");

                //txtSaleAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cTrnStatus.Sale.RemainPayAmt);             // 받을금액

                bNotDoubleClik = false;

                LoadFuncMaster();       // 기능키 설정

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

                txtAppAmt.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 ((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) == btnSearch)             // 취소
                {
                    CompleteTxtInPut(true);
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnEnter)         // 할인
                {
                    CompleteTxtInPut(false);
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnComplete)      // 완료
                {
                    bNotDoubleClik = false;
                    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
            {
                btnMenu.ClearMenuButtonInfo();

                // 쿠폰 List 조회
                DataTable dtMemu = m_cDataCommon.SeletCouponDCFuncKey(ItemConst.TR_ITEM_ID.USER_DC_ITEM, ItemConst.TR_ITEM_ID.USER_DC.IN_EMP_DC);
                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_COUPON_DC_KEY.DATA.SEQ);                                                                 // SEQ
                    cMenuInfo.sClassCode = CmUtil.GetDataRowStr(dr, PosMst.MST_COUPON_DC_KEY.DATA.STOR_CD);                                                         // 점포코드
                    cMenuInfo.sGroupCode = "1";                                                                                                                     // SUB 그룹

                    string sMenuCode = null;
                    sMenuCode = CmUtil.RPadH(CmUtil.GetDataRowStr(dr, PosMst.MST_COUPON_DC_KEY.DATA.CPN_TYPE), 1)                                                   // 쿠폰구분
                              + CmUtil.RPadH(CmUtil.GetDataRowStr(dr, PosMst.MST_COUPON_DC_KEY.DATA.CPN_DC_CD), 40)                                                 // 쿠폰구분코드
                              + CmUtil.LPadH(CmUtil.GetDataRowStr(dr, PosMst.MST_COUPON_DC_KEY.DATA.DC_RATE), 20)                                                   // 할인율(금액)
                              + CmUtil.RPadH(CmUtil.GetDataRowStr(dr, PosMst.MST_COUPON_DC_KEY.DATA.CPN_DC_NM), 80);                                                // 쿠폰명

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

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

                    cMenuInfo.sMenuEtc = "";
                    if (CmUtil.GetDataRowStr(dr, PosMst.MST_COUPON_DC_KEY.DATA.CPN_TYPE) == "1")
                        cMenuInfo.sMenuEtc = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0982);
                    else
                        cMenuInfo.sMenuEtc = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0019);
                    cMenuInfo.cForeColorEtc = Color.Blue;
                    cMenuInfo.fFontSizeEtc = CmUtil.GetDataRowFloat(dr, PosMst.MST_COUPON_DC_KEY.DATA.FONT_SIZE);

                    cMenuInfo.cMenuImage = "";
                    btnMenu.AddMenuButtonInfo(cMenuInfo);
                }

                btnMenu.SetMenuButtonCount(4, 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)
        {
            double nSumAmount = 0;
            try
            {
                if (sMenuCode == "") return;

                // 메뉴 키 값 = 쿠폰구분(1) + 쿠폰구분코드(40) + 할인율(금액)(10) + 쿠폰명(80) 
                txtAppAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cDataService.DoubleParse(CmUtil.MidH(sMenuCode, 41, 20).Trim()));

                lblDcType.Tag = CmUtil.MidH(sMenuCode, 0, 1).Trim();
                lblAppAmt.Tag = CmUtil.MidH(sMenuCode, 1, 40).Trim();
                txtAppAmt.Tag = "0";

                DcBtnDisp(lblDcType.Tag.ToString());

                nSumAmount = 0;
                for (int iRow = 0; iRow < dgvData.Rows.Count; iRow++)
                {
                    // 지정취소 상품 skip
                    if (dgvData.Rows[iRow].Visible == false) continue;

                    if ((bool)dgvData.Rows[iRow].Cells[0].Value == true)
                    {
                        // 선택된 상품의 계
                        nSumAmount = CmUtil.DoubleAdd(nSumAmount, m_cDataService.DoubleParse(dgvData.Rows[iRow].Cells[4].Value.ToString()));
                    }
                }
                if (nSumAmount <= 0)
                {
                    txtSaleAmt.Text = "0";
                }
                else
                {
                    txtSaleAmt.Text = m_cPosStatus.Global.NumericTOCurrency(nSumAmount);
                }

                txtAppAmt.Focus();

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


                }
                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)
                {
                    btnProc_Click(btnComplete, null);
                }
            }
            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) == txtAppAmt)
                {
                    if (lblDcType.Tag == "1")
                    {
                        if ((txtAppAmt.Text.Length == 0) || (m_cDataService.DoubleParse(txtAppAmt.Text) <= 0 && m_cDataService.DoubleParse(txtAppAmt.Text) > 100))
                        {
                            WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0051);
                            txtAppAmt.Focus();
                            return false;
                        }
                    }
                    else
                    {
                        if ((txtAppAmt.Text.Length == 0) || (m_cDataService.DoubleParse(txtAppAmt.Text) <= 0))
                        {
                            WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0049);
                            txtAppAmt.Focus();
                            return false;
                        }
                    }
                }

                // 받을금액 체크
                if (sender == null || ((Cosmos.UI.CsmLabel)sender) == txtSaleAmt)
                {
                    if (m_cDataService.DoubleParse(txtSaleAmt.Text) <= 0)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0039);
                        txtSaleAmt.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 bCancelMode)
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                // 할인 처리

                if (bCancelMode)
                {
                    sRet = GetSaleItemTotalDCCancel();
                }
                else
                {
                    if (CheckTxtInPut(null) == false) return sRet;
                    sRet = GetSaleItemTotalDC(m_cDataService.DoubleParse(txtAppAmt.Value));
                }

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

                // 상품 재조회
                DataGridSetting();


            }
            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 전체상품 할인 처리
        /// <summary>
        /// 전체 상품중 할인 대상금액 조회
        /// </summary>
        /// <returns></returns>
        public double GetSaleItemDCTargerAmt()
        {
            double nDCSum = 0;

            string sRet = UserCom.RST_ERR;

            try
            {
                nDCSum = 0;

                // 상품정보
                ArrayList aSaleItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);

                for (int iRow = 0; iRow < aSaleItem.Count; iRow++)
                {
                    Column.TR_PLU.DATA cSaleItem = (Column.TR_PLU.DATA)aSaleItem[iRow];

                    if (dgvData.Rows[iRow].Visible == false) continue;
                    if ((bool)dgvData.Rows[iRow].Cells[0].Value == false) continue;

                    // 할인 대상 금액 sum
                    //nDCSum = CmUtil.DoubleAdd(CmUtil.DoubleAdd(nDCSum, cSaleItem.BILL_AMT), cSaleItem.ITEM_DC_AMT);

                    // (단가 * 수량) - 예외할인
                    double dAddAmt = CmUtil.DoubleSubtraction(cSaleItem.SALE_AMT, cSaleItem.EXCEP_DC_AMT);
                    nDCSum = CmUtil.DoubleAdd(nDCSum, dAddAmt);


                }
            }
            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 nDCSum;
        }

        /// <summary>
        ///  전체상품 할인 처리
        /// </summary>
        /// <param name="nSaleAmount"></param>
        /// <param name="nDCAvaAmount"></param>
        /// <param name="nAmount"></param>
        /// <returns></returns>
        public string GetSaleItemTotalDC(double nAmount)
        {
            double nSaleAmount = 0, nDCAvaAmount = 0;
            double nPrice = 0, nDCSum = 0, nRate = 0, nDCAmount = 0, nMaxPrice = 0;
            int iIndex = 0;

            string sRet = UserCom.RST_ERR;

            try
            {
                nDCSum = 0;
                nRate = 0;
                nDCAmount = 0;
                nMaxPrice = 0;

                // 상품정보
                ArrayList aSaleItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);

                //// 받을금액중 할인 안된 금액만 조회
                nSaleAmount = GetSaleItemDCTargerAmt();

                nDCAmount = nAmount;
                if (lblDcType.Tag.Equals("1"))
                {
                    // 분배금액 = 받을금액 * %할인 / 100
                    //nDCAmount = CmUtil.DoubleDivision(CmUtil.DoubleMultiplication(nSaleAmount, nAmount), 100);

                    nDCAmount = CmUtil.MathAmtPercent(nSaleAmount, nAmount);
                    nDCAmount = CmUtil.MathRounds(nDCAmount, m_cPosStatus.Mst.DcRudDwLocMethd, CmUtil.IntParse(m_cPosStatus.Mst.DcRudDwLoc));

                }
                if (nDCAmount <= 0)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0050);
                    return sRet;
                }
                else if (nDCAmount > nSaleAmount)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0049);
                    sRet = UserCom.RST_ERR;
                    return sRet;
                }

                // 할인 분배등록
                for (int iRow = 0; iRow < aSaleItem.Count; iRow++)
                {
                    Column.TR_PLU.DATA cSaleItem = (Column.TR_PLU.DATA)aSaleItem[iRow];
                    // 할인가능 여부 
                    if (dgvData.Rows[iRow].Visible == false) continue;
                    if ((bool)dgvData.Rows[iRow].Cells[0].Value == false) continue;

                    // 할인 절삭
                    nDCAmount = CmUtil.MathRounds(nDCAmount, m_cPosStatus.Mst.DcRudDwLocMethd, CmUtil.IntParse(m_cPosStatus.Mst.DcRudDwLoc));


                    // (단가 * 수량) - 예외할인
                    double dAddAmt = CmUtil.DoubleSubtraction(cSaleItem.SALE_AMT ,cSaleItem.EXCEP_DC_AMT);
                    
                    nPrice = CmUtil.DoubleMultiplication(nDCAmount, CmUtil.DoubleDivision(dAddAmt, nSaleAmount));
                    nPrice = CmUtil.MathRounds(nPrice, m_cPosStatus.Mst.DcRudDwLocMethd, CmUtil.IntParse(m_cPosStatus.Mst.DcRudDwLoc));
                    if (nPrice > cSaleItem.SALE_AMT) continue;                                                                                  // 할인금액이 상품금액보다 클수 없음

                    // 상품할인 적용
                    cSaleItem.ITEM_DC_AMT = nPrice;
                    cSaleItem.DC_DIV = ItemConst.PLU_DC_DIV.POS_DC;                // 쿠폰 할인 구분
                    cSaleItem.DC_TYPE = ItemConst.PLU_DC_TYPE.DC_SUM;


                    // 분배후 짜투리 금액 체크용
                    nDCSum = CmUtil.DoubleAdd(nDCSum, nPrice);

                    // 최종 적용 상품 index
                    if (nMaxPrice == 0 || nMaxPrice >= cSaleItem.SALE_AMT)
                    {
                        nMaxPrice = cSaleItem.SALE_AMT;
                        iIndex = iRow;
                    }

                    // 상품행별 영수 금액 재계산 처리
                    m_cDataService.UpdatePluItemAmount(cSaleItem);

                    if (cSaleItem.ORDER_OK_FLAG == PosConst.PLU_ORDER_OK_FLAG.ORDER_OK) cSaleItem.ORDER_OK_FLAG = PosConst.PLU_ORDER_OK_FLAG.ORDER_MOD;
                }

                // 짜투리 금액 최종 적용 상품에 추가
                if (nDCSum != nDCAmount)
                {
                    Column.TR_PLU.DATA cSaleItem = (Column.TR_PLU.DATA)aSaleItem[iIndex];

                    cSaleItem.ITEM_DC_AMT = CmUtil.DoubleAdd(cSaleItem.ITEM_DC_AMT, CmUtil.DoubleSubtraction(nDCAmount, nDCSum));

                    // 상품행별 영수 금액 재계산 처리
                    m_cDataService.UpdatePluItemAmount(cSaleItem);
                }

                // 상품 판매가 계산
                //m_cPluService.ItemAmountExeccute(true, true);

                // 할인금액
                txtAppAmt.Tag = nDCAmount.ToString();

                // 결제 합계금액 재계산 처리
                //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;
        }

        /// <summary>
        /// 전체상품 할인 취소 처리
        /// </summary>
        /// <returns></returns>
        public string GetSaleItemTotalDCCancel()
        {
            string sRet = UserCom.RST_ERR;

            try
            {


                if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0684) == true)
                {
                    // ---------------------------------------------------------------------------------------------------------------------------------------
                    // 상품정보
                    // ---------------------------------------------------------------------------------------------------------------------------------------
                    ArrayList aSaleItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);

                    for (int iRow = 0; iRow < aSaleItem.Count; iRow++)
                    {
                        Column.TR_PLU.DATA cSaleItem = (Column.TR_PLU.DATA)aSaleItem[iRow];


                        if (cSaleItem.CANCEL_DIV == PosConst.CANCEL_DIV.CANCEL || cSaleItem.CANCEL_DIV_MAIN == PosConst.CANCEL_DIV.CANCEL) continue;// 지정취소
                        if (dgvData.Rows[iRow].Visible == false) continue;

                        if (cSaleItem.ITEM_DC_AMT > 0 || cSaleItem.DC_TYPE == "1")
                        {
                            // 상품할인 적용
                            cSaleItem.DC_TYPE = ItemConst.PLU_DC_TYPE.NORMAL;
                            cSaleItem.ITEM_DC_AMT = 0;
                            cSaleItem.DC_DIV = ItemConst.PLU_DC_DIV.NORMAL;
                            m_cDataService.UpdatePluItemAmount(cSaleItem);

                            if (cSaleItem.ORDER_OK_FLAG == PosConst.PLU_ORDER_OK_FLAG.ORDER_OK) cSaleItem.ORDER_OK_FLAG = PosConst.PLU_ORDER_OK_FLAG.ORDER_MOD;
                        }
                    }

                    // 상품 판매가 계산
                    //m_cPluService.ItemAmountExeccute(true, true);

                    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 할인 가능 여부 체크

        /// <summary>
        /// 할인 가능 여부 체크
        /// </summary>
        /// <returns></returns>
        private string CheckDCUseMode()
        {
            string sRet = UserCom.RST_OK;

            try
            {
                if (m_cTrnStatus.Sale.RecvedPayAmt > 0)
                {
                    // 임의 할인 중복 등록 체크
                    WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0112);          // 결제 진행 중 처리 할 수 없는 기능 입니다
                    sRet = UserCom.ERROR;
                    return sRet;
                }

                // 상품정보
                ArrayList aSaleItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);
                for (int iRow = 0; iRow < aSaleItem.Count; iRow++)
                {
                    Column.TR_PLU.DATA cSaleItem = (Column.TR_PLU.DATA)aSaleItem[iRow];
                    if (cSaleItem.CANCEL_DIV == PosConst.CANCEL_DIV.CANCEL || cSaleItem.CANCEL_DIV_MAIN == PosConst.CANCEL_DIV.CANCEL) continue;// 지정취소

                    if (cSaleItem.ITEM_DC_AMT > 0)
                    {
                        sRet = UserCom.RST_IGNORE;
                    }
                }
            }
            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)
        {

        }
        #endregion

        #region 그리드 설정 및 사용
        private void DataGridSetting()
        {
            string sRate = "";
            int iRowNum = 0;
            double nRate = 0;

            try
            {
                dgvData.Rows.Clear();

                dgvData.AllowUserToAddRows = false;
                dgvData.EnableHeadersVisualStyles = false;
                dgvData.RowsDefaultCellStyle.BackColor = Color.White;
                dgvData.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(249, 249, 249);
                dgvData.Font = this.Font;
                dgvData.DefaultCellStyle.Font = new Font(m_cPosStatus.Base.FONT, 9);

                dgvData.Font = new Font(m_cPosStatus.Base.FONT, 9);
                dgvData.RowHeadersDefaultCellStyle.Font = new Font(m_cPosStatus.Base.FONT, 9, FontStyle.Regular);

                // 타이틀 설정
                dgvData.Columns[0].HeaderText = "V";
                dgvData.Columns[1].HeaderText = "ITEMCD";
                dgvData.Columns[2].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0015);
                dgvData.Columns[3].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0017);
                dgvData.Columns[4].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0019);
                dgvData.Columns[5].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0036);
                dgvData.Columns[6].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1023);

                // 상품정보
                ArrayList aSaleItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);

                for (int iLoop = 0; iLoop < aSaleItem.Count; iLoop++)
                {
                    Column.TR_PLU.DATA cSaleItem = (Column.TR_PLU.DATA)aSaleItem[iLoop];

                    int iRow = dgvData.Rows.Add();


                    if (cSaleItem.CANCEL_DIV == PosConst.CANCEL_DIV.CANCEL || cSaleItem.CANCEL_DIV_MAIN == PosConst.CANCEL_DIV.CANCEL
                        || cSaleItem.DC_DIV == ItemConst.PLU_DC_DIV.FREE || cSaleItem.ITEM_DIV != ItemConst.PLU_ITEM_DIV.NORMAL
                        || cSaleItem.NONSALES_RSN_CD != "0" || cSaleItem.BILLSPR_NO != m_cTrnStatus.Sale.BillSplitNo
                        || CmUtil.DoubleSubtraction(cSaleItem.SALE_AMT ,cSaleItem.EXCEP_DC_AMT) < 0 
                        || cSaleItem.DC_PRMT_YN != "0" || cSaleItem.SET_DC_GROUP_CD > 0)
                    //if (cSaleItem.CANCEL_DIV == PosConst.CANCEL_DIV.CANCEL || cSaleItem.CANCEL_DIV_MAIN == PosConst.CANCEL_DIV.CANCEL
                    //    || cSaleItem.DC_PRMT_YN == "1" || cSaleItem.DC_DIV == ItemConst.PLU_DC_DIV.FREE || cSaleItem.SET_DC_GROUP_CD > 0)
                    {
                        dgvData.Rows[iRow].Visible = false;
                        continue;// 지정취소
                    }
                    else
                    {
                        dgvData.Rows[iRow].Visible = true;
                    }

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

                    dgvData.Rows[iRow].HeaderCell.Value = (++iRowNum).ToString();

                    dgvData.Rows[iRow].Cells[0].Value = false;                                                              // 선택
                    dgvData.Rows[iRow].Cells[1].Value = cSaleItem.ITEM_PLU_CD.ToString();                                   // 상품코드
                    dgvData.Rows[iRow].Cells[2].Value = cSaleItem.ITEM_NAME.ToString();                                     // 상품명
                    dgvData.Rows[iRow].Cells[3].Value = m_cPosStatus.Global.NumericTOCurrency(cSaleItem.SALE_QTY);          // 수량
                    dgvData.Rows[iRow].Cells[4].Value = m_cPosStatus.Global.NumericTOCurrency(CmUtil.DoubleSubtraction(cSaleItem.SALE_AMT , CmUtil.DoubleAdd(cSaleItem.ITEM_DC_AMT,cSaleItem.EXCEP_DC_AMT)));          // 금액
                    dgvData.Rows[iRow].Cells[5].Value = m_cPosStatus.Global.NumericTOCurrency(cSaleItem.ITEM_DC_AMT);       // 할인금액
                    dgvData.Rows[iRow].Cells[6].Value = m_cPosStatus.Global.NumericTOCurrency(cSaleItem.EXCEP_DC_AMT);      // 기타할인
                }
                dgvData.Refresh();

                txtAppAmt.Text = "";
                lblAppAmt.Tag = "";
                txtAppAmt.Tag = "0";
                txtSaleAmt.Text = "0";
                //txtSaleAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cDataService.GetPluTagetAmount(m_sPosMenuKey));   // 받을 금액
            }
            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 dgvPluItem_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            double nSumAmount = 0;
            try
            {
                if (dgvData.CurrentCell != null)
                {
                    if (e.RowIndex == -1)
                    {
                        ////////////////////////////////////////////////////////////
                        // 헤더 클릭하여 전체 체크 최초 플래그 체크(반전)
                        bool bisChecked = false;

                        for (int iRow = 0; iRow < dgvData.Rows.Count; iRow++)
                        {
                            // 지정취소 상품 skip
                            if (dgvData.Rows[iRow].Visible == false) continue;

                            // 헤더 클릭하여 전체 체크
                            bisChecked = !(bool)dgvData.Rows[iRow].Cells[0].Value;
                            break;
                        }
                        ////////////////////////////////////////////////////////////

                        dgvData.ClearSelection();
                        dgvData.CurrentCell = null;

                        int iMinRow = 0;

                        for (int iRow = 0; iRow < dgvData.Rows.Count; iRow++)
                        {
                            // 지정취소 상품 skip
                            if (dgvData.Rows[iRow].Visible == false) continue;

                            dgvData.Rows[iRow].Cells[0].Value = bisChecked;

                            if (iMinRow == 0) iMinRow = iRow;

                        }

                        dgvData.Rows[iMinRow].Selected = true;
                        dgvData.Rows[iMinRow].Cells[0].Selected = true;
                        
                    }
                    else
                    {
                        // 지정취소 상품 skip
                        if (dgvData.Rows[e.RowIndex].Visible == false) return;

                        bool bisChecked = !(bool)dgvData.Rows[e.RowIndex].Cells[0].Value;
                        dgvData.Rows[e.RowIndex].Cells[0].Value = bisChecked;
                    }

                    nSumAmount = 0;
                    for (int iRow = 0; iRow < dgvData.Rows.Count; iRow++)
                    {
                        // 지정취소 상품 skip
                        if (dgvData.Rows[iRow].Visible == false) continue;

                        if ((bool)dgvData.Rows[iRow].Cells[0].Value == true)
                        {

                            double dSale = m_cDataService.DoubleParse(dgvData.Rows[iRow].Cells[4].Value.ToString());
                            double dDc = m_cDataService.DoubleParse(dgvData.Rows[iRow].Cells[5].Value.ToString());

                            // 선택된 상품의 계
                            nSumAmount = CmUtil.DoubleAdd(CmUtil.DoubleAdd(nSumAmount, dSale), dDc);
                        }
                    }
                    txtSaleAmt.Text = m_cPosStatus.Global.NumericTOCurrency(nSumAmount);

                }

                txtAppAmt.Focus();

            }
            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

        private void btnDcType_Click(object sender, EventArgs e)
        {
            try
            {
                if (((Cosmos.UI.CsmButton)sender) == btnRate)
                {
                    DcBtnDisp("1");
                }
                else
                {
                    DcBtnDisp("2");
                }
            }
            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 DcBtnDisp(string sType)
        {
            try
            {
                if (sType != "") lblDcType.Tag = sType;

                if (lblDcType.Tag.Equals("1"))
                {
                    lblAppAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0163);
                    btnRate.BackColor = Color.FromArgb(22, 187, 238);
                    btnAmt.BackColor = Color.FromArgb(153, 153, 153);
                }
                else
                {
                    lblAppAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0036);
                    btnAmt.BackColor = Color.FromArgb(22, 187, 238);
                    btnRate.BackColor = Color.FromArgb(153, 153, 153);
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                       System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }


    }

}
