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 frmFloorManager : 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>();
        /// <summary>
        /// 편집모드 
        /// </summary>
        private PosConst.DB_ROW_STATUS m_editMode = PosConst.DB_ROW_STATUS.NONE;

        /// <summary>
        /// 현재층코드
        /// </summary>
        public string FloorCode { get; set; }
        /// <summary>
        /// 층마스터 
        /// </summary>
        public List<Column.MST_FLOOR.FLOOR_DATA> FloorMaster { get; set; }

        public frmFloorManager()
        {
            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;

            m_EditBoxList = new List<CsmPosEditBox>();
            m_EditBoxList.Add(txtFloorCd);
            m_EditBoxList.Add(txtFloorNm);
        }

        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.OK;
                    this.Close();
                }
                else if (sender == btnGridUp)
                {
                    gridFloor.CsmGridScroll("UP");
                }
                else if (sender == btnGridDn)
                {
                    gridFloor.CsmGridScroll("DOWN");
                }
                else if (sender == btnInsert)
                {
                    string newCode = GetNewFloorCode();
                    if (string.IsNullOrWhiteSpace(newCode))
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0499);
                        return; 
                    }

                    this.m_editMode = PosConst.DB_ROW_STATUS.INSERT;
                    txtFloorCd.Value = newCode;
                    txtFloorCd.Focus();
                    txtFloorCd.Select();
                    txtFloorCd.ReadOnly = false;
                    txtFloorNm.Value = newCode;
                }
                else if (sender == btnDelete)
                {
                    if (gridFloor.CsmGridRowsCount == 0) return; 
                    if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0500) == false) return; 
                    this.m_editMode = PosConst.DB_ROW_STATUS.DELETE;
                    if (CompleteInputValue() == false) return;
                }
                else if (sender == btnEnter)
                {
                    CompleteInputValue();
                }
            }
            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].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 Grid_ClickEvent(object sender, string rowIndex)
        {
            try
            {
                if (CmUtil.IsNumber(rowIndex) == false) return;
                if (gridFloor.CsmGridRowsCount == 0) return; 

                int idx = CmUtil.IntParse(rowIndex);
                string floorCd = gridFloor.CsmGridGetCell(idx, 1);

                Column.MST_FLOOR.FLOOR_DATA cFloor = FloorMaster.Find(x => (x.FLOOR_CD == floorCd));
                if (cFloor == null) return;

                this.FloorCode = cFloor.FLOOR_CD.Trim();
                txtFloorCd.Value = cFloor.FLOOR_CD.Trim();
                txtFloorNm.Value = cFloor.FLOOR_NM.Trim();
                
                txtFloorNm.Focus();
                txtFloorNm.Select();
                txtFloorNm.SelectText();
                txtFloorCd.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
            {
                txtFloorNm.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;

                btnInsert.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0224);
                btnDelete.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0021);
                btnEnter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0009);

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0813);
                lblFloorCd.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0815);
                lblFloorNm.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0816);

                m_editMode = PosConst.DB_ROW_STATUS.NONE;

                foreach (CsmPosEditBox box in m_EditBoxList)
                {
                    box.Value = string.Empty;
                    box.Tag = 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
            {
                gridFloor.CsmGridClear();
                gridFloor.CsmGridDataSource = null;

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

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

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

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

                // 컬럼명 설정
                gridFloor.CsmGridColumnName(0, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0014));
                gridFloor.CsmGridColumnName(1, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0815));
                gridFloor.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 = gridFloor.CsmGridSelectedRowIndex;

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

                gridFloor.CsmGridClear();
                gridFloor.SuspendLayout();

                var seq = 0;
                foreach (var cFloor in from x in FloorMaster
                                       where x.STATUS != PosConst.DB_ROW_STATUS.DELETE
                                       orderby x.FLOOR_CD
                                       select x)
                {
                    DataRow dr = dtData.NewRow();
                    dr["NO"] = ++seq;
                    dr["CODE"] = cFloor.FLOOR_CD;
                    dr["NAME"] = cFloor.FLOOR_NM;
                    dtData.Rows.Add(dr);

                    if (this.FloorCode == cFloor.FLOOR_CD) selectRow = seq - 1;
                }

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

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

                // 층정보 화면표시 
                if (gridFloor.CsmGridRowsCount > 0)
                {
                    this.FloorCode = FloorMaster[selectRow].FLOOR_CD;
                    gridFloor.CsmGridSelectRow(selectRow);
                    Grid_ClickEvent(gridFloor, selectRow.ToString());
                }
                else
                { 
                    this.FloorCode = string.Empty ;
                    txtFloorCd.Value = string.Empty;
                    txtFloorNm.Value = string.Empty; 
                }

                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 && txtFloorCd.ReadOnly == false)
                {
                    value = txtFloorCd.Value.Trim();
                    if (string.IsNullOrWhiteSpace(value))
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0501);
                        txtFloorCd.Focus();
                        txtFloorCd.SelectText();
                        return false; 
                    }
                    if (m_editMode == PosConst.DB_ROW_STATUS.INSERT)
                    {
                        Column.MST_FLOOR.FLOOR_DATA cFloor = FloorMaster.Find(x => (x.FLOOR_CD == value));
                        if (cFloor != null && cFloor.STATUS != PosConst.DB_ROW_STATUS.DELETE)
                        {
                            WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0502);
                            txtFloorCd.Focus();
                            txtFloorCd.SelectText();
                            return false; 
                        }
                    }
                }

                if (index >= 1)
                {
                    value = txtFloorNm.Value.Trim();
                    if (string.IsNullOrWhiteSpace(value)) value = txtFloorNm.Value = txtFloorCd.Value.Trim();
                    if (string.IsNullOrWhiteSpace(value))
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0503);
                        txtFloorNm.Focus();
                        txtFloorNm.SelectText();
                        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;
            }
        }

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

                int selectedRow = gridFloor.CsmGridSelectedRowIndex;

                Column.MST_FLOOR.FLOOR_DATA cFloor = FloorMaster.Find(x => (x.FLOOR_CD == txtFloorCd.Value));
                if (cFloor == null)
                {
                    cFloor = new Column.MST_FLOOR.FLOOR_DATA();
                    cFloor.FLOOR_CD = txtFloorCd.Value;
                    cFloor.FLOOR_NM = txtFloorNm.Value;
                    cFloor.STATUS = PosConst.DB_ROW_STATUS.INSERT;
                    FloorMaster.Add(cFloor);
                    FloorMaster = FloorMaster.OrderBy(x => x.FLOOR_CD).ToList();
                }
                else
                {
                    if (m_editMode == PosConst.DB_ROW_STATUS.DELETE)
                    {
                        cFloor.STATUS = PosConst.DB_ROW_STATUS.DELETE;
                    }
                    else if (cFloor.FLOOR_CD != txtFloorCd.Value)
                    {
                        cFloor.STATUS = PosConst.DB_ROW_STATUS.UPDATE;
                    }
                    else if (cFloor.FLOOR_NM != txtFloorNm.Value)
                    {
                        cFloor.STATUS = PosConst.DB_ROW_STATUS.UPDATE;
                    }
                    else if (m_editMode == PosConst.DB_ROW_STATUS.INSERT)
                    {
                        cFloor.STATUS = PosConst.DB_ROW_STATUS.INSERT;
                    }
                    cFloor.FLOOR_CD = txtFloorCd.Value;
                    cFloor.FLOOR_NM = txtFloorNm.Value;
                }

                m_editMode = PosConst.DB_ROW_STATUS.NONE;

                this.FloorCode = cFloor.STATUS == PosConst.DB_ROW_STATUS.DELETE ? string.Empty : cFloor.FLOOR_CD;
                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;
            }
        }

        /// <summary>
        /// 변경여부 확인
        /// </summary>
        /// <returns></returns>
        private bool CheckDataChanged()
        {
            try
            {
                Column.MST_FLOOR.FLOOR_DATA cFloor = FloorMaster.Find(x => (x.STATUS != PosConst.DB_ROW_STATUS.NONE));
                return cFloor == null ? false : 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 string GetNewFloorCode()
        {
            try
            {
                for (var i = 1; i < 1000; i++)
                {
                    string newCode = i.ToString("000");

                    Column.MST_FLOOR.FLOOR_DATA temp = FloorMaster.Find(x => x.FLOOR_CD == newCode);
                    if (temp == null) return newCode;
                    if (temp.STATUS == PosConst.DB_ROW_STATUS.DELETE) return newCode;
                }

                return 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);
                return string.Empty; 
            }
        }
    }   
}
