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 frmCakeChange : frm_PayMainBack
    {
        #region 변수 선언

        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        private PosStatus m_cPosStatus = new PosStatus();                           // 기본정보 참조
        private TranStatus m_cTrnStatus = new TranStatus();                         // 거래정보 참조        
        private DeviceStatus m_cDevStatus = new DeviceStatus();                     // 디바이스 관리

        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스
        private IDataProcessUs m_cDataService = null;
        private IPaymentUs m_cCakeChange = null;

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

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

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

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

        #endregion 변수 선언

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

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

            m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
            m_cTrnStatus = (TranStatus)StateObject.TRAN;    // POS 거래정보 
            m_cDataService = (IDataProcessUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_SERVICE);
            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
            m_cCakeChange = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.CAKECHANGE);
        }

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

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

        private void frmCakeChange_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
            {
                // 이미지 로딩 처리
                //picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_S);
                //this.Size = new Size(788, 402);
                //this.Location = new Point(216, 173);
                //picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_S);
                this.Location = new Point(0, 50);
                this.Size = new Size(1024, 525);
                //this.BackColor = Color.FromArgb(114, 114, 114);

                //버튼이미지 적용
                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 = "";

                btnExit.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BTN_CLOSE);
                if (btnExit.Image != null) btnExit.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);

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

                m_sPay_DC_Grp_Type = ItemConst.TR_ITEM_ID.COUPON_ITEM;
                m_sPay_DC_CD = ItemConst.TR_ITEM_ID.COUPON.CAKE_CHANGE;

                lblCardNo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0739);
                lblCakeChangeAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0740);
                lblSaleAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0037);

                btnComplete.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0263);                      // 결제

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

                bNotDoubleClik = false;

                txtCakeChangeAmt.Text = m_cPosStatus.Global.NumericTOCurrency(0);
                DataTable dtData = m_cDataCommon.SeletCommonCode(PosConst.COMMON_CODE_GROUP.Z0025, "");
                if (dtData != null && dtData.Rows.Count > 0)
                {
                    foreach (DataRow dr in dtData.Rows)
                    {
                        txtCakeChangeAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cDataService.DoubleParse(CmUtil.GetDataRowStr(dr, PosMst.MST_COMMON.DATA.CHAR_VAL_TITLE_VAL_01)));
                    }
                }

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

                txtCardNo.Select();
                txtCardNo.SelectText();
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion

        #region 버튼 입력 처리
        /// <summary>
        /// 버튼 입력 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnProc_Click(object sender, EventArgs e)
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                if (bNotDoubleClik) return;
                bNotDoubleClik = true;

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

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

                            dgvData.Rows[iLoop].Selected = true;
                            dgvData.Rows[iLoop].Cells[dgvData.CurrentCell.ColumnIndex].Selected = true;
                            break;
                        }
                    }
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnComplete)          // 결제
                {                    
                    // 결제
                    sRet = CompleteTxtInPut(false);

                    bNotDoubleClik = false;
                    if (sRet != UserCom.RST_OK)
                    {
                        this.DialogResult = DialogResult.Cancel;
                    }
                    else
                    {
                        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>
        /// <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)
                {
                }
                else if (sFuncValue == PosKey.MENU_KEY.ESC_PREVIOUS)
                {
                    this.DialogResult = DialogResult.Cancel;
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        private void txtCardNo_EditBoxTextChangedEvnet(object sender, EventArgs e)
        {
            try
            {
                m_sInPutType = "";                                                                                  // 입력구분
                m_sInPutData = "";                                                                                  // 입력데이터
                m_sInEncData = "";                                                                                  // 카드데이터

                txtCakeChangeAmt.Text = m_cPosStatus.Global.NumericTOCurrency(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);
            }
        }

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

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

                if (txtCakeChangeAmt.Value.Length > 10 || m_cDataService.DoubleParse(txtCakeChangeAmt.Value) <= 0)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0036);
                    txtCakeChangeAmt.Focus();
                    return false;
                }

                if (CmUtil.AmountCut(m_cDataService.DoubleParse(txtCakeChangeAmt.Value), CmUtil.IntParse(m_cPosStatus.Mst.PayRudDwLoc)) != m_cDataService.DoubleParse(txtCakeChangeAmt.Value))
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0036);
                    txtCakeChangeAmt.Focus();
                    return false;
                }

                // 금액 체크
                //if (m_cDataService.DoubleParse(txtSaleAmt.Text) < m_cDataService.DoubleParse(txtCakeChangeAmt.Text))
                //{
                //    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0039);
                //    txtCakeChangeAmt.Select();
                //    txtCakeChangeAmt.SelectText();
                //    return false;
                //}
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
                return false;
            }
            return true;
        }
        #endregion

        #region 텍스트박스 입력 완료 처리
        /// <summary>
        /// 결제 처리
        /// </summary>
        /// <param name="nFlowMode"></param>
        /// <returns></returns>
        private string CompleteTxtInPut(bool bExchangeMode)
        {
            string sRet = UserCom.RST_ERR;

            try
            {
                if (CheckTxtInPut(null) != true) return sRet;

                if (dgvData.RowCount <= 0)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0431);
                    return sRet;
                }

                // 상품금액 체크
                string siTemCD = "";
                double nSaleAmt = 0;
                double nPayAmt = 0;           
                for (int iLoop = 0; iLoop < dgvData.RowCount; iLoop++)
                {
                    if ((bool)dgvData.Rows[iLoop].Cells[0].Value != true) continue;

                    siTemCD = dgvData.Rows[iLoop].Cells[1].Value.ToString().Trim();
                    nSaleAmt = m_cDataService.DoubleParse(dgvData.Rows[iLoop].Cells[4].Value.ToString());
                    break;
                }
                
                if (nSaleAmt <= 0)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0123);
                    return sRet;
                }

                // 결제금액 체크 (최대값 체크)
                if (m_cDataService.DoubleParse(txtCakeChangeAmt.Text) >= nSaleAmt) 
                    nPayAmt = nSaleAmt;
                else 
                    nPayAmt = m_cDataService.DoubleParse(txtCakeChangeAmt.Text);

                // 저장
                sRet = m_cCakeChange.SetPayment(new string[] { m_sPosMenuKey, m_sPay_DC_Grp_Type, m_sPay_DC_CD, txtCardNo.Value, nPayAmt.ToString(), m_cDataService.DoubleParse(txtCakeChangeAmt.Text).ToString(), siTemCD });
                if (sRet != UserCom.RST_OK) return sRet;

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

                sRet = UserCom.RST_OK;

            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            return sRet;
        }
        #endregion

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

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

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

        }

        /// <summary>
        /// 카드 번호 암호화
        /// </summary>
        /// <param name="sInData"></param>
        /// <param name="sCardData"></param>
        /// <param name="sCardNo"></param>
        /// <returns></returns>
        private string EncryptedCardNo(string sInData, ref string sCardData, ref string sCardNo)
        {
            string sEncData = sInData;

            try
            {
                 
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            return sEncData;
        }

        /// <summary>
        /// IC 카드 정보 입력 처리
        /// </summary>
        /// <returns></returns>
        private bool GetIcCardData()
        {
            try
            {
 
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            return false;
        }
        #endregion

        #region 그리드 설정 및 사용
        private double DataGridSetting(int iWorkMode)
        { 
            try
            {
                if (iWorkMode == 0)
                {
                    // 초기화
                    dgvData.Rows.Clear();

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

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

                    // 타이틀 설정
                    dgvData.Columns[0].HeaderText = "";
                    dgvData.Columns[1].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0178);
                    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);

                    // 조회
                    // 기존 결제 체크
                    ArrayList alPayItem = (ArrayList)StateObject.GetItemObject(Column.TR_PAYMENT.ITEM);
                    foreach (Column.TR_PAYMENT.DATA cPayItem in alPayItem)
                    {
                        if (cPayItem.CANCEL_DIV == "1") continue;
                        if (cPayItem.PAY_WAY_CD == ItemConst.TR_ITEM_ID.COUPON_ITEM && cPayItem.PAY_DTL_CD_01 == ItemConst.TR_ITEM_ID.COUPON.CAKE_CHANGE)
                        {
                            WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0648);

                            this.DialogResult = DialogResult.Cancel;
                            this.Close();
                        }
                    }

                    // 상품정보
                    ArrayList aSaleItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);
                    int iMaxindex = 0;
                    double nMaxAmt = 0;
                    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.CANCEL || cSaleItem.CANCEL_DIV_MAIN == PosConst.CANCEL_DIV.CANCEL) continue;// 지정취소
                        if (cSaleItem.DC_DIV == ItemConst.PLU_DC_DIV.FREE) continue;                                                                // 서비스(무료)
                        if (cSaleItem.ITEM_DIV != ItemConst.PLU_ITEM_DIV.NORMAL) continue;                                                          // 상품구분(일반)
                        if (cSaleItem.NONSALES_RSN_CD != "0") continue;                                                                             // 비매출구분
                        if (cSaleItem.BILLSPR_NO != m_cTrnStatus.Sale.BillSplitNo) continue;                                                        // 빌분리번호
                        if (cSaleItem.BILL_AMT <= 0) continue;                                                                                      // 영수금액
                        if (cSaleItem.DC_PRMT_YN != "0") continue;                                                                                  // 할인가능 여부 

                        if (cSaleItem.CAKE_EXCHNG_CPN_USE_POSS_YN != "1") continue;

                        int iRow = dgvData.Rows.Add();

                        dgvData.Rows[iRow].Visible = true;

                        dgvData.Rows[iRow].DefaultCellStyle.ForeColor = Color.Black;
                        dgvData.Rows[iRow].DefaultCellStyle.SelectionForeColor = Color.Black;

                        dgvData.Rows[iRow].Cells[0].Value = false;
                        dgvData.Rows[iRow].Cells[1].Value = cSaleItem.ITEM_PLU_CD;                                          // 코드
                        dgvData.Rows[iRow].Cells[2].Value = cSaleItem.ITEM_NAME;                                            // 명칭
                        dgvData.Rows[iRow].Cells[3].Value = m_cPosStatus.Global.NumericTOCurrency(cSaleItem.SALE_QTY);      // 수량 
                        dgvData.Rows[iRow].Cells[4].Value = m_cPosStatus.Global.NumericTOCurrency(cSaleItem.SALE_AMT);      // 금액

                        if (nMaxAmt <= m_cDataService.DoubleParse(cSaleItem.SALE_AMT.ToString()))
                        {
                            iMaxindex = iRow;
                            nMaxAmt = m_cDataService.DoubleParse(cSaleItem.SALE_AMT.ToString());
                        }
                    }

                    // 제일 큰 금액의 케익 선택
                    if (iMaxindex >= 0 && nMaxAmt > 0)
                    {
                        dgvData.Rows[iMaxindex].Cells[0].Value = true;

                        // 결제
                        btnProc_Click(btnComplete, null);
                    }
                }

                dgvData.Refresh();

                if (dgvData.Rows.Count <= 0)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0431);
                    
                    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);
            }
            return 0;
        }

        #endregion

        #region 그리드 상품 선택
        private void dgvData_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (dgvData.CurrentCell != null)
                {
                    if (e.RowIndex == -1) return;

                    if ((bool)dgvData.Rows[e.RowIndex].Cells[0].Value == true)
                    {
                        for (int iLoop = 0; iLoop < dgvData.RowCount; iLoop++)
                        {
                            if (e.RowIndex == iLoop)
                            {
                                dgvData.Rows[iLoop].Cells[0].Value = !(bool)dgvData.Rows[iLoop].Cells[0].Value;
                                continue;
                            }
                            if ((bool)dgvData.Rows[iLoop].Cells[0].Value == true)
                            {
                                dgvData.Rows[iLoop].Cells[0].Value = false;
                            }
                        }
                    }
                    else
                    {
                        dgvData.Rows[e.RowIndex].Cells[0].Value = !(bool)dgvData.Rows[e.RowIndex].Cells[0].Value;
                    }
                }
            }
            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


    }

}
