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; 

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 당일 거래 수신
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Win
{
    public partial class frmSvr2Tran : 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_cDataService = null;
        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스
        private ISvr2Tran m_cSvr2Tran = null;
        private bool bNotDoubleClik = false;                                        // 더블 클릭 방지용

        /// <summary>
        /// 영수증 리스트
        /// </summary>
        private DataTable m_dtSearchList;
        /// <summary>
        /// 서버 거래 호출 여부
        /// </summary>
        private bool m_bServerTranCall = false;

        private string m_sMaxTranNo;                                                // 최종 거래번호
        /// <summary>
        /// 최종 거래번호
        /// </summary>
        public string SetMaxTranNo { set { this.m_sMaxTranNo = value; } }
      
        private string m_sMaxRegNo;                                                 // 최종 등록번호
        /// <summary>
        /// 최종 등록번호
        /// </summary>
        public string SetMaxRegNo { set { this.m_sMaxRegNo = value; } }

        /// <summary>
        /// 강제종료
        /// </summary>
        private bool m_bStop = false;

        /// <summary>
        /// 진행중
        /// </summary>
        private bool m_bStart = false;

        #endregion
        
        #region 생성자 & 소멸자
        /// <summary>
        /// 생성자
        /// </summary>
        public frmSvr2Tran()
        {
            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_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_cSvr2Tran = (ISvr2Tran)sManager.InitServiceInstance(ServiceLists.BSV_SALE.DLL, ServiceLists.BSV_SALE.SVR2TRAN); 
        }

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

        /// <summary>
        /// 폼디엑티브
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmSvr2Tran_Deactivate(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(null);
        }
        #endregion 생성자 & 소멸자
        
        #region 폼 컨트롤 초기화
        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            try
            {
                // 이미지 로딩 처리
                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);
                FormManager.MovePopUpForm(this, false, m_cPosStatus.Sale.ScreenSizeUser);

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

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0430);
                lblSaleDate.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0242);

                btnComplete.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0444);

                txtDateFrom.InputTypeFormat = m_cPosStatus.Global.m_stCultureMaster.strDatePattern;
                txtDateFrom.Text = m_cPosStatus.Global.DateToCulture(System.DateTime.Now.ToString("yyyyMMdd"));

                m_bServerTranCall = false;
                m_bStop = false;

                lblCount.Parent = this;
                lblCount.Text = "";
                pbWork.Value = 0;
                m_bStart = false;

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

                bNotDoubleClik = 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
            {
                if (m_bStart != false)
                {
                    if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0277) != true) return;
                }
                m_bStop = true;

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

                if (((Cosmos.UI.CsmButton)sender) == btnComplete)          
                {
                    sRet = GetTran2Svr();
                    if (sRet == 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);
                bNotDoubleClik = false;
            }
            bNotDoubleClik = false;
        }
        #endregion 

        #region 당일 거래 조회
        /// <summary>
        /// 당일 거래 조회
        /// </summary>
        /// <returns></returns>
        private string GetTran2Svr()
        {
            string sRet = UserCom.RST_ERR;
            int iMaxPercent = 0;  
            try
            {
                if (txtDateFrom.Visible == true && txtDateFrom.Value.Length != 8)
                {
                    WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0536));
                    txtDateFrom.Select();
                    txtDateFrom.SelectText();
                    return sRet;
                }

                string sDateFrom = m_cPosStatus.Global.CultureToDate(txtDateFrom.Text);

                // 최종 거래번호 조회
                sRet = m_cSvr2Tran.SearchLastTranNo(sDateFrom, m_cPosStatus.Base.PosNo, ref m_sMaxTranNo, ref m_sMaxRegNo);
                if (sRet != UserCom.RST_OK) return sRet;

                if (m_sMaxTranNo == "00000")
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0289);
                    return sRet;
                }

                // 현재 POS 거래번호와 서버에서 받은 거래번호가 같으면 Skip
                //if (CmUtil.DoubleSubtraction(m_cDataService.DoubleParse(m_cPosStatus.Base.TradeNo), 1) != m_cDataService.DoubleParse(m_sMaxTranNo) && m_cDataService.DoubleParse(m_sMaxTranNo) != 0)
                //{
                    lblCount.Visible = true;
                    pbWork.Visible = true;
                    pbWork.Minimum = 0;
                    iMaxPercent = CmUtil.IntParse(m_sMaxTranNo);
                    pbWork.Maximum = iMaxPercent;
                    pbWork.Value = 0;

                    for (int iLoop = 1; iLoop <= CmUtil.IntParse(m_sMaxTranNo); iLoop++)
                    {
                        m_bStart = true;
                        SetProgreeBar(iMaxPercent);

                        // 당일 거래 조회
                        sRet = m_cSvr2Tran.SearchServerTran(sDateFrom, m_cPosStatus.Base.PosNo, string.Format("{0:00000}", iLoop), "");
                        if (sRet == UserCom.RST_OK)
                        {
                            //m_cPosStatus.Base.TradeNo = string.Format("{0:00000}", iLoop);              // 거래번호 변경 설정
                            //m_cPosStatus.Base.RegNo = m_sMaxRegNo;                                      // 등록번호 변경 설정

                            //m_cDataService.SetMsgNoInc(true, false, true);                              // 거래번호 증가
                        }

                        if (m_bStop == true) break;
                    }

                    if (m_cPosStatus.Base.SaleDate != "" && m_cPosStatus.Base.SaleDate == sDateFrom)
                    {
                        if (CmUtil.LongParse(m_sMaxTranNo) >= CmUtil.LongParse(m_cPosStatus.Base.TradeNo))
                            m_cPosStatus.Base.TradeNo = string.Format("{0:00000}", CmUtil.LongParse(m_sMaxTranNo) + 1);             // 거래번호 변경 설정
                        if (CmUtil.LongParse(m_sMaxRegNo) >= CmUtil.LongParse(m_cPosStatus.Base.RegNo))
                            m_cPosStatus.Base.RegNo = string.Format("{0:00000}", CmUtil.LongParse(m_sMaxRegNo) + 1);                // 등록번호 변경 설정
                    }
                    if (m_cDataService.IntParse(m_sMaxTranNo) > 0 )
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0290);
                    }
                    
                //}
                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);
            }
            m_bStart = false;
            return sRet;
        }
        #endregion

        #region 상태 진행바
        /// <summary>
        /// 상태 진행바
        /// </summary>
        /// <param name="iMaxPercent"></param>
        private void SetProgreeBar(int iMaxPercent)
        {
            try
            {
                pbWork.Increment(1);

                double nPercent = ((double)pbWork.Value / (double)iMaxPercent) * 100;
                lblCount.Text = string.Format(MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0441), "(" + m_cPosStatus.Global.NumericToQuantity((int)pbWork.Value) + " / " + m_cPosStatus.Global.NumericToQuantity(iMaxPercent) + ")  " + Math.Round(nPercent, 0, MidpointRounding.AwayFromZero).ToString());

                lblCount.Refresh();

                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 (GetTran2Svr() == 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 

        #region 달력 클릭
        /// <summary>
        /// 달력 클릭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFromDate_Click(object sender, EventArgs e)
        {
            try
            {
                string sDate = WinBasic.ShowForm(new string[] { FormManager.FORM_CALENDAR });
                if (sDate != "") txtDateFrom.Text = m_cPosStatus.Global.DateToCulture(sDate);
            }
            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


    }
}
