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

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

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 인천공항 VIP 라운지 결제 처리
// 작  성  자 : grayber@20180115
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/

namespace Cosmos.Win
{
    // grayber@20180115 인천공항 VIP 라운지 start - 폼 클래스
    public partial class frmVipLounge : frm_PayMainBack
    {

        #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 IPaymentUs m_cPaymentUs = null;                                       // 현금 결제 클레스
        private IDataProcessUs m_cDataService = null;                                   // 거래데이터 합계금액 계산 및 관리
        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스

        private string m_sPayAmtIn;
        public string SetPayAmt { set { m_sPayAmtIn = value; } }                    // 판매등록시 사용자 입력 금액

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

        private PosOLEDevice.DelegateOlePos delegatePos;

        #endregion Variable

        #region 생성자 & 소멸자

        public frmVipLounge()
        {
            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_cPaymentUs = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.VIP_LOUNGE);

            // OLE 입력 델리게이트 생성
            delegatePos = new PosOLEDevice.DelegateOlePos(OnDeviceEvent);
            
        }
        private void frmVipLounge_Load(object sender, EventArgs e)
        {
            UserLog.WriteLogFile(UserCom.LOG_IOS, UserCom.ERROR_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "");
            InitControl();
        }

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

        private void frmVipLounge_Activated(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(delegatePos);
        }

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

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        #endregion 생성자 & 소멸자
        
