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 Cosmos.UI;

namespace Cosmos.Win
{
    /// <summary>
    /// 주방프린터 상태 체크
    /// </summary>
    public partial class frmCheckKtchPrinter : Form
    {
        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object(객체)
        private PosStatus m_cPosStatus = new PosStatus();                           // 기본정보 참조

        private IMasterUs m_cMstService = null;                                     // 마스터 인터페이스

        private bool isBusy = false; 
        private DataTable m_dtDevice = null; 

        /// <summary>
        /// 생성자  
        /// </summary>
        public frmCheckKtchPrinter()
        {
            InitializeComponent();

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

            m_cPosStatus = (PosStatus)StateObject.POS;      //POS 기본정보

            m_cMstService = (IMasterUs)sManager.InitServiceInstance(ServiceLists.ASV_MASTER.DLL, ServiceLists.ASV_MASTER.POS_MASTER);
        }

        private void Form_Load(object sender, EventArgs e)
        {
            try
            {
                UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "");
                InitControls();
                InitializeGrid();
                
                this.isBusy = false;
                this.Tag = "START";
            }
            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 Form_Activated(object sender, EventArgs e)
        {
            try
            {
                if (this.Tag.ToString() == "START")
                {
                    this.Refresh();
                    this.Tag = string.Empty;
                    CheckKpsStatus();
                }
            }
            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 Form_Closing(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 InitControls()
        {
            try
            {
                this.picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_S);
                this.picBack.Location = new Point(0, 0);
                this.picBack.SendToBack(); 
                this.Size = this.picBack.Size = this.picBack.Image.Size;
                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);

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0312);

                btnEnter.BackColor = CmUtil.GetColorToString(m_cPosStatus.ScnMst.ThemeColor);
                btnExit.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BTN_CLOSE);
                if (btnExit.Image != null) btnExit.Text = "";

