/*
 
 //#20171227 인천공항 포스연동 start, phj
 //#20171227 인천공항 포스연동 end, phj
 
 현금, 현금영수증, 카드 결제는 통합POS에서 진행하고
 나머지 결제수단은 SPCPOS를 이용한다.
 (수표의 경우 조회만 SPCPOS에서하고 결제는 통합POS에서 한다)
 
 1) 결제를 모두 SPCPOS에서 마감했을 경우, 마감 시점에 데이터 연동하고
 2) 일부 결제만 했을 경우, 결제 메뉴에서 기능키를 추가하여 해당 기능키 선택 시 데이터 연동한다. (INCHEON_AIRPORT = "99019")
 
 해당 폼(FORM_INCHEONAIRPORT = "SC9916") 열리기 전에 상품 리스트, 결제 리스트 보내고,
 결제조회 버튼 누르면 통합POS의 결제 데이터를 받아온다. 
 모든 것이 정상적일 때 결제완료 될 수 있지만 비정상 건은 일괄취소 후 다시 처음부터 실행한다.
 
*/

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 frmAirPortTran : 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 PosOLEDevice.DelegateOlePos delegatePos;

        //private IICReaderUs m_cDeviceICReader = null;
        //private ISignPadUs m_cDeviceSignPad = null;
        private IDataProcessUs m_cDataService = null;
        //private IPaymentUs m_cWeChatPay = null;
        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스
        private IAirPortTran m_cAirPortTran = null;
        //private PosOLEDevice.DelegateOlePos delegatePos;

        private string m_sPosMenuKey;
        public string SetPosMenuKey { set { this.m_sPosMenuKey = value; } } // POS 기능키
        
        private bool bNotDoubleClik = false; // 더블 클릭 방지용

        #endregion Variable

        #region 생성자 & 소멸자

        public frmAirPortTran()
        {
            InitializeComponent();

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

            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_cAirPortTran = (IAirPortTran)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.AIRPORT_TRAN);

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

        //#20180118 인천공항 결제마감창 바로 종료 못하도록 딜레이 처리 start
        private void frmAirPortTran_Shown(object sender, EventArgs e)
        {
            int iDelay = 3000;
            Delay(iDelay);
        }
        //#20180118 인천공항 결제마감창 바로 종료 못하도록 딜레이 처리 end

        private void frmAirPortTran_Deactivate(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(null);
        }
        #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 = "";

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1082); // "인천공항";// MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0042);
                padInPut.Visible = false;

                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, "");
            }
            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>
        private void btnProc_Click(object sender, EventArgs e)
        {
            string sRet = string.Empty;
            try
            {
                if (bNotDoubleClik) return;
                bNotDoubleClik = true;

                //닫기 
                if (((Cosmos.UI.CsmButton)sender) == btnExit)
                {
                    sRet = CloseClick();
                    bNotDoubleClik = false;
                    if (sRet != UserCom.RST_OK)
                    {
                        //this.DialogResult = DialogResult.Cancel;
                        //this.Close();
                    }
                    else
                    {
                        this.DialogResult = DialogResult.Cancel;
                        this.Close();
                    }
                }
                //결제요청
                else if (((Cosmos.UI.CsmButton)sender) == btnPayRequest)
                {
                    sRet = PayRequestClick();

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

                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                //결제조회
                else if (((Cosmos.UI.CsmButton)sender) == btnPaySearch)
                {
                    sRet = PaySearchClick();

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

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

                bNotDoubleClik = false;
            }
        }
        #endregion Control Event

        #region 닫기 클릭!
        private string CloseClick()
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                sRet = m_cAirPortTran.CloseClick();
                return sRet;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                            System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                            "Incheon Airport Pay CloseClick() - Error! " + ex.Message);
                return UserCom.RST_ERR;
            }
        }
        #endregion

        #region 결제조회 클릭!
        private string PaySearchClick()
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                sRet = m_cAirPortTran.PaySearchClick();
                return sRet;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                            System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                            "IncheonAirport Pay PaySearchClick() - Error! " + ex.Message);
                return UserCom.RST_ERR;
            } 
        }
        #endregion

        #region 결제요청 클릭!
        private string PayRequestClick()
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                sRet = m_cAirPortTran.PayRequestClick();
                return sRet;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                            System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                            "Incheon Airport Pay PayRequestClick() - Error! " + ex.Message);
                return UserCom.RST_ERR;
            } 
        }
        #endregion

        //#20180118 인천공항 결제마감창 바로 종료 못하도록 딜레이 처리 start
        #region 딜레이
        /// <summary>
        /// 딜레이
        /// </summary>
        /// <param name="MS"></param>
        /// <returns></returns>
        private void Delay(int MS)
        {
            DateTime ThisMoment = DateTime.Now;
            TimeSpan duration = new TimeSpan(0, 0, 0, 0, MS);
            DateTime AfterWards = ThisMoment.Add(duration);

            btnExit.Visible = false;

            while (AfterWards >= ThisMoment)
            {
                System.Windows.Forms.Application.DoEvents();
                ThisMoment = DateTime.Now;
            }

            btnExit.Visible = true;
        }
        #endregion
        //#20180118 인천공항 결제마감창 바로 종료 못하도록 딜레이 처리 end

        #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 관련

    }

}
