using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

//using Microsoft.PointOfService;

namespace Cosmos.Win
{
    public delegate void ProgressbarInitDelegate();
    public delegate void ProgressbarUpdateDelegate(string sMstId, int nProgress);

    public delegate void UpdateLabelDelegate(string sMsg);
    public delegate void ShowUrgentDelegate(bool bShow);
    public delegate void UpdateProgressBarStyleDelegate(ProgressBarStyle pbStyle);
    public delegate void StepUpProgressBarDelegate(int iStep);

    public delegate void PanelDelegate(bool bShow);

    public partial class frmSaleOpen : Form, IFormSaleOpenUs
    {
        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();                         // 거래정보 참조

        IMasterDownUs m_cMstDownSrv = null;
        //private IServiceUs cDeviceSrv = null;

        private static bool m_bIsOver = false;

        /// <summary>
        /// 마스터 수신일자
        /// </summary>
        private string m_sReqDateTime;                                               // 수신일자
        public string ReqDateTime { set { this.m_sReqDateTime = value; } get { return m_sReqDateTime; } }
        /// <summary>
        /// Background 마스터 수신일자
        /// </summary>
        private string m_sBGReqDateTime = string.Empty;
        public string BGReqDateTime { set { this.m_sBGReqDateTime = value; } get { return m_sBGReqDateTime; } }

        private string m_sMstDownOp = string.Empty;
        public string MstDownOp { set { this.m_sMstDownOp = value; } get { return this.m_sMstDownOp; } }

        /// <summary>
        /// POS 주변장비 체크 여부
        /// </summary>
        private string m_sPeripheralChk;
        public string PeripheralChk { set { this.m_sPeripheralChk = value; } get { return this.m_sPeripheralChk; } }

        /// <summary>
        /// 자동/수동 모드
        /// </summary>
        private string m_sManualMode;
        public string ManualMode { set { m_sManualMode = value; } get { return m_sManualMode; } }

        /// <summary>
        /// 체크할 주변장치 목록
        /// </summary>
        private string[] aDeviceList = new string[] {
                    "POSPRINTER",
                    "ICREADER",
                    "SIGNPAD",
                    "CATTERMINAL",
                    "SCALE",
                    "SCALEPOLEDISP",
                    "LABELPRINTER",
                    //"CASHDRAWER",
                    //"SCANNER",
                    //"MSR",
                    //"NETWORK"
                    };

        public frmSaleOpen()
        {
            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_cMstDownSrv = (IMasterDownUs)sManager.InitServiceInstance(ServiceLists.BSV_BASIC.DLL, ServiceLists.BSV_BASIC.MASTER_DOWN);

            InitControl();
        }

        protected override void OnShown(EventArgs e)
        {
            UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "");

            base.OnShown(e);

            InitControl();

            // 통신서버 IP가 설정되어 있지 않으면 마스터 다운로드 Skip 처리
            // 2016/10/19
            if (m_cPosStatus.Base.CommSvrIp.Trim() != "" && m_cPosStatus.Base.MasterDown == "1")
            {
                System.Threading.Thread worker = new System.Threading.Thread(new System.Threading.ThreadStart(SaleOpenProcess));
                worker.Start();
            }
            else
            {
                m_bIsOver = true;
            }