                btnUp.Image = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_14X9_UP1_BASIC);
                btnDn.Image = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_14X9_DOWN1_BASIC);
                if (btnUp.Image != null) btnUp.Text = string.Empty;
                if (btnDn.Image != null) btnDn.Text = string.Empty;


            }
            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 InitializeGrid()
        {
            try
            {
                gridList.CsmGridClear();
                gridList.CsmGridDataSource = null;

                gridList.CsmGridColumnHeadersVisible = true;
                gridList.CsmGridColumnHeadersHeight = 32;
                gridList.CsmGridColumnHeadersFont = new Font(m_cPosStatus.Base.FONT, 11, FontStyle.Bold);

                gridList.CsmGridColumnCount = 4;
                gridList.CsmGridRowsHeight = 32;
                gridList.CsmGridShowPageRowsCount = 7;
                gridList.Font = new Font(m_cPosStatus.Base.FONT, 11, FontStyle.Regular);

                gridList.CsmGridSetHeaderBackColor(236, 238, 239);                                                      //그리드 헤더 배경색
                gridList.CsmGridDefaultRowBackColor = Color.FromArgb(255, 255, 255);                                    //그리드 홀수(Default)행의 배경색 지정
                gridList.CsmGridAlternateRowBackColor = Color.FromArgb(251, 253, 255);                                  //그리드 짝수(Alternate)행의 배경색 지정
                gridList.CsmGridBackGroundColor = Color.FromArgb(251, 253, 255);                                        //기본 백그라운드 컬러
                gridList.CsmGridHighlightColor = Color.FromArgb(255, 251, 211);                                         //그리드 선택 백 컬러
                gridList.CsmGridHighlightTextColor = Color.Black;                                                       //그리드 선택 글자 컬러

                // 컬럼 너비 
                gridList.CsmGridSetColumnWidth(new int[] { 40, 268, 300, 100  });
                // 컬럼 정렬 0:왼쪽, 1:가운데, 2:오른쪽
                gridList.CsmGridAlignment(new int[] { 1, 0, 0, 1 });

                // 컬럼명 설정
                gridList.CsmGridColumnName(0, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0014));              // No
                gridList.CsmGridColumnName(1, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0968));              // 장비명
                gridList.CsmGridColumnName(2, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0699));              // 연결유형
                gridList.CsmGridColumnName(3, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0421));              // 상태 

                // 그리드 테이블 
                m_dtDevice = new DataTable("KTCH_DEVICE");
                m_dtDevice.Columns.Add(new DataColumn("NO", typeof(string)));
                m_dtDevice.Columns.Add(new DataColumn("DEVICE_NAME", typeof(string)));
                m_dtDevice.Columns.Add(new DataColumn("DEVICE_TYPE", typeof(string)));
                m_dtDevice.Columns.Add(new DataColumn("DEVICE_STATUS", typeof(string)));
                m_dtDevice.Columns.Add(new DataColumn("KTCH_SYS_USE_DIV", typeof(string)));
                m_dtDevice.Columns.Add(new DataColumn("KTCH_PRINTER_COMM_PORT", typeof(string)));
                m_dtDevice.Columns.Add(new DataColumn("KTCH_PRINTER_COMM_SPEED", typeof(string)));
                m_dtDevice.Columns.Add(new DataColumn("KTCH_PRINTER_IP", typeof(string)));
                m_dtDevice.Columns.Add(new DataColumn("KTCH_PRINTER_PORT", typeof(string)));

                m_dtDevice.Clear();
                gridList.CsmGridDataSource = m_dtDevice;
            }
            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 btnExit_Click(object sender, EventArgs e)
        {
            try
            {
                this.DialogResult = System.Windows.Forms.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);
            }
        }

        private void Button_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.isBusy) return;

                if (sender == btnUp)
                {
                    gridList.CsmGridScroll("UP");
                }
                else if (sender == btnDn)
                {
                    gridList.CsmGridScroll("DOWN");
                }
                else if (sender == btnEnter)
                {
                    CheckKpsStatus();
                }
            }
            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>
        /// <returns></returns>
        private bool SetGridData()
        {
            try
            {
                gridList.CsmGridClear();
                m_dtDevice.Clear();

                string subShopNo = string.IsNullOrWhiteSpace(m_cPosStatus.Base.SubShopNo)
                                 ? m_cPosStatus.Base.StoreNo
                                 : m_cPosStatus.Base.SubShopNo;
                string sql = "SELECT * FROM POSMST..MST_KTCH_DEVICE \n"
                           + " WHERE CMP_CD       = '" + m_cPosStatus.Base.CmpCd + "' \n"
                           + "   AND STOR_CD      = '" + m_cPosStatus.Base.StoreNo + "' \n"
                           + "   AND SUB_STOR_CD  = '" + subShopNo + "' \n"
                           + "   AND KTCH_SYS_DIV = '" + PosConst.KTCH_SYS_DIV.KPS + "'  \n"
                           + "   AND KTCH_SYS_CD <> '99' \n"
                           + "   AND KTCH_SYS_USE_DIV IN ('1','3') \n"
                           + "   AND USE_YN       = '" + PosConst.DEVICE_USE_FLAG.YES_USE + "' \n"
                           ;
                DataTable dt = m_cMstService.Select(new string[] { sql });
                if (dt != null && dt.Rows.Count > 0)
                {
                    int seq = 0;
                    foreach (DataRow drDevice in dt.Rows)
                    {
                        var devName = string.Format("[{0}] {1}", CmUtil.GetDataRowStr(drDevice, PosMst.MST_KTCH_DEVICE.DATA.KTCH_SYS_CD)
                                                               , CmUtil.GetDataRowStr(drDevice, PosMst.MST_KTCH_DEVICE.DATA.KTCH_SYS_NM));
                        var sysUseDiv = CmUtil.GetDataRowStr(drDevice, PosMst.MST_KTCH_DEVICE.DATA.KTCH_SYS_USE_DIV).Trim();
                        var comPort = CmUtil.GetDataRowStr(drDevice, PosMst.MST_KTCH_DEVICE.DATA.KTCH_PRINTER_COMM_PORT).Trim();
                        var comBaud = CmUtil.GetDataRowStr(drDevice, PosMst.MST_KTCH_DEVICE.DATA.KTCH_PRINTER_COMM_SPEED).Trim();
                        var netIP = CmUtil.GetDataRowStr(drDevice, PosMst.MST_KTCH_DEVICE.DATA.KTCH_PRINTER_IP).Trim();
                        var netPort = CmUtil.GetDataRowStr(drDevice, PosMst.MST_KTCH_DEVICE.DATA.KTCH_PRINTER_PORT).Trim();
                        var deviceType = string.Empty;

                        switch (sysUseDiv)
                        {
                            case PosConst.KTCH_SYS_USE_DIV.RS232:
                                deviceType = string.Format("{0} : COM{1},{2}", "Serial", comPort, comBaud);
                                break;
                            case PosConst.KTCH_SYS_USE_DIV.SOCK:
                                deviceType = string.Format("{0} : {1},{2}", "Network", netIP, netPort);
                                break;
                        }

                        DataRow dr = m_dtDevice.NewRow();
                        dr["NO"] = (++seq).ToString();
                        dr["DEVICE_NAME"] = devName;
                        dr["DEVICE_TYPE"] = deviceType;
                        dr["DEVICE_STATUS"] = string.Empty;
                        dr["KTCH_SYS_USE_DIV"] = sysUseDiv;
                        dr["KTCH_PRINTER_COMM_PORT"] = comPort;
                        dr["KTCH_PRINTER_COMM_SPEED"] = comBaud;
                        dr["KTCH_PRINTER_IP"] = netIP;
                        dr["KTCH_PRINTER_PORT"] = netPort;

                        m_dtDevice.Rows.Add(dr);
                    }
                }
                gridList.Update();

                if (m_dtDevice.Rows.Count == 0)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0337);
                    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;
            }
        }

        /// <summary>
        /// 주방프린터 상태 조회
        /// </summary>
        /// <returns></returns>
        private bool CheckKpsStatus()
        {
            try
            {
                if (this.isBusy) return false;
                this.isBusy = true;

                // 조회
                if (SetGridData() == false) return false;

                var comPrint = (IPosPrinterUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_POSPRINTER);
                var netPrint = (IKPSMain)sManager.InitServiceInstance(ServiceLists.AGENT_KPS.DLL, ServiceLists.AGENT_KPS.KPS_MAIN);

                for (var i = 0; i < m_dtDevice.Rows.Count; i++)
                {
                    DataRow dr = m_dtDevice.Rows[i];
                    bool ret = false;

                    dr["DEVICE_STATUS"] = "Checking";
                    gridList.CsmGridSelectRow(i);
                    gridList.Update();
                    System.Threading.Thread.Sleep(500);


                    switch (CmUtil.GetDataRowStr(dr, PosMst.MST_KTCH_DEVICE.DATA.KTCH_SYS_USE_DIV).Trim())
                    {
                        case PosConst.KTCH_SYS_USE_DIV.RS232:
                            ret = comPrint.OpenDeviceByRS232("COM" + CmUtil.GetDataRowStr(dr, PosMst.MST_KTCH_DEVICE.DATA.KTCH_PRINTER_COMM_PORT)
                                                                   , CmUtil.GetDataRowLong(dr, PosMst.MST_KTCH_DEVICE.DATA.KTCH_PRINTER_COMM_SPEED));
                            break;
                        case PosConst.KTCH_SYS_USE_DIV.SOCK:
                            ret = netPrint.KPSLanStatusCheck(CmUtil.GetDataRowStr(dr, PosMst.MST_KTCH_DEVICE.DATA.KTCH_PRINTER_IP)
                                                           , CmUtil.GetDataRowStr(dr, PosMst.MST_KTCH_DEVICE.DATA.KTCH_PRINTER_PORT));
                            break;
                    }

                    dr["DEVICE_STATUS"] = ret ? "OK" : "NG";
                    gridList.Update();
                }

                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;
            }
            finally
            {
                this.isBusy = false; 
            }
        }
    }
}