        #region 폼 컨트롤 초기화
        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            try
            {

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

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

                btnPay1.Visible = true;
                btnPay2.Visible = true;
                btnPay3.Visible = true;
                btnPay4.Visible = true;
                btnPay5.Visible = true;
                btnPay6.Visible = true;

                // Add, 2017.08.29, 받은돈 권종 입력 편의를 위해 기존 버튼에 +1000원 / +500원 / +100원 추가 진행 
                btnPay7.Visible = true;
                btnPay8.Visible = true;
                btnPay9.Visible = true;

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1084);     // VIP 라운지
                lblCashAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0049);   // 결제금액

                SetPay();       // 결제 대상 금액 세팅

                if (string.IsNullOrEmpty(m_sPayAmtIn) == false)
                {
                    txtCashAmt.Value = m_cPosStatus.Global.NumericTOCurrency(m_cDataService.DoubleParse(m_sPayAmtIn));
                }
                else
                {
                    txtCashAmt.Value = m_cPosStatus.Global.NumericTOCurrency(m_cTrnStatus.Sale.RemainPayAmt);
                }

                if (string.IsNullOrEmpty(m_cPosStatus.Sale.SaleMainPayStep)) m_cPosStatus.Sale.SaleMainPayStep = "3";

                m_sPayAmtIn = "";

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

                // 기능 버튼 설정 체크
                FormManager.SetbtnMenu(null, m_cDevStatus.ICReader.UseYn, btnMenu1, btnMenu2, btnMenu3, btnMenu4);

                txtCashAmt.Select();
                txtCashAmt.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);
            }
        }

        /// <summary>
        /// 결제 대상 금액 세팅
        /// </summary>
        private void SetPay()
        {
            int nRow = 0;
            try
            {
                string sPayamt = m_cPosStatus.Global.NumericTOCurrency(m_cTrnStatus.Sale.RemainPayAmt);
                txtCashAmt.Text = m_cPosStatus.Global.NumericTOCurrency(0); // sPayamt;  // 결제 대상 금액
                
                btnPay1.Text = sPayamt;     // 결제 대상 금액
                btnPay1.Tag = "0" + m_cTrnStatus.Sale.RemainPayAmt.ToString();

                btnPay2.Visible = false;
                btnPay3.Visible = false;
                btnPay4.Visible = false;
                btnPay5.Visible = false;
                btnPay6.Visible = false;

                // Add, 2017.08.29, 받은돈 권종 입력 편의를 위해 기존 버튼에 +1000원 / +500원 / +100원 추가 진행 
                btnPay7.Visible = false;
                btnPay8.Visible = false;
                btnPay9.Visible = false;

                // 0:pay, 1:Add
                DataTable dtData = m_cDataCommon.SeletCommonCode(PosConst.COMMON_CODE_GROUP.Z0001, "");
                nRow = 0;
                if ( dtData != null && dtData.Rows.Count > 0)
                {
                    foreach (DataRow dr in dtData.Rows)
                    {
                        nRow++;
                        if (nRow == 1)
                        {
                            double nCashCeiling = CmUtil.MathRounds(m_cTrnStatus.Sale.RemainPayAmt, PosConst.MATH_ROUND.CEILING, CmUtil.GetDataRowInt(dr, PosMst.MST_COMMON.DATA.CHAR_VAL_TITLE_VAL_01));

                            btnPay2.Text = m_cPosStatus.Global.NumericTOCurrency(nCashCeiling);
                            btnPay2.Tag = "0" + nCashCeiling.ToString();
                            btnPay2.Visible = true;
                        }
                        if (nRow == 2)
                        {
                            double nCashCeiling = CmUtil.MathRounds(m_cTrnStatus.Sale.RemainPayAmt, PosConst.MATH_ROUND.CEILING, CmUtil.GetDataRowInt(dr, PosMst.MST_COMMON.DATA.CHAR_VAL_TITLE_VAL_01));

                            btnPay3.Text = m_cPosStatus.Global.NumericTOCurrency(nCashCeiling);
                            btnPay3.Tag = "0" + nCashCeiling.ToString();
                            btnPay3.Visible = true;
                        }
                    }
                }

                dtData = m_cDataCommon.SeletCommonCode(PosConst.COMMON_CODE_GROUP.Z0002, "");
                nRow = 0;
                if (dtData != null && dtData.Rows.Count > 0)
                {
                    foreach (DataRow dr in dtData.Rows)
                    {
                        nRow++;
                        if (nRow == 1)
                        {
                            btnPay4.Text = "+" + CmUtil.GetDataRowStr(dr, PosMst.MST_COMMON.DATA.CD_NM);
                            btnPay4.Tag = "1" + CmUtil.GetDataRowStr(dr, PosMst.MST_COMMON.DATA.CHAR_VAL_TITLE_VAL_01);
                            btnPay4.Visible = true;
                        }
                        if (nRow == 2)
                        {
                            btnPay5.Text = "+" + CmUtil.GetDataRowStr(dr, PosMst.MST_COMMON.DATA.CD_NM);
                            btnPay5.Tag = "1" + CmUtil.GetDataRowStr(dr, PosMst.MST_COMMON.DATA.CHAR_VAL_TITLE_VAL_01);
                            btnPay5.Visible = true;
                        }
                        if (nRow == 3)
                        {
                            btnPay6.Text = "+" + CmUtil.GetDataRowStr(dr, PosMst.MST_COMMON.DATA.CD_NM);
                            btnPay6.Tag = "1" + CmUtil.GetDataRowStr(dr, PosMst.MST_COMMON.DATA.CHAR_VAL_TITLE_VAL_01);
                            btnPay6.Visible = true;
                        }

                        // Add, 2017.08.29, 받은돈 권종 입력 편의를 위해 기존 버튼에 +1000원 / +500원 / +100원 추가 진행 
                        //      공통코드(Z0002) , 정렬순서 중요 
                        //      그룹코드    코드     언어            값  정렬순서
                        //      Z0002	    1	    ko-KR   	 5,000	1       
                        //      Z0002	    2	    ko-KR   	10,000	2       
                        //      Z0002	    3	    ko-KR   	50,000	3
                        //      Z0002	    4	    ko-KR   	   100	4           (신규)
                        //      Z0002	    5	    ko-KR   	   500	5           (신규)
                        //      Z0002	    6	    ko-KR   	 1,000	6           (신규)
                        if (nRow == 4)
                        {
                            btnPay7.Text = "+" + CmUtil.GetDataRowStr(dr, PosMst.MST_COMMON.DATA.CD_NM);
                            btnPay7.Tag = "1" + CmUtil.GetDataRowStr(dr, PosMst.MST_COMMON.DATA.CHAR_VAL_TITLE_VAL_01);
                            btnPay7.Visible = true;
                        }
                        if (nRow == 5)
                        {
                            btnPay8.Text = "+" + CmUtil.GetDataRowStr(dr, PosMst.MST_COMMON.DATA.CD_NM);
                            btnPay8.Tag = "1" + CmUtil.GetDataRowStr(dr, PosMst.MST_COMMON.DATA.CHAR_VAL_TITLE_VAL_01);
                            btnPay8.Visible = true;
                        }
                        if (nRow == 6)
                        {
                            btnPay9.Text = "+" + CmUtil.GetDataRowStr(dr, PosMst.MST_COMMON.DATA.CD_NM);
                            btnPay9.Tag = "1" + CmUtil.GetDataRowStr(dr, PosMst.MST_COMMON.DATA.CHAR_VAL_TITLE_VAL_01);
                            btnPay9.Visible = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                   System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        #endregion
        
        #region Control Event

        //<summary>
         //버튼 입력 처리
         //</summary>
         //<param name="sender"></param>
         //<param name="e"></param>
        private void btnProc_Click(object sender, EventArgs e)
        {            
            try
            {
                if (((UI.CsmButton)sender).Tag.ToString().StartsWith("0") == true)      // 금액 설정
                {
                    txtCashAmt.Value = ((UI.CsmButton)sender).Tag.ToString().Substring(1);
                    txtEditBox_EditBoxKeyDownEvent(txtCashAmt, PosKey.MENU_KEY.ENTER);
                }
                else
                {
                    // txtCashAmt 금액에서 시작하는 것이 아니라 0에서 시작하도록 변경(가맹점 요청 - 2017.07.07)
                    //txtCashAmt.Value = m_cPosStatus.Global.NumericTOCurrency(CmUtil.DoubleAdd(m_cDataService.DoubleParse(txtCashAmt.Value), m_cDataService.DoubleParse(((UI.CsmButton)sender).Tag.ToString().Substring(1))));
                    string sFirstValue = string.Empty;
                    if (string.IsNullOrEmpty(m_sPayAmtIn) == false)
                    {
                        sFirstValue = m_cPosStatus.Global.NumericTOCurrency(m_cDataService.DoubleParse(m_sPayAmtIn));
                    }
                    else
                    {
                        sFirstValue = m_cPosStatus.Global.NumericTOCurrency(m_cTrnStatus.Sale.RemainPayAmt);
                    }
                    txtCashAmt.Value = m_cPosStatus.Global.NumericTOCurrency(CmUtil.DoubleAdd( (sFirstValue.Equals(txtCashAmt.Text) ? m_cDataService.DoubleParse(m_cPosStatus.Global.NumericTOCurrency(m_cDataService.DoubleParse("0"))) : m_cDataService.DoubleParse(txtCashAmt.Value))
                                                                                             , m_cDataService.DoubleParse(((UI.CsmButton)sender).Tag.ToString().Substring(1))));
                }

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

        /// <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 (CheckTxtInPut(sender) == false) return;

                    if (CompleteTxtInPut() == false) return;

                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else if (sFuncValue == PosKey.MENU_KEY.CLEAR)
                {
                    if (((CsmPosEditBox)sender).ReadOnly == false) ((CsmPosEditBox)sender).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);
            }
        }
        #endregion Control Event
                        
        #region User Method
        /// <summary>
        /// 텍스트박스 입력 유효성 체크
        /// </summary>
        /// <param name="sender"></param>
        /// <returns></returns>
        private bool CheckTxtInPut(object sender)
        {
            try
            {
                if (sender == null || ((CsmPosEditBox)sender) == txtCashAmt)        
                {
                    if ((txtCashAmt.Value.Length == 0) || (txtCashAmt.Value.Length > 9))
                    {
                        //입력 금액 을 확인 하세요.
                        //WinManager.CosmosMessageBox(PosConst.MSG_BOX_TYPE.ERROR, POS_MESSAGE.ERROR.MSG_2048);
                        //#Rhee, 20171222 결제금액이 0원이고 미국 예약등록이면 0원으로도 결제가능하게 추가 start
                        if (m_cPosStatus.Base.CmpCd.Equals("PCUS") && m_cTrnStatus.Head.TradeKind == ItemConst.TRAN_KIND.UNDECIDED.RESERVATION_REG)
                        {
                            return true;
                        }
                        //#Rhee, 20171222 결제금액이 0원이고 미국 예약등록이면 0원으로도 결제가능하게 추가 end
                        return false;
                    }

                    //#20171123 결제금액이 1억 이상이면 원 결제금액으로 변경 start
                    if (m_cDataService.DoubleParse(txtCashAmt.Value) >= 100000000)
                    {
                        txtCashAmt.Value = m_cPosStatus.Global.NumericTOCurrency(m_cTrnStatus.Sale.RemainPayAmt);
                        return false;
                    }
                    //#20171123 결제금액이 1억 이상이면 원 결제금액으로 변경 end

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

        /// <summary>
        /// 텍스트박스 입력 완료 처리
        /// </summary>
        /// <returns></returns>
        private bool CompleteTxtInPut()
        {
            try
            {
                string sRet = UserCom.RST_ERR;

                sRet = m_cPaymentUs.SetPayment(new string[] { m_cDataService.DoubleParse(txtCashAmt.Value).ToString(), m_sPosMenuKey, "", "", "", "", "", "" });                
                if (sRet != UserCom.RST_OK) return false;
                
                return true;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                   System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            return false;
        }
        #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)
        {
            switch (sDevice)
            {
                case PosConst.OPOS_DEVICE.SCANNER:
                    this.Invoke(new EventHandler(OnScannerEvent));
                    break;
            }
        }

        /// <summary>
        /// Scanner Event
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnScannerEvent(object source, EventArgs e)
        {
            string sScanCode = m_cDevStatus.Scanner.DataLabel;
            ScannerEvent(sScanCode);            // 스캐너
        }

        
        /// <summary>
        /// 스캐너 입력 처리
        /// </summary>
        /// <param name="sScanCode">스캔데이터</param>
        private void ScannerEvent(string sScanCode)
        {
            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);
            }
        }
                
        #endregion DeviceEvent 관련

    }
    // grayber@20180115 인천공항 VIP 라운지 end
}
