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 frmReservReg : Form
    {
        private SManager sManager = new SManager();                                 //이 객체를 통해 업무 Service 호출
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   //StateObject : StateServer Object(객체)
        private PosStatus m_cPosStatus;                                             //기본정보 참조
        private TranStatus m_cTrnStatus;                                            //거래정보 참조

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

        private List<CsmPosEditBox> m_EditBoxList = new List<CsmPosEditBox>();		// 입력컨트롤 목록

        /// <summary>
        /// 등록 구분("1":신규, "2":수정)
        /// </summary>
        private string m_sRegType;
        public string RegType { get { return m_sRegType; } set { m_sRegType = value; } }
        /// <summary>
        /// 예약번호(Table Key)
        /// </summary>
        private string m_sReservNo;
        public string ReservNo { get { return m_sReservNo; } set { m_sReservNo = value; } }

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

            // 입력컨트롤 목록 추가 
            m_EditBoxList.Add(this.txtReserveDate);
            m_EditBoxList.Add(this.txtReserveHour);
            m_EditBoxList.Add(this.txtReserveMin);
            m_EditBoxList.Add(this.txtTelNo);
            m_EditBoxList.Add(this.txtCashierNm);
        }


        private void frmReservReg_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();
                LoadProc();
            }
            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 frmReservReg_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);
        }

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

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0077);
                lblReservDt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0189);
                lblReservTime.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0190);
                lblCashierNmTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0191);
                lblReservTelNo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0192);
                lblAlarm.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0892);
                lblNote.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0193);

                txtReserveDate.InputTypeFormat = m_cPosStatus.Global.m_stCultureMaster.strDatePattern;

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

                chkAlram.Checked = false;

                cbAlramTime.Items.Clear();
                cbAlramTime.Items.Add(MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0888));
                cbAlramTime.Items.Add(MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0889));
                cbAlramTime.Items.Add(MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0890));
                cbAlramTime.Items.Add(MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0891));
                cbAlramTime.SelectedIndex = -1;
                cbAlramTime.Enabled = false; 
            }
            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 LoadProc()
        {
            try
            {
                txtReserveDate.Text = string.Empty; 
                txtReserveHour.Text = string.Empty;
                txtCashierNm.Text = string.Empty;
                txtTelNo.Text = string.Empty;
                tbReservNote.Text = string.Empty;

                cbAlramTime.Enabled = false;
                cbAlramTime.SelectedIndex = -1;

                // 신규등록
                if(RegType == "1")
                {
                    txtCashierNm.Text = m_cPosStatus.Base.CashierName;
                    txtReserveDate.Text = m_cPosStatus.Global.DateToCulture(DateTime.Now.ToString("yyyyMMdd"));
                    txtReserveHour.Value = string.Empty;
                    txtReserveMin.Value = string.Empty; 

                    txtReserveDate.Select();
                    txtReserveDate.SelectText();
                }
                // 수정
                else
                {
                    DataTable dtData = null;
                    string sReturn = m_cReservUs.SelectData(new string[] { PosConst.TABLE_RESERVE_SEARCH_TYPE.TABLE_RESERVE_NO, ReservNo }, out dtData);
                    if (sReturn != UserCom.RST_OK || dtData.Rows.Count <= 0)
                    { 
                        txtCashierNm.Text = m_cPosStatus.Base.CashierName;
                        txtReserveDate.Text = m_cPosStatus.Global.DateToCulture(DateTime.Now.ToString("yyyyMMdd"));
                        txtReserveHour.Value = string.Empty;
                        txtReserveMin.Value = string.Empty;     

                        txtReserveDate.Select();
                        txtReserveDate.SelectText();
                        return;
                    }

                    string sReserveDt = CmUtil.GetDataRowStr(dtData.Rows[0], "RESERV_DT");
                    string sReserveTm = CmUtil.GetDataRowStr(dtData.Rows[0], "RESERV_TM");

                    txtReserveDate.Text = m_cPosStatus.Global.DateToCulture(sReserveDt);
                    txtReserveHour.Value = CmUtil.MidH(sReserveTm, 0, 2).PadLeft(2, '0');
                    txtReserveMin.Value = CmUtil.MidH(sReserveTm, 2, 2).PadLeft(2, '0');
                    txtCashierNm.Text = CmUtil.GetDataRowStr(dtData.Rows[0], "CASHIER_NM");
                    txtTelNo.Text = CmUtil.GetDataRowStr(dtData.Rows[0], "TEL_NO");
                    tbReservNote.Text = CmUtil.GetDataRowStr(dtData.Rows[0], "NOTE");

                    chkAlram.Checked = CmUtil.GetDataRowStr(dtData.Rows[0], "ALARM_YN") == "Y" ? true : false;
                    if (chkAlram.Checked)
                    {
                        int idx = CmUtil.IntParse(CmUtil.GetDataRowStr(dtData.Rows[0], "ALARM_TM"));
                        if (idx > cbAlramTime.Items.Count) idx = cbAlramTime.Items.Count - 1;

                        cbAlramTime.Enabled = true;
                        cbAlramTime.SelectedIndex = idx;
                    }
                    
                    tbReservNote.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);
            }
        }

        private void txtEditBox_EditBoxKeyDownEvent(object sender, string sFuncValue)
        {
            try
            {
                if (sender is TextBox) return ;
                int index = m_EditBoxList.IndexOf((CsmPosEditBox)sender);

                switch (sFuncValue)
                { 
                    case PosKey.MENU_KEY.ENTER:
                        if (CheckInputValue(index) == false) return;
                        if (index == 4)
                        {
                            tbReservNote.Focus();
                        }
                        else
                        {
                            m_EditBoxList[index + 1].Select();
                            m_EditBoxList[index + 1].SelectText();
                        }
                        break; 
                    case PosKey.MENU_KEY.ESC_PREVIOUS:
                        this.DialogResult = DialogResult.Cancel;
                        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 void btnExit_Click(object sender, EventArgs e)
        {
            try
            {
                txtEditBox_EditBoxKeyDownEvent(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 ret;
            try
            {
                if (sender == btnDate)
                {
                    string sDate = WinBasic.ShowForm(new string[] { FormManager.FORM_CALENDAR });
                    if (string.IsNullOrWhiteSpace(sDate) == false) txtReserveDate.Text = m_cPosStatus.Global.DateToCulture(sDate);
                    return; 
                }

                if (sender == btnEnter)
                {
                    if (CheckInputValue(15) == false) return;

                    string regTime = txtReserveHour.Value + txtReserveMin.Value;
                    string alramYN = chkAlram.Checked ? "Y" : "N";
                    string alramTM = cbAlramTime.SelectedIndex < 0 ? "" : cbAlramTime.SelectedIndex.ToString();

                    string sResrveDate = m_cPosStatus.Global.CultureToDate(txtReserveDate.Value);

                    // 신규등록
                    if (RegType == "1")
                    {
                        ret = m_cReservUs.InsertData(sResrveDate, regTime, txtCashierNm.Value.Trim(), txtTelNo.Value.Trim(), tbReservNote.Text.TrimEnd(), alramYN, alramTM);
                        if (ret != UserCom.RST_OK)
                        {
                            WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0133);
                            return;
                        }
                    }
                    // 수정
                    else
                    {
                        ret = m_cReservUs.UpdateData(ReservNo, sResrveDate, regTime, txtCashierNm.Value.Trim(), txtTelNo.Value.Trim(), tbReservNote.Text.TrimEnd(), alramYN, alramTM);
                        if (ret != UserCom.RST_OK)
                        {
                            WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0133);
                            return;
                        }
                    }
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                    return; 
                }
            }
            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>
        /// <param name="index"></param>
        /// <returns></returns>
        private bool CheckInputValue(int index)
        {
            try
            {
                string value = string.Empty;
                string check = string.Empty;

                // 예약일자 
                if (index >= 0)
                {
                    value = txtReserveDate.Value.Trim();
                    if (value.Length != 8)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0463);
                        txtReserveDate.SelectText();
                        txtReserveDate.Focus();
                        return false; 
                    }
                    if (CmUtil.IsNumber(value) == false)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0463);
                        txtReserveDate.SelectText();
                        txtReserveDate.Focus();
                        return false;
                    }

                    if (CmUtil.IntParse(m_cPosStatus.Global.CultureToDate(value)) < CmUtil.IntParse(m_cPosStatus.Base.SaleDate))
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0463);
                        txtReserveDate.SelectText();
                        txtReserveDate.Focus();
                        return false;
                    }
                }

                // 예약시간 
                if (index >= 1)
                {
                    //value = txtReserveHour.Value.Replace(":", "").Trim();
                    //if (string.IsNullOrWhiteSpace(value) == false)
                    //{
                    //    string pattern = "^(([0-1][0-9])|(2[0-3]))[0-5][0-9]$";
                    //    if (System.Text.RegularExpressions.Regex.IsMatch(value, pattern) == false)
                    //    {
                    //        WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0226);
                    //        txtReserveHour.SelectText();
                    //        txtReserveHour.Focus();
                    //        return false;
                    //    }
                    //}
                    value = txtReserveHour.Value;
                    if (CmUtil.IntParse(value) > 23)
                    {
                        WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0226);
                        txtReserveHour.SelectText();
                        txtReserveHour.Focus();
                        return false;
                    }
                    if (CmUtil.IsNumber(value) == false)
                    {
                        WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0226);
                        txtReserveHour.SelectText();
                        txtReserveHour.Focus();
                        return false;
                    }
                    txtReserveHour.Value = value.PadLeft(2, '0');
                }
                if (index >= 2)
                {
                    value = txtReserveMin.Value;
                    if (string.IsNullOrWhiteSpace(value))
                    {
                        txtReserveMin.Value = value = "00";
                    }
                    if (CmUtil.IntParse(value) > 59)
                    {
                        WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0226);
                        txtReserveMin.SelectText();
                        txtReserveMin.Focus();
                        return false;
                    }
                    if (CmUtil.IsNumber(value) == false)
                    {
                        WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0226);
                        txtReserveMin.SelectText();
                        txtReserveMin.Focus();
                        return false;
                    }
                    txtReserveMin.Value = value.PadLeft(2, '0');

                    value = txtReserveDate.Value + txtReserveHour.Value + txtReserveMin.Value;
                    if (CmUtil.LongParse(value) <= CmUtil.LongParse(DateTime.Now.ToString("yyyyMMddHHmm")))
                    {
                        WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0226);
                        txtReserveHour.SelectText();
                        txtReserveHour.Focus();
                        return false;
                    }
                }

                // 연락처 
                if (index >= 3)
                {
                    value = txtTelNo.Value;
                    if (string.IsNullOrWhiteSpace(value))
                    {
                        WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0225);
                        txtTelNo.SelectText();
                        txtTelNo.Focus();
                        return false;
                    }

                    txtTelNo.Value = CmUtil.MidH(value, 0, 16);
                }

                // 담당자 
                if (index >= 4)
                {
                    value = txtCashierNm.Value;
                    txtCashierNm.Value = CmUtil.MidH(value, 0, 20);
                }

                // 알람 
                if (index >= 10)
                {
                    if (chkAlram.Checked)
                    {
                        if (cbAlramTime.SelectedIndex < 0) cbAlramTime.SelectedIndex = 0;
                    }
                }

                // 예약메모 
                if (index >= 11)
                {
                    value = tbReservNote.Text;
                    if (string.IsNullOrWhiteSpace(value))
                    {
                        WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0129);
                        tbReservNote.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;
            }
        }

        private void chkAlram_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                cbAlramTime.Enabled = chkAlram.Checked;
                if (cbAlramTime.Enabled && cbAlramTime.SelectedIndex < 0)
                {
                    cbAlramTime.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                            System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                            ex.Message);
            }
        }
    }
}
