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.BaseFrame;
using Cosmos.UserFrame;
using Cosmos.ServiceProvider;
using Cosmos.Common;
using Cosmos.CommonManager;
using Cosmos.UI;

namespace TableConfiguration
{
    /// <summary>
    /// 테이블 관리 
    /// </summary>
    public partial class frmTableManager : Form
    {
        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        private PosStatus m_cPosStatus = new PosStatus();                           // 기본정보 참조

        private ITableUs m_cTableSvr = null;

        /// <summary>
        /// 입력박스 목록
        /// </summary>
        private List<CsmPosEditBox> m_EditBoxList = new List<CsmPosEditBox>();

        private CsmPosEditBox m_currentEditBox = null;

        /// <summary>
        /// 테이블 마스터 
        /// </summary>
        public List<Column.MST_TABLE.TABLE_DATA> TableMaster { get; set; }
        /// <summary>
        /// 현재층코드
        /// </summary>
        public string FloorCode { get; set; }
        /// <summary>
        /// 현재층명
        /// </summary>
        public string FloorName { get; set; }
        /// <summary>
        /// 현재테이블번호 
        /// </summary>
        public string TableNo { get; set; }


        public frmTableManager()
        {
            InitializeComponent();

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

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

            m_cTableSvr = (ITableUs)sManager.InitServiceInstance(ServiceLists.BSV_TABLE.DLL, ServiceLists.BSV_TABLE.TABLE_SERVICE);

            this.FloorCode = string.Empty;
            this.FloorName = string.Empty;
            this.TableNo = string.Empty;

            m_EditBoxList = new List<CsmPosEditBox>();
            m_EditBoxList.Add(txtTableNo);          // 0 readonley
            m_EditBoxList.Add(txtTableNm);          // 1
            m_EditBoxList.Add(txtFontSize);         // 2
            m_EditBoxList.Add(txtCordX);            // 3 readonley
            m_EditBoxList.Add(txtCordY);            // 4 readonley
            m_EditBoxList.Add(txtWidth);            // 5 readonley
            m_EditBoxList.Add(txtHeight);           // 6 readonley
        }

        private void From_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);