            tmrCheckStatus.Enabled = true;
        }
        private void frmSaleOpen_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 + "()", "");
        }

        private void InitControl()
        {
            try
            {
                if (m_cPosStatus.Sale.ScreenSizeUser == 1024)
                {
                    // 이미지 로딩 처리
                    //picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_FULL_SIZE);
                    //this.Size = new Size(1024, 696);
                    //this.Location = new Point(0, 50);
                    if (m_sManualMode == "K")
                        FormManager.SetControlSize(picBack, 0, 0, 1024, 696);
                    else
                        FormManager.SetControlSize(picBack, 0, 0, 1024, 768);
                    FormManager.SetControlSize(this, 0, 50, picBack.Size.Width, picBack.Size.Height);

                    FormManager.SetControlSize(this.progressBar1, 30, 332, 963, 30);
                    FormManager.SetControlSize(this.btnCancel, 893, 365, 100, 40);
                    FormManager.SetControlSize(this.lblStatusMsg, 38, 307, 214, 18);
                    FormManager.SetControlSize(this.pnlDeviceCheck, 30, 385, 963, 163);
                    FormManager.SetControlSize(this.lblScannerStatus, 661, 103, 96, 28);
                    FormManager.SetControlSize(this.lblMSRStatus, 851, 103, 96, 28);
                    FormManager.SetControlSize(this.lblCashDrawerStatus, 472, 99, 96, 28);
                    FormManager.SetControlSize(this.lblLabelPrinterStatus, 283, 99, 96, 28);
                    FormManager.SetControlSize(this.lblScalePoleDispStatus, 95, 99, 96, 28);
                    FormManager.SetControlSize(this.lblScaleStatus, 851, 36, 96, 28);
                    FormManager.SetControlSize(this.lblCatTerminalStatus, 661, 35, 96, 28);
                    FormManager.SetControlSize(this.lblSignPadStatus, 472, 35, 96, 28);
                    FormManager.SetControlSize(this.lblCardReaderStatus, 283, 35, 96, 28);
                    FormManager.SetControlSize(this.lblPrinterStatus, 95, 35, 96, 28);
                    FormManager.SetControlSize(this.label10, 766, 12, 1, 140);
                    FormManager.SetControlSize(this.label8, 8, 150, 950, 1);
                    FormManager.SetControlSize(this.label7, 8, 81, 950, 1);
                    FormManager.SetControlSize(this.label6, 9, 11, 950, 1);
                    FormManager.SetControlSize(this.label5, 958, 11, 1, 140);
                    FormManager.SetControlSize(this.label4, 576, 12, 1, 140);
                    FormManager.SetControlSize(this.label3, 199, 11, 1, 140);
                    FormManager.SetControlSize(this.label1, 388, 12, 1, 140);
                    FormManager.SetControlSize(this.label2, 8, 11, 1, 140);
                    FormManager.SetControlSize(this.lblMSR, 769, 99, 75, 32);
                    FormManager.SetControlSize(this.lblScanner, 579, 99, 75, 32);
                    FormManager.SetControlSize(this.lblCashDrawer, 391, 99, 75, 32);
                    FormManager.SetControlSize(this.lblLabelPrinter, 202, 99, 75, 32);
                    FormManager.SetControlSize(this.lblScalePoleDisp, 11, 99, 75, 32);
                    FormManager.SetControlSize(this.lblScale, 769, 31, 75, 32);
                    FormManager.SetControlSize(this.lblCatTerminal, 579, 32, 75, 32);
                    FormManager.SetControlSize(this.lblSignPad, 391, 31, 75, 32);
                    FormManager.SetControlSize(this.lblCardReader, 202, 32, 75, 32);
                    FormManager.SetControlSize(this.lblPrinter, 11, 31, 75, 32);
                    FormManager.SetControlSize(this.lblPercent, 933, 305, 56, 18);
                    FormManager.SetControlSize(this.lblUrgent, 41, 277, 221, 21);
                    FormManager.SetControlSize(this.lblTitleMsg1, 34, 62, 113, 39);
                    FormManager.SetControlSize(this.lblTitleMsg2, 34, 114, 250, 39);
                    FormManager.SetControlSize(this.lblTitleMsg3, 34, 166, 297, 53);
                }
                else
                {
                    // 이미지 로딩 처리
                    //picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_800X600);
                    FormManager.SetControlSize(picBack, 0, 0, 800, 600);
                    FormManager.SetControlSize(this, 0, 0, picBack.Size.Width, picBack.Size.Height);
                    FormManager.SetControlSize(this.progressBar1, 30, 332, 739, 30);
                    FormManager.SetControlSize(this.btnCancel, 893, 365, 100, 40);
                    FormManager.SetControlSize(this.lblStatusMsg, 38, 307, 214, 18);
                    FormManager.SetControlSize(this.pnlDeviceCheck, 30, 385, 739, 163);
                    FormManager.SetControlSize(this.lblScannerStatus, 526, 103, 51, 28);
                    FormManager.SetControlSize(this.lblMSRStatus, 671, 103, 51, 28);
                    FormManager.SetControlSize(this.lblCashDrawerStatus, 382, 99, 51, 28);
                    FormManager.SetControlSize(this.lblLabelPrinterStatus, 238, 99, 51, 28);
                    FormManager.SetControlSize(this.lblScalePoleDispStatus, 95, 99, 51, 28);
                    FormManager.SetControlSize(this.lblScaleStatus, 671, 36, 51, 28);
                    FormManager.SetControlSize(this.lblCatTerminalStatus, 526, 35, 51, 28);
                    FormManager.SetControlSize(this.lblSignPadStatus, 382, 35, 51, 28);
                    FormManager.SetControlSize(this.lblCardReaderStatus, 238, 35, 51, 28);
                    FormManager.SetControlSize(this.lblPrinterStatus, 95, 35, 51, 28);
                    FormManager.SetControlSize(this.label10, 586, 12, 1, 140);
                    FormManager.SetControlSize(this.label8, 8, 150, 726, 1);
                    FormManager.SetControlSize(this.label7, 8, 81, 726, 1);
                    FormManager.SetControlSize(this.label6, 8, 11, 726, 1);
                    FormManager.SetControlSize(this.label5, 733, 11, 1, 140);
                    FormManager.SetControlSize(this.label4, 441, 12, 1, 140);
                    FormManager.SetControlSize(this.label3, 154, 11, 1, 140);
                    FormManager.SetControlSize(this.label1, 298, 12, 1, 140);
                    FormManager.SetControlSize(this.label2, 8, 11, 1, 140);
                    FormManager.SetControlSize(this.lblMSR, 589, 99, 75, 32);
                    FormManager.SetControlSize(this.lblScanner, 444, 99, 75, 32);
                    FormManager.SetControlSize(this.lblCashDrawer, 301, 99, 75, 32);
                    FormManager.SetControlSize(this.lblLabelPrinter, 157, 99, 75, 32);
                    FormManager.SetControlSize(this.lblScalePoleDisp, 11, 99, 75, 32);
                    FormManager.SetControlSize(this.lblScale, 589, 31, 75, 32);
                    FormManager.SetControlSize(this.lblCatTerminal, 444, 32, 75, 32);
                    FormManager.SetControlSize(this.lblSignPad, 301, 31, 75, 32);
                    FormManager.SetControlSize(this.lblCardReader, 157, 32, 75, 32);
                    FormManager.SetControlSize(this.lblPrinter, 11, 31, 75, 32);
                    FormManager.SetControlSize(this.lblPercent, 709, 305, 56, 18);
                    FormManager.SetControlSize(this.lblUrgent, 41, 277, 221, 21);
                    FormManager.SetControlSize(this.lblTitleMsg1, 34, 62, 113, 39);
                    FormManager.SetControlSize(this.lblTitleMsg2, 34, 114, 250, 39);
                    FormManager.SetControlSize(this.lblTitleMsg3, 34, 166, 297, 53);
                }

                this.BackColor = Color.FromArgb(240, 248, 253);
                //this.Size = new Size(1024, 768);
                //this.Location = new Point(0, 0);

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

                picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.LODING_BACKGROUND);

                progressBar1.Minimum = 0;
                progressBar1.Maximum = 100;
                progressBar1.Value = 0;
                lblStatusMsg.Text = string.Empty;
                lblPercent.Text = string.Empty;

                pnlDeviceCheck.Visible = false;

                btnCancel.Visible = true;

                m_bIsOver = false;

                // Device Check Init
                lblPrinterStatus.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.DEVICE_WAIT);
                //lblScannerStatus.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.DEVICE_WAIT);
                lblCardReaderStatus.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.DEVICE_WAIT);
                lblCatTerminalStatus.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.DEVICE_WAIT);
                //lblCashDrawerStatus.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.DEVICE_WAIT);
                lblScaleStatus.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.DEVICE_WAIT);
                lblScalePoleDispStatus.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.DEVICE_WAIT);
                lblSignPadStatus.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.DEVICE_WAIT);
                lblLabelPrinterStatus.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.DEVICE_WAIT);
                //lblMSRStatus.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.DEVICE_WAIT);

                // 주변장치
                lblPrinter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0849);
                //lblScanner.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0850);
                lblCardReader.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0851);
                lblSignPad.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0097);
                lblLabelPrinter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0853);
                lblCatTerminal.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0854);
                lblScale.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0855);
                lblScalePoleDisp.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0695);
                //lblMSR.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0857);
                //lblCashDrawer.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0693);
                
                lblTitleMsg1.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1011);
                lblTitleMsg2.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1012);
                lblTitleMsg3.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1013);

                lblUrgent.Visible = false;

                if (MstDownOp == PosConst.MASTER_DOWN_OP.ALL)
                {
                    ReqDateTime = m_cPosStatus.Mst.ComplexShopType == "0" ? PosConst.BEGINNING_MST_DOWN_DATE : PosConst.BEGINNING_COMPLEX_SHOP_MST_DOWN_DATE;
                    BGReqDateTime = m_cPosStatus.Mst.ComplexShopType == "0" ? PosConst.BEGINNING_MST_DOWN_DATE : PosConst.BEGINNING_COMPLEX_SHOP_MST_DOWN_DATE;
                }
                else if(MstDownOp == PosConst.MASTER_DOWN_OP.CHANGED)
                {
                    ReqDateTime = m_cPosStatus.Base.MstDownDate;
                    BGReqDateTime = m_cPosStatus.Base.MstBatchDownDate;
                }
                else if(MstDownOp == PosConst.MASTER_DOWN_OP.ALL_CAMPAIGN)
                {
                    ReqDateTime = m_cPosStatus.Mst.ComplexShopType == "0" ? PosConst.BEGINNING_MST_DOWN_DATE : PosConst.BEGINNING_COMPLEX_SHOP_MST_DOWN_DATE;
                    BGReqDateTime = m_cPosStatus.Mst.ComplexShopType == "0" ? PosConst.BEGINNING_MST_DOWN_DATE : PosConst.BEGINNING_COMPLEX_SHOP_MST_DOWN_DATE;
                }
            }
            catch(Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        public void SetPanelShowFlag(bool bShow)
        {
            try
            {
                if (InvokeRequired)
                {
                    PanelDelegate pnDelegate = new PanelDelegate(SetPanelShowFlag);
                    this.Invoke(pnDelegate, new object[] { bShow });
                }
                else
                {
                    pnlDeviceCheck.Visible = bShow;
                    btnCancel.Visible = !bShow;
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        #region ProgressBar 제어
        /// <summary>
        /// ProgressBar 초기화
        /// </summary>
        public void InitProgressbar()
        {
            try
            {
                if (InvokeRequired)
                {
                    ProgressbarInitDelegate pbUpdDelegate = new ProgressbarInitDelegate(InitProgressbar);
                    this.Invoke(pbUpdDelegate, new object[] { });
                }
                else
                {
                    progressBar1.Value = 0;
                    progressBar1.Maximum = 100;

                    lblStatusMsg.Text = string.Empty;

                    Application.DoEvents();

                    this.Refresh();
                }
            }
            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>
        /// ProgressBar 진행 상태 갱신
        /// </summary>
        /// <param name="sMstId">상태메시지</param>
        /// <param name="nProgress">진행률 증가분</param>
        public void SaleOpenProgress(string sMstId, int nProgress)
        {
            try
            {
                if(InvokeRequired)
                {
                    ProgressbarUpdateDelegate pbUpdDelegate = new ProgressbarUpdateDelegate(SaleOpenProgress);
                    this.Invoke(pbUpdDelegate, new object[] { sMstId, nProgress });
                }
                else
                {
                    if (progressBar1.Value + nProgress <= progressBar1.Maximum)
                    {
                        progressBar1.Value += nProgress;
                    }
                    else
                    {
                        progressBar1.Value = progressBar1.Maximum;
                    }

                    if (sMstId.Length > 0)
                    {
                        lblStatusMsg.Text = sMstId;
                    }

                    lblPercent.Text = GetProgressPercentage();

                    lblPercent.Update();
                    progressBar1.Update();
                    //this.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);
            }
        }

        /// <summary>
        /// 상태메시지 변경
        /// </summary>
        /// <param name="sMsg"></param>
        public void SetLabelMsg(string sMsg)
        {
            try
            {
                if(InvokeRequired)
                {
                    UpdateLabelDelegate lblDelegate = new UpdateLabelDelegate(SetLabelMsg);
                    this.Invoke(lblDelegate, new object[] { sMsg });
                }
                else
                {
                    lblStatusMsg.Text = sMsg;

                    lblStatusMsg.Refresh();
                }
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
        }

        public void ShowUrgentLabel(bool bShow)
        {
            try
            {
                if (InvokeRequired)
                {
                    ShowUrgentDelegate lblDelegate = new ShowUrgentDelegate(ShowUrgentLabel);
                    this.Invoke(lblDelegate, new object[] { bShow });
                }
                else
                {
                    lblUrgent.Visible = bShow;

                    lblUrgent.Refresh();
                }
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
        }

        /// <summary>
        /// ProgressBar Style 변경
        /// </summary>
        /// <param name="pbStyle"></param>
        public void SetProgressbarStyle(ProgressBarStyle pbStyle)
        {
            try
            {
                if (InvokeRequired)
                {
                    UpdateProgressBarStyleDelegate pbDelegate = new UpdateProgressBarStyleDelegate(SetProgressbarStyle);
                    this.Invoke(pbDelegate, new object[] { pbStyle });
                }
                else
                {
                    if(pbStyle == ProgressBarStyle.Marquee)
                    {
                        lblPercent.Visible = false;
                    }
                    else
                    {
                        progressBar1.Value = 0;
                        lblPercent.Text = GetProgressPercentage();
                        lblPercent.Visible = true;
                    }

                    progressBar1.Style = pbStyle;
                    
                    progressBar1.Refresh();
                    lblPercent.Refresh();
                }
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
        }

        /// <summary>
        /// ProgressBar 진행 상태 갱신
        /// </summary>
        /// <param name="iStep">증가값</param>
        public void ProgressProgressBar(int iStep)
        {
            try
            {
                if (InvokeRequired)
                {
                    StepUpProgressBarDelegate pbDelegate = new StepUpProgressBarDelegate(ProgressProgressBar);
                    this.Invoke(pbDelegate, new object[] { iStep });
                }
                else
                {
                    progressBar1.Value += iStep;

                    lblPercent.Text = GetProgressPercentage();
                                        
                    progressBar1.Refresh();
                    lblPercent.Refresh();
                }
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
        }

        /// <summary>
        /// ProgressBar 진행율을 가져 옴
        /// </summary>
        /// <returns></returns>
        private string GetProgressPercentage()
        {
            string sPercent = string.Empty;
            try
            {
                int percent = (int)(((double)progressBar1.Value / (double)progressBar1.Maximum) * 100);
                sPercent = percent.ToString() + "%";
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
            return sPercent;
        }
        #endregion

        private void SaleOpenProcess()
        {
            bool bIsUrgent = false;
            string sReturn = UserCom.RST_ERR;
            //string sReqDateTime = string.Empty;
            //Hashtable htMasterList = new Hashtable();
            //Hashtable htComplexStoreMstList = new Hashtable();
            Hashtable htMasterList = null;
            Hashtable htComplexStoreMstList = null;

            DataTable dtData = null;
            try
            {
                // 주변장치 표시 창을 비활성화.
                SetPanelShowFlag(false);

                string sToBeMstDownTime = DateTime.Now.ToString("yyyyMMddHHmmss");

                //테이블 변경사항에 대한 적용(추후 없어질 수도 있음)

                // 일반 마스터 정보 Down
                int iSeq = 0;
                dtData = m_cMstDownSrv.SelectEmergencyMasterList();
                if(MstDownOp == PosConst.MASTER_DOWN_OP.ALL_CAMPAIGN)
                {
                    ShowUrgentLabel(false);

                    // 캠페인 관련 마스터만 받는다.
                    htMasterList = MasterListManager.GetCampaignMaster();
                }
                else if (MstDownOp == PosConst.MASTER_DOWN_OP.ALL || (dtData == null || dtData.Rows.Count == 0))
                {
                    ShowUrgentLabel(false);

                    if (m_cPosStatus.Base.PosType == PosConst.POS_TYPE.DEFERRED_PAYMENT && m_cPosStatus.Base.PosCommunicationType == PosConst.MAIN_POS_DIV.SUB_POS)
                    {
                        // 후불SUB POS 의 경우에 SUB POS 전용 마스터만 받는다.
                        htMasterList = MasterListManager.GetSubPosMaster();
                    }
                    else
                    {
                        // 그 이외라면 일반 마스터를 받는다.
                        htMasterList = MasterListManager.GetNormalMaster();
                    }
                }
                else
                {
                    bIsUrgent = true;
                    ShowUrgentLabel(true);

                    foreach(DataRow dr in dtData.Rows)
                    {
                        htMasterList.Add(iSeq++, dr["MST_TBL_ID"].ToString());
                    }

                    m_cMstDownSrv.UpdateEmergencyMasterList();
                }

                sReturn = m_cMstDownSrv.Execute(new object[] { htMasterList, ReqDateTime, BGReqDateTime });
                if(sReturn != UserCom.RST_OK)
                {
                    UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                         System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                         System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                         System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                         "Failed specified master download and insert.");
                    return;
                }


                // 선불 이거나 후불 MAIN POS 의 경우에만 복합매장 정보를 추가로 다운로드
                if (m_cPosStatus.Base.PosType != PosConst.POS_TYPE.DEFERRED_PAYMENT ||
                   (m_cPosStatus.Base.PosType == PosConst.POS_TYPE.DEFERRED_PAYMENT && m_cPosStatus.Base.PosCommunicationType == PosConst.MAIN_POS_DIV.MAIN_POS))
                {
                    // 복합매장점포일 경우 복합매장 정보를 추가로 Down
                    iSeq = 0;
                    dtData = (DataTable)m_cMstDownSrv.GetData(new string[] { m_cPosStatus.Base.CmpCd, m_cPosStatus.Base.StoreNo });
                    if (dtData != null && dtData.Rows.Count > 0)
                    {
                        htComplexStoreMstList = MasterListManager.GetComplexStorMaster();

                        foreach (DataRow dr in dtData.Rows)
                        {
                            sReturn = m_cMstDownSrv.Execute(new object[] { htComplexStoreMstList, ReqDateTime, BGReqDateTime, CmUtil.GetDataRowStr(dr, "SUB_BRAND_CD"), CmUtil.GetDataRowStr(dr, "SUB_STOR_CD") });
                            if (sReturn != UserCom.RST_OK)
                            {
                                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                                     "Failed Complex store specified master download and insert.");
                                return;
                            }
                        }
                    }
                }

                // 마스터 다운 일자 갱신
                if (bIsUrgent == false && MstDownOp != PosConst.MASTER_DOWN_OP.ALL_CAMPAIGN)
                {
                    m_cPosStatus.Base.MstDownDate = sToBeMstDownTime;
                    m_cPosStatus.Base.MstBatchDownDate = sToBeMstDownTime;

                    // PosSaleInfo.ini 저장
                    IServiceUs cSaveConfigInfo = (IServiceUs)sManager.InitServiceInstance(ServiceLists.BSV_OPEN_CLOSE.DLL, ServiceLists.BSV_OPEN_CLOSE.SAVE_CONFIGINFO);
                    string sRet = cSaveConfigInfo.Execute(new string[] { PosConst.INI_FILE_NAME.PosSaleInfo });
                }
            }
            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;
            }
            finally
            {
                m_bIsOver = true;
            }
            return;
        }

        // Device Check
        private bool DeviceCheck()
        {
            string sRet = UserCom.RST_ERR;

            // 프로그래스바 초기화
            //progressBar1.Value = 0;
            InitProgressbar();
            // 주변장치 표시 창 활성화 한다.
            //pnlDeviceCheck.Visible = true;
            SetPanelShowFlag(true);

            try
            {
                // 주변장비 체크 서비스 인스턴스 활성화
                IServiceUs cDeviceSrv = (IServiceUs)sManager.InitServiceInstance(ServiceLists.BSV_OPEN_CLOSE.DLL, ServiceLists.BSV_OPEN_CLOSE.DEVICE_SERVICE);

                // 주변장치 목록 체크
                CmMessage msgSend = CmMessage.MakeMessageFromFile(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosDevice);

                for (int i = 0; i < aDeviceList.Length; i++)
                {
                    //string sDeviceName = msgSend.MessageKeyList[i].ToString();
                    string sDeviceName = aDeviceList[i].ToString();

                    if (msgSend.GetMessage(sDeviceName).GetMessageValue("UseFlag") != PosConst.DEVICE_USE_FLAG.YES_USE)
                    {
                        DisplayDeviceStatus(sDeviceName, UserCom.RST_IGNORE);
                        SaleOpenProgress(sDeviceName, (100 / aDeviceList.Length));
                    }
                    else
                    {
                        sRet = cDeviceSrv.Execute(new string[] { sDeviceName });
                        DisplayDeviceStatus(sDeviceName, sRet);
                        SaleOpenProgress(sDeviceName, (100 / aDeviceList.Length));
                    }
                }


                // Network
                sRet = SetServerSysDateTime();
                DisplayDeviceStatus("NETWORK", sRet);
            }
            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;
            }

            return true;
        }

        #region 서버 시간 동기화 - 서버 접속 체크용으로 사용
        /// <summary>
        /// 서버 시간 동기화
        /// </summary>
        public string SetServerSysDateTime()
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                // 서버 시간 동기화
                ISvr2Tran m_cSvr2Tran = (ISvr2Tran)sManager.InitServiceInstance(ServiceLists.BSV_SALE.DLL, ServiceLists.BSV_SALE.SVR2TRAN);
                sRet = m_cSvr2Tran.ServerSysDateTime();
            }
            catch (Exception ex)
            {
            }
            return sRet;
        }
        #endregion 

        public void DisplayDeviceStatus(string pDeviceName, string pStatus)
        {
            try
            {
                switch (pDeviceName)
                {
                    case "POSPRINTER":
                        SetImage(this.lblPrinterStatus, pStatus);
                        m_cPosStatus.Base.OlePosPrinterStatus = pStatus;
                        //lblPrinterStatus.Text = "OK";
                        break;
                    //case "SCANNER":
                    //    SetImage(this.pnlScanner, lblScannerStatus, pStatus);
                    //    m_cPosStatus.Base.OlePosScannerStatus = pStatus;
                    //    break;
                    case "ICREADER":
                        SetImage(this.lblCardReaderStatus, pStatus);
                        m_cPosStatus.Base.OlePosICReaderStatus = pStatus;
                        break;
                    case "CATTERMINAL":
                        SetImage(this.lblCatTerminalStatus, pStatus);
                        m_cPosStatus.Base.OlePosCATStatus = pStatus;
                        break;
                    case "CASHDRAWER":
                        SetImage(this.lblCashDrawerStatus, pStatus);
                        m_cPosStatus.Base.OlePosCashDrawerStatus = pStatus;
                        break;
                    case "SCALE":
                        SetImage(this.lblScaleStatus, pStatus);
                        m_cPosStatus.Base.OlePosScaleStatus = pStatus;
                        break;
                    case "SIGNPAD":
                        SetImage(this.lblSignPadStatus, pStatus);
                        m_cPosStatus.Base.OlePosSignPadStatus = pStatus;
                        break;
                    case "LABELPRINTER":
                        SetImage(this.lblLabelPrinterStatus, pStatus);
                        m_cPosStatus.Base.OlePosLabelPrinterStatus = pStatus;
                        break;
                    case "SCALEPOLEDISP":
                        SetImage(this.lblScalePoleDispStatus, pStatus);
                        m_cPosStatus.Base.OlePosScalePoleDispStatus = pStatus;
                        break;
                    //case "MSR":
                    //    SetImage(this.pnlMSR, lblMSRStatus, pStatus);
                    //    m_cPosStatus.Base.OlePosMsrStatus = pStatus;
                    //    break;
                    case "NETWORK":
                        m_cPosStatus.Base.OlePosNetworkStatus = pStatus;
                        break;
                    case "":
                        break;
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        private void SetImage(Label lStatus, string sStatus)
        {
            Image imgBack = null;
            string sTextStatus = UserCom.RST_ERR;
            if (sStatus == UserCom.RST_OK)//OK
            {
                imgBack = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.DEVICE_OK);
                sTextStatus = "OK";
            }
            else if (sStatus == UserCom.RST_ERR)//NG
            {
                imgBack = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.DEVICE_NG);
                sTextStatus = "NG";
            }
            else if (sStatus == UserCom.RST_IGNORE) //PASS (미사용)
            {
                imgBack = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.DEVICE_PASS);
                sTextStatus = "PASS";
            }

            lStatus.Image = imgBack;
            lStatus.Text = sTextStatus;
        }

        private void tmrCheckStatus_Tick(object sender, EventArgs e)
        {
            try
            {
                tmrCheckStatus.Enabled = false;

                if (m_bIsOver == true)
                {
                    

                    #region ### 주변장비체크 ###
                    if (PeripheralChk == PosConst.POS_PERIPHERAL_CHECK.CHECK)
                    {
                        DeviceCheck();
                    }
                    #endregion
                    this.Close();
                    return;
                }

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

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

                double nPercent = ((double)progressBar1.Value / (double)iMaxPercent) * 100;

                lblStatusMsg.Visible = true;
                lblStatusMsg.Text = string.Format(sMsgCD + "{0}%", Math.Round(nPercent, 0, MidpointRounding.AwayFromZero).ToString());
                lblStatusMsg.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

        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                m_cMstDownSrv.IsAborted = 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);
            }
        }

        


    }
}
