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
{
    public partial class frmReservMain : Form
    {
        /*--------------------------------------------------------------*/
        /* SManager Object : 이 객체를 통해 업무 Service 호출
        /*--------------------------------------------------------------*/
        SManager sManager = new SManager();

        /*--------------------------------------------------------------*/
        /* StateObject : StateServer 객체
        /*--------------------------------------------------------------*/
        private StateServer StateObject = (StateServer)StateServer.GetInstance();

        private PosStatus m_cPosStatus = null;                                      //기본정보 참조
        private TranStatus m_cTrnStatus = null;                                     //거래정보 참조

        private DataTable dtReservedData;

        private IReservationUs m_cReserveUs = null;                                 //예약 관리

        public frmReservMain()
        {
            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_cReserveUs = (IReservationUs)sManager.InitServiceInstance(ServiceLists.BSV_TABLE.DLL, ServiceLists.BSV_TABLE.RESERVATION_SERVICE);
        }

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

                // Form 초기화
                InitControls();

                // Grid  초기화 
                InitializeGrid();
                SetGridData();
            }
            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);
            }
        }

        private void frmReservMain_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 + "()", lblTitle.Text);
        }

        /// <summary>
        /// Grid Data 설정
        /// </summary>
        private void SetGridData(int selectIdx = -1)
        {
            try
            {
                if (CheckInputData(null) == false) return; 

                gridReserv.SuspendLayout();
                dtReservedData.Clear();

                string yymm = txtReservYear.Value + txtReservMon.Value.PadLeft(2, '0');
                DataTable dtData = null;
                string sReturn = m_cReserveUs.SelectData(new string[] { PosConst.TABLE_RESERVE_SEARCH_TYPE.TABLE_RESERVE_YM, yymm }, out dtData);
                if (sReturn == UserCom.RST_OK)
                {
                    for (var i = 0; i < dtData.Rows.Count; i++)
                    {
                        DataRow dr = dtReservedData.NewRow();

                        dr["RESERV_DT"] = m_cPosStatus.Global.DateToCulture(CmUtil.GetDataRowStr(dtData.Rows[i], "RESERV_DT").Trim());
                        dr["RESERV_TM"] = CmUtil.StrToTime(CmUtil.GetDataRowStr(dtData.Rows[i], "RESERV_TM"));
                        dr["CASHIER_NM"] = CmUtil.GetDataRowStr(dtData.Rows[i], "CASHIER_NM");
                        dr["TEL_NO"] = CmUtil.GetDataRowStr(dtData.Rows[i], "TEL_NO");
                        dr["NOTE"] = CmUtil.GetDataRowStr(dtData.Rows[i], "NOTE");
                        dr["RESERV_NO"] = CmUtil.GetDataRowStr(dtData.Rows[i], "RESERV_NO");

                        dtReservedData.Rows.Add(dr);
                    }

                    if (selectIdx < 0) selectIdx = dtReservedData.Rows.Count - 1;
                    gridReserv.CsmGridSelectRow(selectIdx);
                }
            }
            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);
            }
            finally
            {
                gridReserv.ResumeLayout(false);
                // gridReserv.Focus();
            }
        }

        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 = "";
                //btnDate.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.ICON_DATE_BASIC);
                //if (btnDate.Image != null) btnDate.Text = "";

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0187);
                txtReservYear.Value = m_cPosStatus.Base.SaleDate.Substring(0, 6);

                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;

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

                txtReservYear.Value = DateTime.Now.Year.ToString();
                txtReservMon.Value = DateTime.Now.Month.ToString();
                txtReservMon.Select();
            }
            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>
        /// Grid 초기화
        /// </summary>
        private void InitializeGrid()
        {
            try
            {
                //gridReserv.CsmGridClear();
                //gridReserv.CsmGridDataSource = null;

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

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

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

                //컬럼 넓이 지정
                gridReserv.CsmGridSetColumnWidth(new int[] { 100, 100, 100, 150, 306, 0 });
                //컬럼별 정렬 기준 설정(0:왼쪽, 1:가운데, 2:오른쪽)
                gridReserv.CsmGridAlignment(new int[] { 1, 1, 1, 1, 0, 0 });

                // 컬럼명 설정
                gridReserv.CsmGridColumnName(0, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0189));        // 예약일자
                gridReserv.CsmGridColumnName(1, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0190));        // 예약시간
                gridReserv.CsmGridColumnName(2, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0191));        // 담당자
                gridReserv.CsmGridColumnName(3, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0192));        // 연락처
                gridReserv.CsmGridColumnName(4, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0193));        // 내용
                gridReserv.CsmGridColumnName(5, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0188));        // 예약번호

                //특정컬럼 Visible 여부 설정
                //gridReserv.CsmGridColumnShowHide(5, false);

                dtReservedData = new DataTable();
                dtReservedData.Columns.Add(new DataColumn("RESERV_DT", typeof(string)));
                dtReservedData.Columns.Add(new DataColumn("RESERV_TM", typeof(string)));
                dtReservedData.Columns.Add(new DataColumn("CASHIER_NM", typeof(string)));
                dtReservedData.Columns.Add(new DataColumn("TEL_NO", typeof(string)));
                dtReservedData.Columns.Add(new DataColumn("NOTE", typeof(string)));
                dtReservedData.Columns.Add(new DataColumn("RESERV_NO", typeof(string)));
                
                gridReserv.CsmGridDataSource = dtReservedData;
            }
            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
            {
                EditBox_KeyDownEvent(null, PosKey.MENU_KEY.ESC_PREVIOUS);
            }
            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 btnProc_Click(object sender, EventArgs e)
        {
            string sRet;
            try
            {
                if (sender == btnEnter)      // 등록
                {
                    sRet = WinTable.ShowForm(new string[] { FormManager.FORM_ETC_RESERV_REG, "1" });
                    if(sRet == UserCom.RST_OK)
                    {
                        SetGridData();
                    }
                }
                else if (sender == btnModify) // 수정
                {
                    if (gridReserv.CsmGridRowsCount == 0) return;

                    int iSelectedIdx = gridReserv.CsmGridSelectedRowIndex;
                    string ss = gridReserv.CsmGridGetCell(0, 0);
                    sRet = WinTable.ShowForm(new string[] { FormManager.FORM_ETC_RESERV_REG, "2", CmUtil.GetDataRowStr(dtReservedData.Rows[iSelectedIdx], "RESERV_NO") });
                    if(sRet == UserCom.RST_OK)
                    {
                        SetGridData(iSelectedIdx);
                    }
                }
                else if (sender == btnSearch)
                {
                    EditBox_KeyDownEvent(txtReservYear, 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 btnGrid_Click(object sender, EventArgs e)
        {
            try
            {
                if ((Cosmos.UI.CsmButton)sender == btnGridUp)
                {
                    gridReserv.CsmGridScroll("UP");
                }
                else if ((Cosmos.UI.CsmButton)sender == btnGridDn)
                {
                    gridReserv.CsmGridScroll("DOWN");
                }
            }
            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 btnGrid_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                ((Cosmos.UI.CsmButton)sender).BorderStyle = BorderStyle.FixedSingle;
            }
            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 btnGrid_MouseUp(object sender, MouseEventArgs e)
        {
            try
            {
                ((Cosmos.UI.CsmButton)sender).BorderStyle = BorderStyle.None;
            }
            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
            {

                switch (sFuncValue)
                { 
                    case PosKey.MENU_KEY.ENTER:
                        if (CheckInputData(sender) == false) return;
                        SetGridData();
                        break; 
                    case PosKey.MENU_KEY.ESC_PREVIOUS:
                        this.DialogResult = System.Windows.Forms.DialogResult.OK;
                        this.Close();
                        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 bool CheckInputData(object sender)
        {
            try
            {
                string value = string.Empty; 

                if (sender == null || sender == txtReservYear)
                {
                    value = txtReservYear.Value.Trim();
                    if (value.Length != 4)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0582);
                        txtReservYear.SelectText();
                        txtReservYear.Focus();
                        return false; 
                    }
                    if (sender != null) txtReservMon.Select();
                }
                if (sender == null || sender == txtReservMon)
                {
                    value = txtReservMon.Value.Trim();
                    int x = CmUtil.IntParse(value);
                    if (x < 1 || x > 12)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0582);
                        txtReservYear.SelectText();
                        txtReservYear.Focus();
                        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; 
            }
        }
    }
}