                InitControls();
                InitializeGrid();
                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_Closing(object sender, FormClosingEventArgs e)
        {
            try
            {
                UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                          System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                          System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "");
            }
            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 = System.Windows.Forms.DialogResult.Cancel;
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    this.Close();
                }
                else if (sender == btnGridUp)
                {
                    gridTable.CsmGridScroll("UP");
                }
                else if (sender == btnGridDn)
                {
                    gridTable.CsmGridScroll("DOWN");
                }
                else if (sender == btnEnter)
                {
                    //CompleteInputValue();
                    EditBox_KeyDownEvent(m_currentEditBox, PosKey.MENU_KEY.ENTER);
                }
            }
            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 EditBox_KeyDownEvent(object sender, string sFuncValue)
        {
            try
            {
                int index = m_EditBoxList.IndexOf((CsmPosEditBox)sender);

                switch (sFuncValue)
                {
                    case PosKey.MENU_KEY.ENTER:
                        if (CheckInputValue(index) == false) return;
                        if (CompleteInputValue() == false) return;
                        if (index < m_EditBoxList.Count - 1 && m_EditBoxList[index + 1].Enabled == true)
                            m_EditBoxList[index + 1].Select();
                        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 EditBox_Enter(object sender, EventArgs e)
        {
            try
            {
                if (sender is CsmPosEditBox)
                {
                    m_currentEditBox = (CsmPosEditBox)sender;
                }
                else
                {
                    m_currentEditBox = null;
                }
            }
            catch { }
        }

        private void Grid_ClickEvent(object sender, string rowIndex)
        {
            try
            {
                if (CmUtil.IsNumber(rowIndex) == false) return;
                if (gridTable.CsmGridRowsCount == 0) return;

                int idx = CmUtil.IntParse(rowIndex);
                string tableno = gridTable.CsmGridGetCell(idx, 1);

                Column.MST_TABLE.TABLE_DATA cTable = TableMaster.Find(x => (x.FLOOR_CD == FloorCode && x.TABLE_NO == tableno));
                if (cTable == null) return;

                this.TableNo = tableno;
                txtTableNo.Value = cTable.TABLE_NO;
                txtTableNm.Value = cTable.TABLE_NM;
                txtFontSize.Value = cTable.FONT_SIZE.ToString();
                txtCordX.Value = cTable.X_COORD.ToString();
                txtCordY.Value = cTable.Y_COORD.ToString();
                txtWidth.Value = cTable.WIDTH.ToString();
                txtHeight.Value = cTable.HEIGHT.ToString();

                txtTableNm.Focus();
                txtTableNm.Select();
                txtTableNm.SelectText();
                txtTableNo.ReadOnly = 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);
            }
        }

        private void Grid_Enter(object sender, EventArgs e)
        {
            try
            {
                txtTableNm.Focus();
            }
            catch { }
        }

        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 = picBack.Size = picBack.Image.Size;

                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_170X48_UP1_BASIC);
                btnGridUp.ClickImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_170X48_UP1_PRESS);
                btnGridUp.BorderStyle = BorderStyle.None;

                btnGridDn.DefaultImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_170X48_DOWN1_BASIC);
                btnGridDn.ClickImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_170X48_DOWN1_PRESS);
                btnGridDn.BorderStyle = BorderStyle.None;

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

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0811);
                lblFloorCd.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0175);
                lblTableNo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0820);
                lblTableNm.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0821);
                lblFontSize.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0822);
                lblTblPos.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0823);
                lblTblSize.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0824);

                foreach (CsmPosEditBox box in m_EditBoxList)
                {
                    box.Value = string.Empty;
                    box.Tag = string.Empty; 
                }

                lblFloor.Text = string.Format("{0} [{1}]", this.FloorCode, this.FloorName);
            }
            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
            {
                gridTable.CsmGridClear();
                gridTable.CsmGridDataSource = null;

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

                gridTable.CsmGridColumnCount = 3;
                gridTable.CsmGridRowsHeight = 34;
                gridTable.CsmGridShowPageRowsCount = 7;
                gridTable.Font = new Font(m_cPosStatus.Base.FONT, 11, FontStyle.Regular);

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

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

                // 컬럼명 설정
                gridTable.CsmGridColumnName(0, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0014));
                gridTable.CsmGridColumnName(1, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0815));
                gridTable.CsmGridColumnName(2, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0816));

            }
            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 bool SetGridData()
        {
            try
            {
                int selectRow = gridTable.CsmGridSelectedRowIndex;
                string selectTableNo = string.Empty; 

                DataTable dtData = new DataTable("MST_TABLE");
                dtData.Columns.Add(new DataColumn("NO", typeof(string)));
                dtData.Columns.Add(new DataColumn("CODE", typeof(string)));
                dtData.Columns.Add(new DataColumn("NAME", typeof(string)));

                gridTable.CsmGridClear();
                gridTable.SuspendLayout();

                var seq = 0;
                foreach (var cTable in from x in TableMaster
                                       where x.FLOOR_CD == this.FloorCode
                                          && x.STATUS != PosConst.DB_ROW_STATUS.DELETE
                                       orderby x.FLOOR_CD, x.TABLE_NO
                                       select x)
                {
                    DataRow dr = dtData.NewRow();
                    dr["NO"] = ++seq;
                    dr["CODE"] = cTable.TABLE_NO;
                    dr["NAME"] = cTable.TABLE_NM;
                    dtData.Rows.Add(dr);

                    if (cTable.FLOOR_CD == this.FloorCode && cTable.TABLE_NO == this.TableNo)
                    {
                        selectTableNo = cTable.TABLE_NO;
                        selectRow = seq - 1;
                    }
                }

                gridTable.CsmGridDataSource = dtData;
                gridTable.ResumeLayout();

                if (selectRow < 0)
                {
                    selectRow = 0;
                }
                else if (selectRow > gridTable.CsmGridRowsCount)
                {
                    selectRow = gridTable.CsmGridRowsCount - 1; 
                }

                // 테이블정보 화면표시 
                this.TableNo = gridTable.CsmGridGetCell(selectRow, 1);
                gridTable.CsmGridSelectRow(selectRow);
                
                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;
            }
        }

        private bool CheckInputValue(int index)
        {
            try
            {
                string value = string.Empty;

                if (index >= 0 && txtTableNo.ReadOnly == false)
                {
                    value = txtTableNo.Value.Trim();
                    if (string.IsNullOrWhiteSpace(value))
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0504);
                        txtTableNo.Focus();
                        txtTableNo.SelectText();
                    }
                }

                if (index >= 1)
                {
                    value = txtTableNm.Value.Trim();
                    if (string.IsNullOrWhiteSpace(value)) value = txtTableNm.Value = txtTableNo.Value.Trim();
                    if (string.IsNullOrWhiteSpace(value))
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0505);
                        txtTableNm.Focus();
                        txtTableNm.SelectText();
                        return false;
                    }
                }

                if (index >= 2)
                {
                    value = txtFontSize.Value.Trim();
                    if (CmUtil.IntParse(value) < 7) value = "10";
                }



                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;
            }
        }

        private bool CompleteInputValue()
        {
            try
            {
                if (CheckInputValue(m_EditBoxList.Count) == false) return false;

                int selectedRow = gridTable.CsmGridSelectedRowIndex;

                Column.MST_TABLE.TABLE_DATA cTable = TableMaster.Find(x => (x.FLOOR_CD == FloorCode && x.TABLE_NO == txtTableNo.Value));
                if (cTable == null) return false; 

                if (cTable.STATUS == PosConst.DB_ROW_STATUS.NONE)
                {
                    if (cTable.TABLE_NM != txtTableNm.Value)
                        cTable.STATUS = PosConst.DB_ROW_STATUS.UPDATE;

                    if (cTable.FONT_SIZE != CmUtil.IntParse(txtFontSize.Value))
                        cTable.STATUS = PosConst.DB_ROW_STATUS.UPDATE;
                }

                cTable.TABLE_NO = txtTableNo.Value.Trim();
                cTable.TABLE_NM = txtTableNm.Value.Trim();
                cTable.FONT_SIZE = CmUtil.IntParse(txtFontSize.Value);

                cTable.X_COORD = CmUtil.IntParse(txtCordX.Value);
                cTable.Y_COORD = CmUtil.IntParse(txtCordY.Value);
                cTable.WIDTH = CmUtil.IntParse(txtWidth.Value);
                cTable.HEIGHT = CmUtil.IntParse(txtHeight.Value);

                this.TableNo = cTable.TABLE_NO;
                SetGridData();

                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;
            }
        }
    }
}
