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;

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/

namespace Cosmos.Win
{
    public partial class frmXChargeAmt : 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 IDataProcessUs m_cDataService = null;                               // 거래데이터 합계금액 계산 및 관리
        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스
        private IPaymentUs m_cCreaditCard = null;                                   // 신용카드 결제 클래스

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

        private string m_sFuncKey = "";                     // 결제 수단 기능키

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

        private PosOLEDevice.DelegateOlePos delegatePos;

        #endregion Variable

        #region 생성자 & 소멸자

        public frmXChargeAmt()
        {
            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;

#if !DEVICE_MSR_VER                       
            m_cCreaditCard = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.CREDITCARD);
#else
            m_cCreaditCard = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.MSRCARD);
#endif
            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);

            // OLE 입력 델리게이트 생성
            delegatePos = new PosOLEDevice.DelegateOlePos(OnDeviceEvent);
            
        }
        private void frmXChargeAmt_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 frmXChargeAmt_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 frmXChargeAmt_Activated(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(delegatePos);
        }

        private void frmXChargeAmt_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
            {
                // 이미지 로딩 처리
                //picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_S);

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

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0058);
                lblPayAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0066);

                if (m_sPayAmtIn != "")
                {
                    txtPayAmt.Value = m_cPosStatus.Global.NumericTOCurrency(m_cDataService.DoubleParse(m_sPayAmtIn));
                }
                else
                {
                    txtPayAmt.Value = m_cPosStatus.Global.NumericTOCurrency(m_cTrnStatus.Sale.RemainPayAmt);
                }

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

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

                txtPayAmt.Select();
                txtPayAmt.SelectText();

                if (m_sPayAmtIn != "") tmrAutoStart.Enabled = true;

                m_sPayAmtIn = "";

            }
            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)      // 금액 설정
                {
                    txtPayAmt.Value = ((UI.CsmButton)sender).Tag.ToString().Substring(1);
                    txtEditBox_EditBoxKeyDownEvent(txtPayAmt, PosKey.MENU_KEY.ENTER);
                }
                else
                {
                    txtPayAmt.Value = m_cPosStatus.Global.NumericTOCurrency(CmUtil.DoubleAdd(m_cDataService.DoubleParse(txtPayAmt.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);
            }
        }

        /// <summary>
        /// 선입력 금액 자동 승인 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tmrAutoStart_Tick(object sender, EventArgs e)
        {
            try
            {
                tmrAutoStart.Enabled = false;

                txtEditBox_EditBoxKeyDownEvent(txtPayAmt, PosKey.MENU_KEY.ENTER);
            }
            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) == txtPayAmt)        
                {
                    if (m_cDataService.DoubleParse(txtPayAmt.Value) == 0)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0038);
                        return false;
                    }

                    if (m_cDataService.DoubleParse(txtPayAmt.Value) > m_cTrnStatus.Sale.RemainPayAmt)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0039);
                        return false;
                    }


                    if (txtPayAmt.Value.Length > 10)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0035);    // 입력한 금액이 너무 큰 금액 입니다.
                        return false;
                    }

                    if (CmUtil.AmountCut(m_cDataService.DoubleParse(txtPayAmt.Value), CmUtil.IntParse(m_cPosStatus.Mst.PayRudDwLoc)) != m_cDataService.DoubleParse(txtPayAmt.Value))
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0036);    // 입력한 금액은 입력 불가 단위 입니다.
                        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 true;
        }

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

                sRet = m_cCreaditCard.SetPayment(new string[] { PosConst.XCHARGE.TRANSACTION, m_cDataService.DoubleParse(txtPayAmt.Value).ToString(), "", "", "", "" });
                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 관련

        

    }

}
