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 frmDutchPay : Form
    {

        #region Variable

        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 IICReaderUs m_cDeviceICReader = null;
        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스
        private IDataProcessUs m_cDataService = null;
        private ISalePluItemUs m_cPluService = 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 string m_sPaying = "0";
        public string Paying { set { m_sPaying = value; } }    //결제 진행중


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

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


        /// <summary>
        /// 등록 상품 리스트 데이터
        /// </summary>
        private DataTable m_dtcglAlliTem;
        /// <summary>
        /// 선택 상품 리스트 데이터
        /// </summary>
        private DataTable m_dtcglBundleiTem;

        #endregion Variable

        #region 생성자 & 소멸자 & 폼초기화
        /// <summary>
        /// 생성자
        /// </summary>
        public frmDutchPay()
        {
            InitializeComponent();

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

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

            m_cDataService = (IDataProcessUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_SERVICE);
            m_cDeviceICReader = (IICReaderUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_ICREADER);
            m_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 frmDutchPay_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 frmDutchPay_Activated(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(delegatePos);
        }

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

        private void frmDutchPay_FormClosing(object sender, FormClosingEventArgs e)
        {
            m_sPaying = "0";

            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, 544);
                //this.Location = new Point(110, 173);
                picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_800X600);

                FormManager.SetFormAllControlFont(this, m_cPosStatus.Base.FONT);
                FormManager.SetTextBoxGlobalInfo(this, m_cPosStatus.Global.m_stCultureMaster.nGroupingDigits, m_cPosStatus.Global.m_stCultureMaster.strGroupingSymbol
                    , m_cPosStatus.Global.m_stCultureMaster.nDecimalDigits, m_cPosStatus.Global.m_stCultureMaster.strDecimalSymbol);

                btnExit.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BTN_CLOSE);
                if (btnExit.Image != null) btnExit.Text = "";
                
                btnAllUp.DefaultImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_170X48_UP1_BASIC);
                btnAllUp.ClickImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_170X48_UP1_PRESS);
                btnAllUp.BorderStyle = BorderStyle.None;
                if (btnAllUp.DefaultImage != null) btnAllUp.Text = "";

                btnAllDw.DefaultImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_170X48_DOWN1_BASIC);
                btnAllDw.ClickImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_170X48_DOWN1_PRESS);
                btnAllDw.BorderStyle = BorderStyle.None;
                if (btnAllDw.DefaultImage != null) btnAllDw.Text = "";

                btnBudleUp.DefaultImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_170X48_UP1_BASIC);
                btnBudleUp.ClickImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_170X48_UP1_PRESS);
                btnBudleUp.BorderStyle = BorderStyle.None;
                if (btnBudleUp.DefaultImage != null) btnBudleUp.Text = "";

                btnBudleDw.DefaultImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_170X48_UP1_BASIC);
                btnBudleDw.ClickImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_170X48_UP1_PRESS);
                btnBudleDw.BorderStyle = BorderStyle.None;
                if (btnBudleDw.DefaultImage != null) btnBudleDw.Text = "";


                btnAddOne.DefaultImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BUTTON_RIGHT_ARROW_BASIC);
                btnAddOne.ClickImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BUTTON_RIGHT_ARROW_PRESS);
                btnAddOne.BorderStyle = BorderStyle.None;
                if (btnAddOne.DefaultImage != null) btnAddOne.Text = "";

                btnDelOne.DefaultImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BUTTON_LEFT_ARROW_BASIC);
                btnDelOne.ClickImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BUTTON_LEFT_ARROW_PRESS);
                btnDelOne.BorderStyle = BorderStyle.None;
                if (btnDelOne.DefaultImage != null) btnDelOne.Text = "";

                btnAddAll.DefaultImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BUTTON_RIGHT_ALL_ARROW_BASIC);
                btnAddAll.ClickImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BUTTON_RIGHT_ALL_ARROW_PRESS);
                btnAddAll.BorderStyle = BorderStyle.None;
                if (btnAddAll.DefaultImage != null) btnAddAll.Text = "";

                btnDelAll.DefaultImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BUTTON_LEFT_ALL_ARROW_BASIC);
                btnDelAll.ClickImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BUTTON_LEFT_ALL_ARROW_PRESS);
                btnDelAll.BorderStyle = BorderStyle.None;
                if (btnDelAll.DefaultImage != null) btnDelAll.Text = "";


                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0438);

                lblPayAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0374);                        // 선택금액
                lblSaleAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0348);                       // 판매금액

                txtSaleAmt.Text = "0";
                txtPayAmt.Text = "0";

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

                DataGridSetting(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);
            }
        }
        #endregion

        #region Control Event

        #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
                {
                    cglAlliTem.CsmGridScroll("UP");
                }
                else if ((UI.CsmButton)sender == btnAllDw)                          // 상단 그리드 Down
                {
                    cglAlliTem.CsmGridScroll("DOWN");
                }
                else if ((UI.CsmButton)sender == btnBudleUp)                        // 하단 그리드 Up
                {
                    cgdBundleiTem.CsmGridScroll("UP");
                }
                else if ((UI.CsmButton)sender == btnBudleDw)                        // 하단 그리드 Down
                {
                    cgdBundleiTem.CsmGridScroll("DOWN");
                }

                else if (((Cosmos.UI.CsmButton)sender) == btnDelAll)                // 전체 삭제
                {
                    sRet = DataGridSetting(3);

                    bNotDoubleClik = false;
                    if (sRet != UserCom.RST_OK) return;
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnAddAll)                // 전체 이동
                {
                    sRet = DataGridSetting(1);
                    
                    bNotDoubleClik = false;
                    if (sRet != UserCom.RST_OK) return;
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnAddOne)                // 1개 이동
                {
                    //할인 체크
                    sRet = DcAmtCheck(cglAlliTem);

                    if (sRet == UserCom.RST_OK)
                    {
                        sRet = DataGridSetting(2);
                    }
                    else if (sRet == UserCom.RST_RETRY)
                    {
                        if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0681) == true)
                        {
                            sRet = DataGridSetting(1);
                        }
                    }


                    bNotDoubleClik = false;
                    if (sRet != UserCom.RST_OK) return;
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnDelOne)                // 1개 삭제
                {

                    //할인 체크
                    sRet = DcAmtCheck(cgdBundleiTem);

                    if (sRet == UserCom.RST_OK)
                    {
                        sRet = DataGridSetting(4);
                    }
                    else if (sRet == UserCom.RST_RETRY)
                    {
                        if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0681) == true)
                        {
                            sRet = DataGridSetting(3);
                        }
                    }
                    
                    //sRet = DataGridSetting(4);
                    bNotDoubleClik = false;

                    if (sRet != UserCom.RST_OK) return;
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnPay)              // 결제
                {

                    if (cgdBundleiTem.CsmGridRowsCount == 0)
                    {
                        bNotDoubleClik = false;
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0396);
                        //메세지
                        return;
                    }

                    sRet = SetPay();

                    bNotDoubleClik = false;
                    if (sRet != UserCom.RST_OK) return;
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                    //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);
                bNotDoubleClik = false;
            }

            bNotDoubleClik = false;
        }

        /// <summary>
        /// 닫기
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            try
            {
                // 진행중이고 후불이면 못나가게 임시로 막음!
                if (m_sPaying == "1" && m_cPosStatus.Base.PosType == PosConst.POS_TYPE.DEFERRED_PAYMENT)
                {
                    WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0284));
                    return;
                }

                //더치페이 관련 함수들 초기화!
                m_cPosStatus.Sale.DutchPayFlg = "";
                m_cTrnStatus.Head.AmtDutchPayYn = "";
                m_cPosStatus.Sale.PayingDutchFlag = "";

                this.DialogResult = DialogResult.Cancel;
                this.Close();
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion

        #endregion Control Event

        #region User Method

        #region 그리드 설정 및 사용
        private string DataGridSetting(int index)
        {
            string sRet = UserCom.RST_ERR;

            try
            {
                switch (index)
                {
                    case 0:
                        {
                            // ------------------------------------------------------------------------------------------------------------------------
                            // 상단 그리드
                            // ------------------------------------------------------------------------------------------------------------------------
                            // 초기화
                            cglAlliTem.CsmGridColumnHeadersFont = new Font(m_cPosStatus.Base.FONT, 10, cglAlliTem.CsmGridColumnHeadersFont.Style);


                            cglAlliTem.CsmGridColumnHeadersVisible = true;                                      //DataGridView 자체의 컬럼 헤더 Visible 여부
                            cglAlliTem.CsmGridColumnHeadersHeight  = 37;                                        //DataGridView 자체의 컬럼 헤더 높이
                            cglAlliTem.CsmGridRowsHeight           = 35;
                            cglAlliTem.CsmGridColumnCount          = 11;                                        //그리드의 컬럼 수
                            cglAlliTem.CsmGridShowPageRowsCount    = 9;                                         //그리드의 한 화면에 보이는 로우수
                            cglAlliTem.CsmGridSetHeaderBackColor(236, 238, 239);                                //그리드 헤더 배경색
                            cglAlliTem.CsmGridDefaultRowBackColor   = Color.FromArgb(255, 255, 255);            //그리드 홀수(Default)행의 배경색 지정
                            cglAlliTem.CsmGridAlternateRowBackColor = Color.FromArgb(251, 253, 255);            //그리드 짝수(Alternate)행의 배경색 지정
                            cglAlliTem.CsmGridBackGroundColor       = Color.FromArgb(251, 253, 255);            //기본 백그라운드 컬러
                            cglAlliTem.CsmGridHighlightColor        = Color.FromArgb(255, 251, 211);            //그리드 선택 백 컬러
                            cglAlliTem.CsmGridHighlightTextColor    = Color.Black;                              //그리드 선택 글자 컬러

                            //각 컬럼별 이름 지정
                            cglAlliTem.CsmGridColumnName(0, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0014));
                            cglAlliTem.CsmGridColumnName(1, "");
                            cglAlliTem.CsmGridColumnName(2, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0015));
                            cglAlliTem.CsmGridColumnName(3, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0017));
                            cglAlliTem.CsmGridColumnName(4, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0348));
                            cglAlliTem.CsmGridColumnShowHide(5, false);
                            cglAlliTem.CsmGridColumnShowHide(6, false);
                            cglAlliTem.CsmGridColumnShowHide(7, false);
                            cglAlliTem.CsmGridColumnShowHide(8, false);
                            cglAlliTem.CsmGridColumnShowHide(9, false);
                            cglAlliTem.CsmGridColumnShowHide(10, false);

                            //컬럼넓이 지정(406)
                            cglAlliTem.CsmGridSetColumnWidth(new int[] { 42, 0, 140, 58, 100, 0, 0, 0, 0, 0, 0 });

                            //컬럼 정렬 0:왼쪽, 1:가운데, 2:오른쪽
                            cglAlliTem.CsmGridAlignment(new int[] { 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2 });

                            m_dtcglAlliTem = new DataTable("GRID_LIST");
                            m_dtcglAlliTem.Columns.Add(new DataColumn("NO", typeof(string)));
                            m_dtcglAlliTem.Columns.Add(new DataColumn("ITEMCD", typeof(string)));
                            m_dtcglAlliTem.Columns.Add(new DataColumn("ITEMNM", typeof(string)));
                            m_dtcglAlliTem.Columns.Add(new DataColumn("QTY", typeof(string)));
                            m_dtcglAlliTem.Columns.Add(new DataColumn("AMOUNT", typeof(string)));
                            m_dtcglAlliTem.Columns.Add(new DataColumn("ITEM_DIV", typeof(string)));
                            m_dtcglAlliTem.Columns.Add(new DataColumn("DC_PRMT_YN", typeof(string)));
                            m_dtcglAlliTem.Columns.Add(new DataColumn("COST", typeof(string)));
                            m_dtcglAlliTem.Columns.Add(new DataColumn("SEQ", typeof(string)));
                            m_dtcglAlliTem.Columns.Add(new DataColumn("UPDATE", typeof(string)));
                            m_dtcglAlliTem.Columns.Add(new DataColumn("TOT_DC_AMT", typeof(string)));
                            m_dtcglAlliTem.Clear();
                            // ------------------------------------------------------------------------------------------------------------------------

                            // ------------------------------------------------------------------------------------------------------------------------
                            // 하단 그리드
                            // ------------------------------------------------------------------------------------------------------------------------
                            // 초기화
                            cgdBundleiTem.CsmGridColumnHeadersFont = new Font(m_cPosStatus.Base.FONT, 10, cgdBundleiTem.CsmGridColumnHeadersFont.Style);

                            //DataGridView 자체의 컬럼 헤더 Visible 여부
                            cgdBundleiTem.CsmGridColumnHeadersVisible = true;
                            //DataGridView 자체의 컬럼 헤더 높이
                            cgdBundleiTem.CsmGridColumnHeadersHeight = 37;
                            cgdBundleiTem.CsmGridRowsHeight = 35;

                            //그리드의 컬럼 수
                            cgdBundleiTem.CsmGridColumnCount = 11;
                            //그리드의 한 화면에 보이는 로우수
                            cgdBundleiTem.CsmGridShowPageRowsCount = 9;

                            //그리드 홀수(Default)/짝수(Alternate)행의 배경색 지정
                            cgdBundleiTem.CsmGridDefaultRowBackColor = Color.White;
                            cgdBundleiTem.CsmGridAlternateRowBackColor = Color.Ivory;

                            //각 컬럼별 이름 지정
                            cgdBundleiTem.CsmGridColumnName(0, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0014));
                            cgdBundleiTem.CsmGridColumnName(1, "");
                            cgdBundleiTem.CsmGridColumnName(2, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0015));
                            cgdBundleiTem.CsmGridColumnName(3, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0017));
                            cgdBundleiTem.CsmGridColumnName(4, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0348));
                            cgdBundleiTem.CsmGridColumnShowHide(5, false);
                            cgdBundleiTem.CsmGridColumnShowHide(6, false);
                            cgdBundleiTem.CsmGridColumnShowHide(7, false);
                            cgdBundleiTem.CsmGridColumnShowHide(8, false);
                            cgdBundleiTem.CsmGridColumnShowHide(9, false);
                            cgdBundleiTem.CsmGridColumnShowHide(10, false);

                            //컬럼넓이 지정(406)

                            cgdBundleiTem.CsmGridSetColumnWidth(new int[] { 42, 0, 140, 58, 100, 0, 0, 0, 0, 0, 0 });

                            //컬럼 정렬 0:왼쪽, 1:가운데, 2:오른쪽
                            cgdBundleiTem.CsmGridAlignment(new int[] { 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2 });

                            m_dtcglBundleiTem = new DataTable("GRID_BUNDLE_LIST");
                            m_dtcglBundleiTem.Columns.Add(new DataColumn("NO", typeof(string)));
                            m_dtcglBundleiTem.Columns.Add(new DataColumn("ITEMCD", typeof(string)));
                            m_dtcglBundleiTem.Columns.Add(new DataColumn("ITEMNM", typeof(string)));
                            m_dtcglBundleiTem.Columns.Add(new DataColumn("QTY", typeof(string)));
                            m_dtcglBundleiTem.Columns.Add(new DataColumn("AMOUNT", typeof(string)));
                            m_dtcglBundleiTem.Columns.Add(new DataColumn("ITEM_DIV", typeof(string)));
                            m_dtcglBundleiTem.Columns.Add(new DataColumn("DC_PRMT_YN", typeof(string)));
                            m_dtcglBundleiTem.Columns.Add(new DataColumn("COST", typeof(string)));
                            m_dtcglBundleiTem.Columns.Add(new DataColumn("SEQ", typeof(string)));
                            m_dtcglBundleiTem.Columns.Add(new DataColumn("UPDATE", typeof(string)));
                            m_dtcglBundleiTem.Columns.Add(new DataColumn("TOT_DC_AMT", typeof(string)));
                            m_dtcglBundleiTem.Clear();


                            cgdBundleiTem.CsmGridDataSource = m_dtcglBundleiTem;



                            // ------------------------------------------------------------------------------------------------------------------------

                            // ------------------------------------------------------------------------------------------------------------------------
                            // 상품정보
                            // ------------------------------------------------------------------------------------------------------------------------
                            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];

                                if (cSaleItem.CANCEL_DIV != PosConst.CANCEL_DIV.NORMAL || cSaleItem.CANCEL_DIV_MAIN != PosConst.CANCEL_DIV.NORMAL) continue;    // 지정취소

                                DataRow drNewRow = m_dtcglAlliTem.NewRow();


                                //if (m_sPaying == "1")
                                //{
                                //    //결제 진행 중일 경우 TOT_QTY에서 현재 수량을 빼서 수량을 만들어준다.

                                //    cSaleItem.SALE_QTY = cSaleItem.DUTCH_PAY_TOTQTY - cSaleItem.SALE_QTY;
                                //}
                                //else
                                //{
                                cSaleItem.DUTCH_PAY_TOTQTY = cSaleItem.SALE_QTY;
                                //}

                                cSaleItem.DUTCH_PAY_SELQTY = 0;


                                if (cSaleItem.ITEM_DIV == ItemConst.PLU_ITEM_DIV.OPT_MENU || cSaleItem.ITEM_DIV == ItemConst.PLU_ITEM_DIV.SET_DETL)
                                {
                                    drNewRow["NO"] = "";
                                }
                                else
                                {
                                    drNewRow["NO"] = SelectMaxNo(m_dtcglAlliTem).ToString();
                                }
                                drNewRow["ITEMCD"] = cSaleItem.ITEM_PLU_CD;                                                 // 상품코드
                                drNewRow["ITEMNM"] = cSaleItem.ITEM_NAME;                                                   // 상품명
                                drNewRow["QTY"] = m_cPosStatus.Global.NumericToQuantity(cSaleItem.SALE_QTY);                // 수량
                                drNewRow["AMOUNT"] = m_cPosStatus.Global.NumericTOCurrency(cSaleItem.BILL_AMT);             // 판매금액
                                drNewRow["ITEM_DIV"] = cSaleItem.ITEM_DIV;                                                  // 부가상품
                                drNewRow["DC_PRMT_YN"] = cSaleItem.DC_PRMT_YN;                                              // 할인불가
                                drNewRow["COST"] = cSaleItem.SALE_PRC;                                                      // 단가
                                drNewRow["SEQ"] = iLoop;                                                                    // Seq
                                drNewRow["UPDATE"] = "";                                                                    // 변경구분
                                drNewRow["TOT_DC_AMT"] = cSaleItem.TOT_DC_AMT;                                              // 할인금액

                                m_dtcglAlliTem.Rows.Add(drNewRow);
                            }

                            cglAlliTem.CsmGridDataSource = m_dtcglAlliTem;
                            cglAlliTem.CsmGridSelectRow(0);
                            // ------------------------------------------------------------------------------------------------------------------------

                            break;
                        }
                    case 1:
                        {
                            // 추가(수량전체)
                            int iRow = cglAlliTem.CsmGridSelectedRowIndex;

                            if (cglAlliTem.CsmGridRowsCount <= 0) break;
                            if (m_dtcglAlliTem.Rows[iRow]["ITEM_DIV"].ToString() == ItemConst.PLU_ITEM_DIV.OPT_MENU || m_dtcglAlliTem.Rows[iRow]["ITEM_DIV"].ToString() == ItemConst.PLU_ITEM_DIV.SET_DETL) break;

                            sRet = GridDataSet(cglAlliTem, m_dtcglAlliTem, cgdBundleiTem, m_dtcglBundleiTem, true, iRow, false);
                            if (sRet != UserCom.RST_OK) return sRet;

                            break;
                        }
                    case 2:
                        {
                            // 추가(수량1개)
                            int iRow = cglAlliTem.CsmGridSelectedRowIndex;

                            if (cglAlliTem.CsmGridRowsCount <= 0) break;
                            if (m_dtcglAlliTem.Rows[iRow]["ITEM_DIV"].ToString() == ItemConst.PLU_ITEM_DIV.OPT_MENU || m_dtcglAlliTem.Rows[iRow]["ITEM_DIV"].ToString() == ItemConst.PLU_ITEM_DIV.SET_DETL) break;

                            sRet = GridDataSet(cglAlliTem, m_dtcglAlliTem, cgdBundleiTem, m_dtcglBundleiTem, false, iRow, false);
                            if (sRet != UserCom.RST_OK) return sRet;

                            break;
                        }
                    case 3:
                        {
                            // 취소(전체)
                            int iRow = cgdBundleiTem.CsmGridSelectedRowIndex;

                            if (cgdBundleiTem.CsmGridRowsCount <= 0) break;
                            if (m_dtcglBundleiTem.Rows[iRow]["ITEM_DIV"].ToString() == ItemConst.PLU_ITEM_DIV.OPT_MENU || m_dtcglBundleiTem.Rows[iRow]["ITEM_DIV"].ToString() == ItemConst.PLU_ITEM_DIV.SET_DETL) break;

                            sRet = GridDataSet(cgdBundleiTem, m_dtcglBundleiTem, cglAlliTem, m_dtcglAlliTem, true, iRow, true);
                            if (sRet != UserCom.RST_OK) return sRet;

                            break;
                        }
                    case 4:
                        {
                            //취소(1개)
                            int iRow = cgdBundleiTem.CsmGridSelectedRowIndex;

                            if (cgdBundleiTem.CsmGridRowsCount <= 0) break;
                            if (m_dtcglBundleiTem.Rows[iRow]["ITEM_DIV"].ToString() == ItemConst.PLU_ITEM_DIV.OPT_MENU || m_dtcglBundleiTem.Rows[iRow]["ITEM_DIV"].ToString() == ItemConst.PLU_ITEM_DIV.SET_DETL) break;

                            sRet = GridDataSet(cgdBundleiTem, m_dtcglBundleiTem, cglAlliTem, m_dtcglAlliTem, false, iRow, true);
                            if (sRet != UserCom.RST_OK) return sRet;


                            break;
                        }

                }

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

                sRet = UserCom.RST_ERR;
            }

            return sRet;
        }

        /// <summary>
        /// 그리드 No 최대값 조회
        /// </summary>
        /// <param name="dtData"></param>
        /// <returns></returns>
        private string SelectMaxNo(DataTable dtData)
        {
            double nGetData = 0;
            double nMaxNo = 0;
            string sRet = "";
            try
            {
                if (dtData.Rows.Count <= 0) sRet = "1";

                for (int iLoop = 0; iLoop < dtData.Rows.Count; iLoop++)
                {
                    DataRow dvDataRow = dtData.Rows[iLoop];
                    if (dvDataRow["ITEM_DIV"].ToString() == ItemConst.PLU_ITEM_DIV.OPT_MENU || dvDataRow["ITEM_DIV"].ToString() == ItemConst.PLU_ITEM_DIV.SET_DETL) continue;

                    nGetData = m_cDataService.DoubleParse(dvDataRow["NO"].ToString());

                    if (nGetData > nMaxNo)
                    {
                        nMaxNo = nGetData;

                        sRet = (nMaxNo + 1).ToString();
                    }
                }
            }
            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>
        /// 그리드 특정 Row 추가/삭제
        /// </summary>
        /// <param name="cdgSrc"></param>
        /// <param name="dtSrc"></param>
        /// <param name="cdgTaget"></param>
        /// <param name="dtTarget"></param>
        /// <param name="AllMove"></param>
        /// <param name="iRow"></param>
        /// <param name="bDelete"></param>
        /// <returns></returns>
        private string GridDataSet(Cosmos.UI.CsmGrid cdgSrc, DataTable dtSrc, Cosmos.UI.CsmGrid cdgTaget, DataTable dtTarget, bool AllMove, int iRow, bool bDelete)
        {
            string sRet = UserCom.RST_ERR;
            double nPayAmount = 0;

            try
            {
                if (cdgSrc.CsmGridRowsCount <= 0) return sRet;

                // 코드 체크
                if (cdgSrc.CsmGridGetCell(iRow, 1).ToString().Trim() == "") return sRet;

                DataRow drNewRow = dtTarget.NewRow();

                if (cdgSrc.CsmGridGetCell(iRow, 5) == ItemConst.PLU_ITEM_DIV.OPT_MENU || cdgSrc.CsmGridGetCell(iRow, 5) == ItemConst.PLU_ITEM_DIV.SET_DETL)
                {
                    drNewRow["NO"] = "";
                }
                else
                {
                    drNewRow["NO"] = SelectMaxNo(dtTarget).ToString();
                }
                drNewRow["ITEMCD"] = cdgSrc.CsmGridGetCell(iRow, 1);
                drNewRow["ITEMNM"] = cdgSrc.CsmGridGetCell(iRow, 2);
                drNewRow["ITEM_DIV"] = cdgSrc.CsmGridGetCell(iRow, 5);
                drNewRow["DC_PRMT_YN"] = cdgSrc.CsmGridGetCell(iRow, 6);
                drNewRow["COST"] = cdgSrc.CsmGridGetCell(iRow, 7);
                drNewRow["SEQ"] = cdgSrc.CsmGridGetCell(iRow, 8);
                drNewRow["UPDATE"] = "U";
                drNewRow["TOT_DC_AMT"] = cdgSrc.CsmGridGetCell(iRow, 10);

                dtSrc.Rows[iRow]["UPDATE"] = "U";

                if (AllMove != true)
                {
                    // 수량1개
                    long nQty = m_cDataService.LongParse(dtSrc.Rows[iRow]["QTY"].ToString());
                    double nAmount = m_cDataService.DoubleParse(dtSrc.Rows[iRow]["AMOUNT"].ToString());
                    double nDanga = m_cDataService.DoubleParse(dtSrc.Rows[iRow]["COST"].ToString());

                    if (nQty <= 1)
                    {
                        // 삭제
                        dtSrc.Rows.RemoveAt(iRow);
                        AllMove = true; //부모가 1개일때는 다 넘겨주자!
                    }
                    else
                    {
                        // 원시 수량 1차감
                        nQty = nQty - 1;
                        dtSrc.Rows[iRow]["QTY"] = m_cPosStatus.Global.NumericToQuantity(nQty);
                        dtSrc.Rows[iRow]["AMOUNT"] = m_cPosStatus.Global.NumericTOCurrency(CmUtil.DoubleMultiplication(nQty, nDanga));            // 판매금액 재계산

                        // 타켓 수량 1로 설정
                        nQty = 1;
                        drNewRow["SEQ"] = "";       // 신규생성

                        // 다음 Row 세트자식/부가메뉴
                        iRow++;
                    }
                    drNewRow["QTY"] = m_cPosStatus.Global.NumericToQuantity(nQty);
                    drNewRow["AMOUNT"] = m_cPosStatus.Global.NumericTOCurrency(CmUtil.DoubleMultiplication(nQty, nDanga));

                    cdgSrc.CsmGridDataSource = dtSrc;
                    cdgSrc.CsmGridSelectRow(iRow);
                }
                else
                {
                    // 전체
                    drNewRow["QTY"] = cdgSrc.CsmGridGetCell(iRow, 3);
                    drNewRow["AMOUNT"] = cdgSrc.CsmGridGetCell(iRow, 4);

                    // 삭제
                    dtSrc.Rows.RemoveAt(iRow);
                    cdgSrc.CsmGridDataSource = dtSrc;
                    cdgSrc.CsmGridSelectRow(iRow);
                }

                // 추가
                dtTarget.Rows.Add(drNewRow);
                cdgTaget.CsmGridDataSource = dtTarget;
                cdgTaget.CsmGridSelectRow(cdgTaget.CsmGridRowsCount);

                // 부가메뉴 체크
                if (cdgSrc.CsmGridRowsCount > iRow)
                {
                    if (dtSrc.Rows[iRow]["ITEM_DIV"].ToString() == ItemConst.PLU_ITEM_DIV.OPT_MENU || dtSrc.Rows[iRow]["ITEM_DIV"].ToString() == ItemConst.PLU_ITEM_DIV.SET_DETL)
                        sRet = GridDataSet(cdgSrc, dtSrc, cdgTaget, dtTarget, AllMove, iRow, bDelete);
                }

                // 선택금액
                if (dtTarget.Rows.Count > 0)
                {
                    for (int iLoop = 0; iLoop < dtTarget.Rows.Count; iLoop++)
                    {
                        nPayAmount = CmUtil.DoubleAdd(nPayAmount, m_cDataService.DoubleParse(dtTarget.Rows[iLoop]["AMOUNT"].ToString()));
                    }
                }
                else
                {
                    for (int iLoop = 0; iLoop < dtSrc.Rows.Count; iLoop++)
                    {
                        nPayAmount = CmUtil.DoubleAdd(nPayAmount, m_cDataService.DoubleParse(dtSrc.Rows[iLoop]["AMOUNT"].ToString()));
                    }
                }


                if ((Cosmos.UI.CsmGrid)cdgSrc == cglAlliTem)
                {
                    // 등록금액
                    txtSaleAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cTrnStatus.Sale.RemainPayAmt - nPayAmount);

                    // 선택금액
                    txtPayAmt.Text = m_cPosStatus.Global.NumericTOCurrency(nPayAmount);

                }
                else
                {

                    // 등록금액
                    txtSaleAmt.Text = m_cPosStatus.Global.NumericTOCurrency(nPayAmount);

                    // 선택금액
                    txtPayAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cTrnStatus.Sale.RemainPayAmt - nPayAmount);
                }


                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);
                sRet = UserCom.RST_ERR;
            }

            return sRet;
        }
        #endregion

        /// <summary>
        /// 더치페이 결제
        /// </summary>
        /// <returns></returns>
        private string SetPay()
        {
            string sRet = UserCom.RST_ERR;

            try
            {

                // 상품정보
                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.NORMAL || cSaleItem.CANCEL_DIV_MAIN != PosConst.CANCEL_DIV.NORMAL) continue;


                    cSaleItem.DUTCH_PAY_CAN_DIV = cSaleItem.CANCEL_DIV;

                    cSaleItem.DUTCH_PAY_MAIN_CAN_DIV = cSaleItem.CANCEL_DIV_MAIN;

                    cSaleItem.CANCEL_DIV = "1";
                }

                // ---------------------------------------------------------------------------------------------------------
                // 타켓 업데이트
                // ---------------------------------------------------------------------------------------------------------
                for (int iRow = 0; iRow < m_dtcglBundleiTem.Rows.Count; iRow++)
                {
                    for (int iRow2 = 0; iRow2 < aSaleItem.Count; iRow2++)
                    {
                        Column.TR_PLU.DATA cSaleItem = (Column.TR_PLU.DATA)aSaleItem[iRow2];

                        if (cSaleItem.DUTCH_PAY_CAN_DIV != PosConst.CANCEL_DIV.NORMAL || cSaleItem.DUTCH_PAY_MAIN_CAN_DIV != PosConst.CANCEL_DIV.NORMAL) continue;


                        if (m_dtcglBundleiTem.Rows[iRow]["ITEMCD"].ToString() == cSaleItem.ITEM_PLU_CD)
                        {

                            if (cSaleItem.SALE_QTY >= cSaleItem.DUTCH_PAY_SELQTY + m_cDataService.LongParse(m_dtcglBundleiTem.Rows[iRow]["QTY"].ToString()))
                            {
                                cSaleItem.DUTCH_PAY_SELQTY = cSaleItem.DUTCH_PAY_SELQTY + m_cDataService.LongParse(m_dtcglBundleiTem.Rows[iRow]["QTY"].ToString());
                                cSaleItem.CANCEL_DIV = ItemConst.PAY_CANCEL_DIV.NORMAL;
                                break;
                            }

                        }
                    }
                }



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

                    if (cSaleItem.DUTCH_PAY_CAN_DIV != PosConst.CANCEL_DIV.NORMAL || cSaleItem.DUTCH_PAY_MAIN_CAN_DIV != PosConst.CANCEL_DIV.NORMAL) continue;


                    if (cSaleItem.CANCEL_DIV == ItemConst.PAY_CANCEL_DIV.NORMAL)
                    {
                        cSaleItem.SALE_QTY = cSaleItem.DUTCH_PAY_SELQTY;
                        //break;
                    }
                }


                m_cPluService.ItemAmountExeccute(true, true);

                IFormSaleMainUs cFormSaleMain = (IFormSaleMainUs)FormManager.GetForm(FormManager.FORM_SAL_MAIN);

                cFormSaleMain.DisplayItem(1, false);

                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>
        /// <param name="csmGrid"></param>
        /// <returns></returns>
        private string DcAmtCheck(Cosmos.UI.CsmGrid csmGrid)
        {
            string sRet = UserCom.RST_ERR;

            //UserCom.RST_ERR       에러
            //UserCom.RST_OK        정상
            //UserCom.RST_IGNORE    
            //UserCom.RST_RETRY     할일적용변경
            
            try
            {
                int iRow = csmGrid.CsmGridSelectedRowIndex;

                if (csmGrid.CsmGridRowsCount <= 0) return sRet;

                if (CmUtil.DoubleParse(csmGrid.CsmGridGetCell(iRow, 10).ToString()) > 0) return UserCom.RST_RETRY;

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

        #region DeviceEvent 관련
        /// <summary>
        /// DeviceEvent 관련
        /// </summary>
        /// <param name="sDevice"></param>
        /// <param name="sData1"></param>
        /// <param name="sData2"></param>
        /// <param name="sData3"></param>
        public void OnDeviceEvent(string sDevice, string sData1, string sData2, string sData3)
        {
            try
            {
                switch (sDevice)
                {
                    case PosConst.OPOS_DEVICE.MSR:
                        this.Invoke(new EventHandler(OnMSREvent));
                        break;
                    case PosConst.OPOS_DEVICE.SCANNER:
                        this.Invoke(new EventHandler(OnScannerEvent));
                        break;
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        /// <summary>
        /// MSR Event
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnMSREvent(object source, EventArgs e)
        {

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

        }
        #endregion

    }
}
