using System;
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 frmKitchMsgList : Form
    {
        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 IDataProcessUs m_cDataSrv = null;                                   //거래데이터 합계금액 계산 및 관리
        private ITableUs m_cTableSvr = null;                                        //테이블 서비스 관리
        private DataTable m_dtMemo = null;

        /// <summary>
        /// 층코드
        /// </summary>
        public string FloorCd { set; private get; }
        /// <summary>
        /// 층명 
        /// </summary>
        public string FloorNm { set; private get; }
        /// <summary>
        /// 테이블번호 
        /// </summary>
        public string TableNo { set; private get; }
        /// <summary>
        /// 화면표시용 테이블명 
        /// </summary>
        public string TableNm { set; private get; }

        /// <summary>
        /// 생성자 
        /// </summary>
        public frmKitchMsgList()
        {
            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_cTableSvr = (ITableUs)sManager.InitServiceInstance(ServiceLists.BSV_TABLE.DLL, ServiceLists.BSV_TABLE.TABLE_SERVICE);

            this.FloorCd = string.Empty;
            this.FloorNm = string.Empty; 
            this.TableNo = string.Empty;
            this.TableNm = string.Empty; 
        }

        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 + "()", "");

                PosOLEDevice.SetEventHandle(null);

                this.InitControls();
                this.InitializeGrid();
                this.SetGridData();
            }
            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
            {
                PosOLEDevice.SetEventHandle(null);
            }
            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)
        {
            try
            {
                this.FloorCd = string.Empty;
                this.FloorNm = string.Empty;
                this.TableNo = string.Empty;
                this.TableNm = string.Empty; 

                PosOLEDevice.SetEventHandle(null);

                UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                          System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                          System.Reflection.MethodBase.GetCurrentMethod().Name + "()", lblTitle.Text);
            }
            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>
        private void InitControls()
        {
            try
            {
                this.picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_800X600);
                this.picBack.Location = new Point(0, 0);
                this.picBack.SendToBack();
                this.Size = this.picBack.Size = new Size(800, 600);

                FormManager.MovePopUpForm(this, false, m_cPosStatus.Sale.ScreenSizeUser);
                FormManager.SetFormAllControlFont(this, m_cPosStatus.Base.FONT);

                //테마색상 적용!
                btnEnter.BackColor = CmUtil.GetColorToString(m_cPosStatus.ScnMst.ThemeColor);

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

                btnGridUp.DefaultImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_378X48_UP1_BASIC);
                btnGridUp.ClickImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_378X48_UP1_PRESS);
                btnGridUp.BorderStyle = BorderStyle.None;
                btnGridDn.DefaultImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_378X48_DOWN1_BASIC);
                btnGridDn.ClickImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_378X48_DOWN1_PRESS);
                btnGridDn.BorderStyle = BorderStyle.None;

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0174);
                lblLabel1.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0175);
                lblLabel2.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0176);

                btnEnter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0126);

                lblFloorCd.Text = string.IsNullOrWhiteSpace(this.FloorNm) ? this.FloorCd : this.FloorNm;
                lblTableNo.Text = string.IsNullOrWhiteSpace(this.TableNm) ? this.TableNo : this.TableNm;
            }
            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>
        private void InitializeGrid()
        {
            try
            {
                gridMemo.CsmGridClear();
                gridMemo.CsmGridDataSource = null;

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

                gridMemo.CsmGridColumnCount = 4;
                gridMemo.CsmGridRowsHeight = 35;
                gridMemo.CsmGridShowPageRowsCount = 9;
                gridMemo.Font = new Font(m_cPosStatus.Base.FONT, 11, FontStyle.Regular);

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

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

                // 컬럼명 설정
                gridMemo.CsmGridColumnName(0, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0014));
                gridMemo.CsmGridColumnName(1, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0239));
                gridMemo.CsmGridColumnName(2, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0191));
                gridMemo.CsmGridColumnName(3, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0193));

                // 그리드 테이블 
                m_dtMemo = new DataTable("SEAT_MEMO");
                m_dtMemo.Columns.Add(new DataColumn("NO", typeof(string)));
                m_dtMemo.Columns.Add(new DataColumn("REGTIME", typeof(string)));
                m_dtMemo.Columns.Add(new DataColumn("CASHIER", typeof(string)));
                m_dtMemo.Columns.Add(new DataColumn("MEMO", typeof(string)));
                m_dtMemo.Clear();

                gridMemo.CsmGridDataSource = m_dtMemo;
            }
            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 (sender == btnExit)
                {
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else if (sender == btnGridUp)
                {
                    gridMemo.CsmGridScroll("UP");
                }
                else if (sender == btnGridDn)
                {
                    gridMemo.CsmGridScroll("DOWN");
                }
                else if (sender == btnEnter)
                {
                    // 거래 초기화
                    m_cDataSrv.InitTranHeader();
                    m_cDataSrv.DeleteTranItem();

                    m_cTrnStatus.Head.FloorCd = this.FloorCd;
                    m_cTrnStatus.Head.TableNo = this.TableNo;
                    m_cTrnStatus.Head.TableNm = this.TableNm;
                    m_cTrnStatus.Head.OrderFlag = PosConst.ORDER_TYPE.NORMAL;
                    m_cTableSvr.SelectMenuOrder();

                    WinTable.ShowForm(new string[] { FormManager.FORM_ETC_TABLE_MEMO, "2", this.FloorCd, this.TableNo, this.TableNm });

                    // 거래 초기화
                    m_cDataSrv.InitTranHeader();
                    m_cDataSrv.DeleteTranItem();

                    this.SetGridData();
                }
            }
            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 SetGridData()
        {
            try
            {
                gridMemo.CsmGridClear();
                m_dtMemo.Clear();

                DataTable dtData = null;
                string ret = m_cTableSvr.SelectKtchOrderMessage(this.FloorCd, this.TableNo, out dtData);
                if (ret.StartsWith(UserCom.RST_IGNORE))
                {
                    // Select 결과 없음
                    return;
                }
                if (ret != UserCom.RST_OK)
                {
                    WinManager.ErrorMessage(ret);
                    return;
                }
                if (dtData == null || dtData.Rows.Count == 0) return;

                gridMemo.SuspendLayout();

                for (var i = 0; i < dtData.Rows.Count; i++)
                {
                    DataRow dr = m_dtMemo.NewRow();
                    dr["NO"] = (i + 1).ToString();
                    dr["REGTIME"] = CmUtil.StrToTime(dtData.Rows[i]["REG_TIME"].ToString().Substring(0, 6));
                    //dr["CASHIER"] = dtData.Rows[i]["CASHIER_ID"].ToString() 
                    //              + (string.IsNullOrWhiteSpace(dtData.Rows[i]["CASHIER_NM"].ToString()) 
                    //              ? string.Empty : Environment.NewLine + dtData.Rows[i]["CASHIER_NM"].ToString());
                    dr["CASHIER"] = dtData.Rows[i]["CASHIER_NM"].ToString();
                    dr["MEMO"] = dtData.Rows[i]["MSG1"].ToString() + Environment.NewLine
                               + dtData.Rows[i]["MSG2"].ToString() + Environment.NewLine
                               + dtData.Rows[i]["MSG3"].ToString() + Environment.NewLine;

                    m_dtMemo.Rows.Add(dr);
                }

                gridMemo.CsmGridSelectRow(m_dtMemo.Rows.Count - 1);
                gridMemo.ResumeLayout();
                gridMemo.Select();
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                            System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                            ex.Message);
            }
            finally
            {
                gridMemo.Update();
            }
        }
    }
}
