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 System.Threading; 

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 결락 재전송
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Win
{
    public partial class frmMissTranCheck : Form
    {
        #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 PosOLEDevice.DelegateOlePos delegatePos; 

        private IDataProcessUs m_cDataSrv = null;
        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스
        private ISvr2Tran m_cSvr2Tran = null; 
        #endregion
        
        #region 생성자 & 소멸자
        /// <summary>
        /// 생성자
        /// </summary>
        public frmMissTranCheck()
        {
            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_cDataSrv = (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_cSvr2Tran = (ISvr2Tran)sManager.InitServiceInstance(ServiceLists.BSV_SALE.DLL, ServiceLists.BSV_SALE.SVR2TRAN); 
        }

        /// <summary>
        /// 폼로드
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmMissTranCheck_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();
        }

        /// <summary>
        /// 폼클로즈
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmMissTranCheck_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>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmMissTranCheck_Activated(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(delegatePos);
        }

        /// <summary>
        /// 폼디엑티브
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmMissTranCheck_Deactivate(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(null);
        }
        #endregion 생성자 & 소멸자
        
        #region 폼 컨트롤 초기화
        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            try
            {
                // 이미지 로딩 처리
                picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_MSGBOX);

                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);
                FormManager.MovePopUpForm(this, false, m_cPosStatus.Sale.ScreenSizeUser);

                btnExit.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BTN_CLOSE);
                if (btnExit.Image != null) btnExit.Text = "";

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0711);
                lblUpdateInfo.Text = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0623);

                lblCount.Visible = false;
                pbWork.Visible = false; 

                tmStart.Enabled = 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 버튼 입력 처리
        private void btnExit_Click(object sender, EventArgs e)
        {
            try
            { 
                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

        #region 결락 거래번호 조회
        /// <summary>
        /// 결락 거래번호 조회
        /// </summary>
        /// <returns></returns>
        private string GetMissTran()
        {
            string sRet = UserCom.RST_ERR; 
            string sMissTranNo = "";
            string[] aMissTranNo = null;
            bool bMissTranNo = false;
            int iCount = 0;

            string sReTry = "";

            try
            {
            ReTry:

                if (m_cPosStatus.Base.MissChkPort < 0) return UserCom.RST_OK; ;

                iCount++;
                //for (int iTranDiv = 0; iTranDiv <= 1; iTranDiv++)
                for (int iTranDiv = 0; iTranDiv <= 0; iTranDiv++)       // ETC_SALE_HEADER는 결락 체크 제외  (거래복구후 재수신된 데이터에서 결락 체크 불가능해서 제외)
                {
                    // 결락 거래번호 조회
                    sReTry = (iCount > 0 ? "(" + iCount + "/3)" : "");
                    lblUpdateInfo.Text = sReTry + MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0623);

                    string sRegNo = iTranDiv == 1 ? m_cPosStatus.Base.RegNo : m_cPosStatus.Base.TradeNo;

                    sRet = m_cSvr2Tran.SearchMissTran(m_cPosStatus.Base.SaleDate, m_cPosStatus.Base.PosNo, iTranDiv.ToString(), sRegNo, ref sMissTranNo);
                    if (sRet == UserCom.RST_OK && sMissTranNo.Trim() != "" )
                    {
                        lblUpdateInfo.Text = sReTry + MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0624);

                        aMissTranNo = sMissTranNo.Split(new string[] { "|" }, StringSplitOptions.None);
                        for (int iLoop = 0; iLoop < aMissTranNo.Length; iLoop++)
                        {
                            if (aMissTranNo[iLoop].Trim() !=  "" && aMissTranNo[iLoop].Trim() != "00000")
                            {
                                // 결락 거래번호 재전송 설정
                                sRet = m_cSvr2Tran.SetMissTran(iTranDiv.ToString(), m_cPosStatus.Base.CmpCd, m_cPosStatus.Base.StoreNo, m_cPosStatus.Base.SaleDate, m_cPosStatus.Base.PosNo, aMissTranNo[iLoop]);

                                // 상태표시
                                SetProgreeBar(lblCount, pbWork, iLoop + 1, aMissTranNo.Length);

                                bMissTranNo = true;
                            }
                        }
                    }
                }

                if (bMissTranNo == true)
                {
                    Thread.Sleep(400);

                    // 결락 건수 존재시 3회 재시도
                    if (iCount <= 3) goto ReTry;

                    // {0}회 재시도 하였으나 결락이 존재합니다. 결락전송을 재시도 하시겠습니까?
                    if (WinManager.QuestionMessage(string.Format(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0625), iCount - 1)) == true)
                    {
                        iCount = 0;
                        goto ReTry;
                    }
                }
                else
                {
                    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 상태 진행바
        /// <summary>
        /// 상태 진행바
        /// </summary>
        /// <param name="iMaxPercent"></param>
        private void SetProgreeBar(Label lblLabel, ProgressBar pbProgreeBar, long nValue, long nMaxValue)
        {
            try
            {
                double nPercent = CmUtil.DoubleMultiplication(CmUtil.DoubleDivision(nValue, nMaxValue), 100);

                pbProgreeBar.Visible = true;
                pbProgreeBar.Value = (int)Math.Round(nPercent, 0, MidpointRounding.AwayFromZero);
                pbProgreeBar.Update();

                lblLabel.Visible = true;
                lblLabel.Text = string.Format(MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0441) + "  (" + m_cPosStatus.Global.NumericToQuantity(nValue) + " / " + m_cPosStatus.Global.NumericToQuantity(nMaxValue) + ")", Math.Round(nPercent, 0, MidpointRounding.AwayFromZero).ToString());
                lblLabel.Update();

                this.Update();
                Application.DoEvents();
            }
            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 tmStart_Tick(object sender, EventArgs e)
        {
            try
            {
                tmStart.Enabled = false;

                if (GetMissTran() == UserCom.RST_OK)
                {
                    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);
            }
        }
        #endregion 
    }
}
