using System;
using System.Text;
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;

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 전체 금액,%,추가 할인
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Win
{
    public partial class frmTotItemDC : 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 IDataProcessUs m_cDataService = null;
        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스
        private ISalePluItemUs m_cPluService = null;                                // 상품등록 관리
        private IPaymentUs m_ciNStorDC = null;                                     // 점포임의 할인

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

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

        #endregion 변수 선언

        #region 생성자 & 소멸자 & 폼초기화
        public frmTotItemDC()
        {
            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_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);
            m_ciNStorDC = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.iNStorDC);
        }

        private void frmTotItemDC_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 frmTotItemDC_FormClosing(object sender, FormClosingEventArgs e)
        {
            //#20180110 전체금액할인 & 전체%할인 통합 Start
            //#20180227 전체금액할인 & 전체%할인 통합 국내만 적용되도록 수정 Start
            //if (m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_DC_AMT)
            if (m_cPosStatus.Mst.CntryDiv == ItemConst.CNTRY_DIV.KR && m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_DC_AMT)
            //#20180227 전체금액할인 & 전체%할인 통합 국내만 적용되도록 수정 End
            {
                m_sPosMenuKey = PosKey.MENU_KEY.TOTAL_DC_RATE;
            }
            //#20180110 전체금액할인 & 전체%할인 통합 End

            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()
        {
            string sRet = UserCom.RST_OK;

            try
            {
                this.Location = new Point(0, 50);
                this.Size = new Size(1024, 525);

                // 이미지 로딩 처리
                //picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_S);

                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 = "";

                //테마색상 적용!
                btnEnter.BackColor = CmUtil.GetColorToString(m_cPosStatus.ScnMst.ThemeColor);                            

                //#20180110 전체금액할인 & 전체%할인 통합 Start
                // 기존
                /*if (m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_DC_AMT)
                {
                    // 전체 금액 할인
                    lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0159);         // 전체 금액 할인
                    lblDCAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0036);         // 할인 금액
                    txtDCAmt.MaxLength = 9;
                }
                else if (m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_DC_RATE)
                {
                    // 전체 % 할인
                    lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0160);         // 전체 % 할인
                    lblDCAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0163);         // 할인율(%)
                    txtDCAmt.MaxLength = 3;
                }
                else if (m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_ADDDC_AMT)
                {
                    // 추가 금액 할인
                    lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0607);         // 추가 금액 할인
                    lblDCAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0036);         // 할인 금액
                    txtDCAmt.MaxLength = 9;
                }*/

                // 변경
                if (m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_ADDDC_AMT)
                {
                    // 추가 금액 할인
                    lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0607);         // 추가 금액 할인
                    lblDCAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0036);         // 할인 금액
                    txtDCAmt.MaxLength = 9;

                    SetControlLocation(false);
                }
                else
                {
                    //#20180227 전체금액할인 & 전체%할인 통합 국내만 적용되도록 수정 Start
                    // 기존
                    // 전체 %할인
                    /*m_sPosMenuKey = PosKey.MENU_KEY.TOTAL_DC_RATE;
                    lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0160);         // 전체 % 할인
                    lblDCAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0163);         // 할인율(%)
                    txtDCAmt.MaxLength = 3;

                    SetControlLocation(true);
                    rbTotalDCRate.Checked = true;*/

                    if (m_cPosStatus.Mst.CntryDiv == ItemConst.CNTRY_DIV.KR)  //한국
                    {
                        // 전체 %할인
                        m_sPosMenuKey = PosKey.MENU_KEY.TOTAL_DC_RATE;
                        lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0160);         // 전체 % 할인
                        lblDCAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0163);         // 할인율(%)
                        txtDCAmt.MaxLength = 3;

                        SetControlLocation(true);
                        rbTotalDCRate.Checked = true;
                    }
                    else
                    {
                        if (m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_DC_AMT)
                        {
                            // 전체 금액 할인
                            lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0159);         // 전체 금액 할인
                            lblDCAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0036);         // 할인 금액
                            txtDCAmt.MaxLength = 9;
                        }
                        else if (m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_DC_RATE)
                        {
                            // 전체 % 할인
                            lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0160);         // 전체 % 할인
                            lblDCAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0163);         // 할인율(%)
                            txtDCAmt.MaxLength = 3;
                        }

                        SetControlLocation(false);
                    }
                    //#20180227 전체금액할인 & 전체%할인 통합 국내만 적용되도록 수정 End

                }
                //#20180110 전체금액할인 & 전체%할인 통합 End

                lblSaleAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0037);           // 받은금액 
                lblDCTargetAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0162);       // 할인 대상 금액
                lblAfterDCAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0238);        // 기존 할인 금액

                btnSearch.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0161);            // 할인취소
                btnEnter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0047);             // 할인적용

                bNotDoubleClik = false;

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

                // 기존 할인 금액    
                double nAgoDcAmt = GetSaleItemDCAmt(false);                                                                                            

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

                txtDCTargerAmt.Text = m_cPosStatus.Global.NumericTOCurrency(CmUtil.DoubleAdd(m_cDataService.GetPluTagetAmount(m_sPosMenuKey), nAgoDcAmt));   // 할인 대상 금액

                txtAfterDCAmt.Text = m_cPosStatus.Global.NumericTOCurrency(nAgoDcAmt);                        // 기존 할인 금액                
                txtDCAmt.Text = "";
                txtDCAmt.Select();
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion

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

                if (((Cosmos.UI.CsmButton)sender) == btnSearch)             // 취소
                {
                    CompleteTxtInPut(true);
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnEnter)         // 할인
                {
                    CompleteTxtInPut(false);
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnExit)         // 닫기
                {
                    txtEditBox_EditBoxKeyDownEvent(null, PosKey.MENU_KEY.ESC_PREVIOUS);
                }
                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;
        }

        #endregion

        #region 텍스트박스 키 입력 이벤트 처리
        /// <summary>
        /// 텍스트박스 키 입력 이벤트 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="sFuncValue"></param>
        private void txtEditBox_EditBoxKeyDownEvent(object sender, string sFuncValue)
        {
            try
            {
                if (sFuncValue == PosKey.MENU_KEY.ENTER)
                {
                    if (((Cosmos.UI.CsmPosEditBox)sender) == txtDCAmt)
                    {
                        if (txtDCAmt.Text != "")
                        {
                            CompleteTxtInPut(false);
                            return;
                        }
                        else
                        {
                            txtDCAmt.Focus();
                        }
                    }
                }
                else if (sFuncValue == PosKey.MENU_KEY.CLEAR)
                {
                    if (((Cosmos.UI.CsmPosEditBox)sender).ReadOnly == false) ((Cosmos.UI.CsmPosEditBox)sender).Text = "";
                    if (((Cosmos.UI.CsmPosEditBox)sender) == txtDCAmt)
                    {
                        txtDCAmt.Text = "";
                    }
                }
                else if (sFuncValue == PosKey.MENU_KEY.ESC_PREVIOUS)
                {
                    this.DialogResult = DialogResult.Cancel;
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

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

        #region 텍스트박스 입력 유효성 체크
        /// <summary>
        /// 텍스트박스 입력 유효성 체크
        /// </summary>
        /// <param name="sender"></param>
        /// <returns></returns>
        private bool CheckTxtInPut(object sender)
        {
            try
            {
                // 길이 체크
                if (sender == null || ((Cosmos.UI.CsmPosEditBox)sender) == txtDCAmt)
                {
                    if (m_cDataService.DoubleParse(txtDCTargerAmt.Text) <= 0)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0050);
                        txtDCAmt.Focus();
                        return false;
                    }

                    if (m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_DC_AMT || m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_ADDDC_AMT)
                    {
                        // 금액할인
                        if (txtDCAmt.Value.Length > 10 || m_cDataService.DoubleParse(txtDCAmt.Value) == 0
                            || m_cDataService.DoubleParse(txtDCAmt.Value) > m_cDataService.DoubleParse(txtSaleAmt.Text) || m_cDataService.DoubleParse(txtDCAmt.Value) > m_cDataService.DoubleParse(txtDCTargerAmt.Text))
                        {
                            WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0049);
                            txtDCAmt.Focus();
                            return false;
                        }
                        // 할인 절삭
                        if (CmUtil.MathRounds(m_cDataService.DoubleParse(txtDCAmt.Value), m_cPosStatus.Mst.DcRudDwLocMethd, CmUtil.IntParse(m_cPosStatus.Mst.DcRudDwLoc)) != m_cDataService.DoubleParse(txtDCAmt.Value))
                        {
                            WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0036);
                            txtDCAmt.Focus();
                            return false;
                        }

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


                    }
                    else 
                    {
                        // 율할인
                        if (txtDCAmt.Value.Length > 10 || m_cDataService.DoubleParse(txtDCAmt.Value) == 0 || m_cDataService.DoubleParse(txtDCAmt.Value) > 100)
                        {
                            WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0051);
                            txtDCAmt.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)
                {
                    // 할인 취소
                    //if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0053) == false)    // 등록된 할인을 취소 하시겠습니까?
                    //    return sRet;

                    sRet = SetSaleItemTotalDCCancel();
                }
                else
                {
                    // 할인 적용
                    if (CheckTxtInPut(null) == false) return sRet;

                    //if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0124) == false)    // 할인 적용을 하시겠습니까?
                    //    return sRet;

                    sRet = SetSaleItemTotalDC(m_cDataService.DoubleParse(txtDCAmt.Value));
                }

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

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

        #region 전체상품 할인 처리
        ///// <summary>
        ///// 전체 상품중 할인 대상금액 조회
        ///// </summary>
        ///// <returns></returns>
        //public double GetSaleItemDCTargerAmt(bool bAllMode)
        //{
        //    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 (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 && bAllMode != true) 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;                                                                                  // 할인가능 여부 

        //            // 할인 대상 금액 sum
        //            nDCSum = CmUtil.DoubleAdd(nDCSum, cSaleItem.BILL_AMT);
        //        }
        //    }
        //    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>
        /// 전체 상품중 임의할인 금액 Sum 조회
        /// </summary>
        /// <returns></returns>
        public double GetSaleItemDCAmt(bool bAllMode)
        {
            double nDCSum = 0;

            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.CANCEL || cSaleItem.CANCEL_DIV_MAIN == PosConst.CANCEL_DIV.CANCEL) continue;// 지정취소
                    if (cSaleItem.NONSALES_RSN_CD != "0") continue;                                                                             // 비매출구분
                    if (cSaleItem.BILLSPR_NO != m_cTrnStatus.Sale.BillSplitNo) continue;                                                        // 빌분리번호
                    if (cSaleItem.DC_PRMT_YN != "0") continue;                                                                                  // 할인가능 여부 

                    if (m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_DC_AMT || m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_DC_RATE)
                    {
                        // 전체상품할인
                        nDCSum = CmUtil.DoubleAdd(nDCSum, cSaleItem.ITEM_DC_AMT);
                    }
                    else if (m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_ADDDC_AMT) 
                    {
                        // 추가전체할인
                        nDCSum = CmUtil.DoubleAdd(nDCSum, cSaleItem.ETC_DC_AMT);
                    }
                }
            }
            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="nTotDcAmt"></param>
        /// <returns></returns>
        public string SetSaleItemTotalDC(double nTotDcAmt)
        {
            double nTotSaleAmt = 0;
            double nApplyAmt = 0, nDisAmt = 0, nMaxAmt = 0;
            int nMaxRow = 0;
            string sRet = UserCom.RST_ERR;

            try
            {
                // 기존 할인 취소 처리
                if (m_cDataService.DoubleParse(txtAfterDCAmt.Text) > 0) SetSaleItemTotalDCCancel();

                // 할인 대상상품 합계
                double nAgoDcAmt = GetSaleItemDCAmt(false);   
                nTotSaleAmt = CmUtil.DoubleAdd(m_cDataService.GetPluTagetAmount(m_sPosMenuKey), nAgoDcAmt);          

                // 할인 금액
                if (m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_DC_RATE)
                {
                    nTotDcAmt = CmUtil.MathAmtPercent(nTotSaleAmt, nTotDcAmt);
                    nTotDcAmt = CmUtil.MathRounds(nTotDcAmt, m_cPosStatus.Mst.DcRudDwLocMethd, CmUtil.IntParse(m_cPosStatus.Mst.DcRudDwLoc));
                }

                // 상품정보
                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.NONSALES_RSN_CD != "0") continue;                                                                                 // 비매출구분
                    if (cSaleItem.BILLSPR_NO != m_cTrnStatus.Sale.BillSplitNo) continue;                                                            // 빌분리번호
                    if (cSaleItem.DC_PRMT_YN != "0") continue;                                                                                      // 할인가능 여부 

                    if (m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_DC_AMT || m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_DC_RATE)
                    {
                        nDisAmt = CmUtil.DoubleMultiplication(nTotDcAmt, CmUtil.DoubleDivision(cSaleItem.BILL_AMT, nTotSaleAmt));
                        nDisAmt = CmUtil.MathRounds(nDisAmt, m_cPosStatus.Mst.ItemRudDwLocMethd, CmUtil.IntParse(m_cPosStatus.Mst.ItemRudDwLoc));

                        // 상품할인 적용(전체 할인)
                        cSaleItem.ITEM_DC_AMT = nDisAmt;
                        cSaleItem.DC_DIV = m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_DC_AMT ? ItemConst.PLU_DC_DIV.IN_DC_TOTAMT : ItemConst.PLU_DC_DIV.IN_DC_TOTRATE;
                        cSaleItem.DC_TYPE = ItemConst.PLU_DC_TYPE.DC_SUM;           // 단품 할인 타입(0:없음, 1:소계할인, 2:단품할인)
                    }
                    else if (m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_ADDDC_AMT) 
                    {
                        nDisAmt = CmUtil.DoubleMultiplication(nTotDcAmt, CmUtil.DoubleDivision(cSaleItem.BILL_AMT, nTotSaleAmt));
                        nDisAmt = CmUtil.MathRounds(nDisAmt, m_cPosStatus.Mst.ItemRudDwLocMethd, CmUtil.IntParse(m_cPosStatus.Mst.ItemRudDwLoc));

                        // 상품할인 적용(추가 할인)
                        cSaleItem.ETC_DC_AMT = nDisAmt;
                        cSaleItem.ETC_DC_DIV = ItemConst.PLU_DC_DIV.IN_DC_ADDAMT;
                    }

                    m_cDataService.UpdatePluItemAmount(cSaleItem);

                    nApplyAmt = CmUtil.DoubleAdd(nApplyAmt, nDisAmt);
                    if (nMaxAmt == 0 || nMaxAmt < cSaleItem.BILL_AMT)
                    {
                        nMaxAmt = cSaleItem.BILL_AMT;
                        nMaxRow = iRow;
                    }

                }

                // 자투리 금액 
                if (nTotDcAmt != nApplyAmt)
                    {
                    Column.TR_PLU.DATA cSaleItem = (Column.TR_PLU.DATA)aSaleItem[nMaxRow];

                    if (m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_DC_AMT || m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_DC_RATE)
                    {
                        // 상품할인 적용(전체 할인)
                        cSaleItem.ITEM_DC_AMT = CmUtil.DoubleAdd(cSaleItem.ITEM_DC_AMT, CmUtil.DoubleSubtraction(nTotDcAmt, nApplyAmt));
                    }
                    else if (m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_ADDDC_AMT) 
                    {
                        // 상품할인 적용(추가 할인)
                        cSaleItem.ETC_DC_AMT = CmUtil.DoubleAdd(cSaleItem.ETC_DC_AMT, CmUtil.DoubleSubtraction(nTotDcAmt, nApplyAmt));
                    }
                    m_cDataService.UpdatePluItemAmount(cSaleItem);
                }

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

                // 결제 아이템 생성
                sRet = m_ciNStorDC.SetPayment(new string[] { m_sPosMenuKey, "", "", "", nTotDcAmt.ToString(), nTotSaleAmt.ToString(), "", "" }); 
                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;
        }

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

            try
            {
                // 결제 수단 취소
                ArrayList alPayItem = (ArrayList)StateObject.GetItemObject(Column.TR_PAYMENT.ITEM);

                for (int iRow = 0; iRow < alPayItem.Count; iRow++)
                {
                    Column.TR_PAYMENT.DATA cPayItem = (Column.TR_PAYMENT.DATA)alPayItem[iRow];

                    // 취소구분
                    if (cPayItem.CANCEL_DIV == ItemConst.PAY_CANCEL_DIV.CANCEL) continue;
                    // 할인
                    if (cPayItem.PAY_WAY_CD != ItemConst.TR_ITEM_ID.USER_DC_ITEM ) continue;

                    if (m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_DC_AMT || m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_DC_RATE)
                    {
                        if (cPayItem.PAY_DTL_CD_01 == ItemConst.TR_ITEM_ID.USER_DC.TOTAL_DC_AMT || cPayItem.PAY_DTL_CD_01 == ItemConst.TR_ITEM_ID.USER_DC.TOTAL_DC_RATE)
                        {
                            // 결제 수단 취소
                            m_ciNStorDC.CancelPayment(new string[] { iRow.ToString() });
                        }
                    }
                    else if (m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_ADDDC_AMT) 
                    {
                        if (cPayItem.PAY_DTL_CD_01 == ItemConst.TR_ITEM_ID.USER_DC.TOTAL_ADDDC_AMT)
                        {
                            // 결제 수단 취소
                            m_ciNStorDC.CancelPayment(new string[] { iRow.ToString() });
                        }
                    }
                }

                // 상품정보
                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.ITEM_DC_AMT == 0) continue;                                   // 할인 금액

                    if (m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_DC_AMT || m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_DC_RATE)
                    {
                        // 상품할인 적용
                        cSaleItem.ITEM_DC_AMT = 0;
                        cSaleItem.DC_DIV = ItemConst.PLU_DC_DIV.NORMAL;
                        cSaleItem.DC_TYPE = ItemConst.PLU_DC_TYPE.NORMAL;                           // 단품 할인 타입(0:없음, 1:소계할인, 2:단품할인)
                    }
                    else if (m_sPosMenuKey == PosKey.MENU_KEY.TOTAL_ADDDC_AMT)
                    {
                        cSaleItem.ETC_DC_AMT = 0;
                        cSaleItem.ETC_DC_DIV = ItemConst.PLU_DC_DIV.NORMAL;
                    }
                    // 상품행별 영수 금액 재계산 처리
                    m_cDataService.UpdatePluItemAmount(cSaleItem);
                }

                // 상품 판매가 계산
                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

        //#20180110 전체금액할인 & 전체%할인 통합 Start
        #region 전체금액할인 & 전체%할인 통합 관련 화면 처리
        /// <summary>
        /// 전체%할인 & 전체금액할인 숨김처리 및 컨트롤 위치 변경
        /// </summary>
        /// <param name="bToltalDCYN"></param>
        /// <returns></returns>
        public void SetControlLocation(bool bToltalDCYN)
        {
            lblDCCategory.Visible = bToltalDCYN;
            lblBox5.Visible = bToltalDCYN;
            rbTotalDCAmt.Visible = bToltalDCYN;
            rbTotalDCRate.Visible = bToltalDCYN;

            //#20180221 추가금액할인 창 연속으로 들어가는 경우 금액 입력창 사라지는 증상 수정 start
            lblDCAmt.Location = new Point(238, 308);
            lblAfterDCAmt.Location = new Point(238, 347);

            lblBox3.Location = new Point(359, 308);
            lblBox4.Location = new Point(359, 347);

            txtDCAmt.Location = new Point(376, 315);
            txtAfterDCAmt.Location = new Point(376, 354);
            //#20180221 추가금액할인 창 연속으로 들어가는 경우 금액 입력창 사라지는 증상 수정 end

            if (bToltalDCYN == false)
            {
                //#20180227 전체금액할인 & 전체%할인 통합 국내만 적용되도록 수정 Start
                // 기존
                /*lblAfterDCAmt.Location = lblDCAmt.Location;
                lblDCAmt.Location = lblDCCategory.Location;

                lblBox4.Location = lblBox3.Location;
                lblBox3.Location = lblBox5.Location;

                txtAfterDCAmt.Location = txtDCAmt.Location;
                txtDCAmt.Location = new Point(376, 276);*/

                lblDCAmt.Location = new Point(238, 269);
                lblAfterDCAmt.Location = new Point(238, 308);

                lblBox3.Location = new Point(359, 269);
                lblBox4.Location = new Point(359, 308);

                txtDCAmt.Location = new Point(376, 276);
                txtAfterDCAmt.Location = new Point(376, 315);
                //#20180227 전체금액할인 & 전체%할인 통합 국내만 적용되도록 수정 End

            }
            else
            {

                lblDCAmt.Location = new Point(238, 308);
                lblAfterDCAmt.Location = new Point(238, 347);

                lblBox3.Location = new Point(359, 308);
                lblBox4.Location = new Point(359, 347);

                txtDCAmt.Location = new Point(376, 315);
                txtAfterDCAmt.Location = new Point(376, 354);

                lblDCCategory.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1021);
                rbTotalDCRate.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0160);
                rbTotalDCAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0159);
            }

            label4.Location = lblAfterDCAmt.Location;
        }

        private void TotalDCRadioButton_Click(object sender, EventArgs e)
        {
            if (sender == rbTotalDCRate)
            {
                m_sPosMenuKey = PosKey.MENU_KEY.TOTAL_DC_RATE;

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0160);         // 전체 % 할인
                lblDCAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0163);         // 할인율(%)
                txtDCAmt.MaxLength = 3;
            }
            else if (sender == rbTotalDCAmt)
            {
                m_sPosMenuKey = PosKey.MENU_KEY.TOTAL_DC_AMT;

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0159);         // 전체 금액 할인
                lblDCAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0036);         // 할인 금액
                txtDCAmt.MaxLength = 9;
            }

            txtDCAmt.Select();
        }
        #endregion
        //#20180110 전체금액할인 & 전체%할인 통합 End

        //#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.ITEM_DC_AMT > 0)
        //            {
        //                if (cSaleItem.DC_DIV != ItemConst.PLU_DC_DIV.NORMAL && cSaleItem.DC_DIV != ItemConst.PLU_DC_DIV.POS_DC)
        //                // 소계할인
        //                {
        //                    WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0113);  // 기존 할인을 취소후 시도하여 주시기 바랍니다.
        //                    sRet = UserCom.ERROR;
        //                    return sRet;
        //                }
        //            }
        //        }
        //    }
        //    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

    }
}
