using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

using Cosmos.BaseFrame;
using Cosmos.UserFrame;
using Cosmos.ServiceProvider;
using Cosmos.Common;
using Cosmos.CommonManager;

namespace Cosmos.Service
{
    class ReservationService : IReservationUs
    {
        private SManager sManager = new SManager();                                                                     // 이 객체를 통해 업무 Service 호출
        private StateServer StateObject = (StateServer)StateServer.GetInstance();                                       // StateObject : StateServer Object (객체)
        private PosStatus m_cPosStatus;                                                                                 // 기본정보 참조
        private TranStatus m_cTrnStatus;                                                                                // 거래정보 참조

        private IMasterUs m_cMstService = null;                                                                         // 마스터 인터페이스

        public ReservationService()
        {
            m_cPosStatus = (PosStatus)StateObject.POS;                                                                  // POS 기본정보
            m_cTrnStatus = (TranStatus)StateObject.TRAN;                                                                // POS 거래정보

            m_cMstService = (IMasterUs)sManager.InitServiceInstance(ServiceLists.ASV_MASTER.DLL, ServiceLists.ASV_MASTER.POS_MASTER);
        }

        /// <summary>
        /// 예약 데이터 조회
        /// </summary>
        /// <param name="aPara">예약번호</param>
        /// <param name="dtData">조회결과</param>
        /// <returns></returns>
        public string SelectData(string[] aPara, out DataTable dtData)
        {
            string sReturn = UserCom.RST_ERR;

            dtData = new DataTable();

            try
            {
                string sql = "SELECT CMP_CD         \n"
                           + "     , STOR_CD        \n"
                           + "     , RESERV_NO      \n"
                           + "     , RESERV_DT      \n"
                           + "     , RESERV_TM      \n"
                           + "     , CASHIER_NM     \n"
                           + "     , TEL_NO         \n"
                           + "     , NOTE           \n"
                           + "     , ALARM_YN       \n"
                           + "     , ALARM_TM       \n"
                           + "     , CONFIRM        \n"
                           + "     , FILLER1        \n"                                                                 // 연습모드 
                           + "     , FILLER2        \n"
                           + "     , FILLER3        \n"
                           + "     , FILLER4        \n"
                           + "     , FILLER5        \n"
                           + "     , UPD_ID         \n"
                           + "     , UPD_DT         \n"
                           + "     , REG_ID         \n"
                           + "     , REG_DT         \n"
                           + "  FROM POSMST..MST_RESERV WITH(NOLOCK) "
                           + " WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "' ";

                if (aPara[0] == PosConst.TABLE_RESERVE_SEARCH_TYPE.TABLE_RESERVE_NO)
                {
                    sql += " AND RESERV_NO = '" + aPara[1].Trim() + "' ";
                }
                else if (aPara[0] == PosConst.TABLE_RESERVE_SEARCH_TYPE.TABLE_RESERVE_YM)
                {
                    sql += " AND RESERV_DT LIKE '" + aPara[1].Trim() + "%' ";
                }
                else if (aPara[0] == PosConst.TABLE_RESERVE_SEARCH_TYPE.TABLE_RESERVE_ALRAM)
                {
                    sql += " AND RESERV_DT = '" + m_cPosStatus.Base.SaleDate + "' AND ALARM_YN  = 'Y' AND CONFIRM <> 'Y' ";
                }

                sql += "   AND FILLER1 = '" + m_cPosStatus.Base.TrainingFlag + "' ";                                    // Add, 2017.03.06, 연습모드 
                sql += " ORDER BY RESERV_DT, RESERV_NO ";


                dtData = m_cMstService.Select(new string[] { sql });
                if (dtData == null)
                {
                    return UserCom.RST_ERR;
                }

                sReturn = UserCom.RST_OK;
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,     
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + 
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",               
                                     "Exception." + ex.Message);
                sReturn = UserCom.RST_ERR + ex.Message;
            }

            return sReturn;
        }

        /// <summary>
        /// 예약등록
        /// </summary>
        /// <param name="reservDate"></param>
        /// <param name="reservTime"></param>
        /// <param name="cashierNm"></param>
        /// <param name="custTelNo"></param>
        /// <param name="note"></param>
        /// <param name="alarmYN"></param>
        /// <param name="alarmTM"></param>
        /// <returns></returns>
        public string InsertData(string reservDate, string reservTime, string cashierNm, string custTelNo, string note, string alarmYN, string alarmTM)
        {
            try
            {
                string reservNo = this.GetReserveNo(reservDate);
                if (string.IsNullOrWhiteSpace(reservNo)) return UserCom.RST_ERR; 

                string fmt = "INSERT INTO POSMST..MST_RESERV "
                           + " (CMP_CD, STOR_CD, RESERV_NO, RESERV_DT, RESERV_TM, CASHIER_NM, TEL_NO, NOTE, ALARM_YN, ALARM_TM, CONFIRM "
                           + ", FILLER1, FILLER2, FILLER3, FILLER4, FILLER5, UPD_ID, UPD_DT, REG_ID, REG_DT) "
                           + "SELECT '{0}'  "                                                                           // CMP_CD         
                           + "     , '{1}'  "                                                                           // STOR_CD        
                           + "     , '{2}'  "                                                                           // RESERV_DT      
                           + "     , '{3}'  "                                                                           // RESERV_NO      
                           + "     , '{4}'  "                                                                           // RESERV_TM      
                           + "     , N'{5}' "                                                                           // CASHIER_NM     
                           + "     , '{6}'  "                                                                           // TEL_NO         
                           + "     , N'{7}' "                                                                           // NOTE           
                           + "     , '{8}'  "                                                                           // ALARM_YN       
                           + "     , '{9}'  "                                                                           // ALARM_TM       
                           + "     , '{10}'  "                                                                          // CONFIRM        
                           + "     , '{11}' "                                                                           // FILLER1  연습모드        
                           + "     , '{12}' "                                                                           // FILLER2        
                           + "     , '{13}' "                                                                           // FILLER3        
                           + "     , '{14}' "                                                                           // FILLER4        
                           + "     , '{15}' "                                                                           // FILLER5        
                           + "     , '{16}' "                                                                           // UPD_ID         
                           + "     , '{17}' "                                                                           // UPD_DT         
                           + "     , '{18}' "                                                                           // REG_ID         
                           + "     , '{19}' ";                                                                          // REG_DT         
                string sql = string.Format(fmt
                                         , m_cPosStatus.Base.CmpCd
                                         , m_cPosStatus.Base.StoreNo
                                         , reservNo
                                         , reservDate
                                         , reservTime.Replace(":", "")
                                         , cashierNm
                                         , custTelNo
                                         , ConvertDBStr(note)
                                         , alarmYN
                                         , alarmTM
                                         , "N"
                                         , m_cPosStatus.Base.TrainingFlag                                               // Add, 2017.03.06, 연습모드 
                                         , ""
                                         , ""
                                         , ""
                                         , ""
                                         , m_cPosStatus.Base.CashierNo
                                         , DateTime.Now.ToString("yyyyMMddHHmmss")
                                         , m_cPosStatus.Base.CashierNo
                                         , DateTime.Now.ToString("yyyyMMddHHmmss")
                                         );

                int ret = m_cMstService.Insert(new string[] { sql });
                return ret == UserCom.OK ? UserCom.RST_OK : UserCom.RST_ERR;
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,    
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",              
                                     "Exception." + ex.Message);
                return UserCom.RST_ERR + ex.Message;
            }
        }

        /// <summary>
        /// 예약수정
        /// </summary>
        /// <param name="reserveNo"></param>
        /// <param name="reserveDate"></param>
        /// <param name="reserveTime"></param>
        /// <param name="cashierNm"></param>
        /// <param name="custTelNo"></param>
        /// <param name="note"></param>
        /// <param name="alarmYN"></param>
        /// <param name="alarm"></param>
        /// <returns></returns>
        public string UpdateData(string reserveNo, string reserveDate, string reserveTime, string cashierNm, string custTelNo, string note, string alarmYN, string alarmTM)
        {
            try
            {
                string fmt = "UPDATE POSMST..MST_RESERV  \n"
                           + "   SET RESERV_DT  = '{3}'  \n"        // @reserv_dt
                           + "     , RESERV_TM  = '{4}'  \n"        // @reserv_tm
                           + "     , CASHIER_NM = N'{5}' \n"        // @cashier_nm
                           + "     , TEL_NO     = '{6}'  \n"        // @tel_no
                           + "     , NOTE       = N'{7}' \n"        // @note
                           + "     , ALARM_YN   = '{8}'  \n"        // @alarm_yn
                           + "     , ALARM_TM   = '{9}'  \n"        // @alarm_tm
                           + "     , FILLER1    = '{10}' \n"        // @filler1
                           + "     , FILLER2    = '{11}' \n"        // @filler2
                           + "     , FILLER3    = '{12}' \n"        // @filler3
                           + "     , FILLER4    = '{13}' \n"        // @filler4
                           + "     , FILLER5    = '{14}' \n"        // @filler5
                           + "     , UPD_ID     = '{15}' \n"        // @upd_id
                           + "     , UPD_DT     = '{16}' \n"        // @upd_dt
                           + "     , CONFIRM    = CASE WHEN '{8}' = 'Y' AND '{9}' <> ALARM_TM THEN 'N' ELSE CONFIRM END "
                           + " WHERE CMP_CD     = '{0}'  \n"        // @cmp_cd
                           + "   AND STOR_CD    = '{1}'  \n"        // @stor_cd
                           + "   AND RESERV_NO  = '{2}' ";          // @reserv_no

                string sql = string.Format(fmt
                                         , m_cPosStatus.Base.CmpCd
                                         , m_cPosStatus.Base.StoreNo
                                         , reserveNo
                                         , reserveDate
                                         , reserveTime
                                         , cashierNm 
                                         , custTelNo 
                                         , ConvertDBStr(note)
                                         , alarmYN
                                         , alarmTM
                                         , m_cPosStatus.Base.TrainingFlag                                               // Add, 2017.03.06, 연습모드 
                                         , ""
                                         , ""
                                         , ""
                                         , ""
                                         , m_cPosStatus.Base.CashierNo
                                         , DateTime.Now.ToString("yyyyMMddHHmmss")
                                         );

                int ret = m_cMstService.Update(new string[] { sql });
                return ret == UserCom.OK ? UserCom.RST_OK : UserCom.RST_ERR;
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,    
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",              
                                     "Exception." + ex.Message);
                return UserCom.RST_ERR + ex.Message;
            }
        }

        /// <summary>
        /// 알람확인
        /// </summary>
        /// <param name="reserveDate"></param>
        /// <param name="reserveNo"></param>
        /// <returns></returns>
        public string UpdateAlarmComfrim(string reserveNo)
        {
            try
            {
                string[] resvNoList = reserveNo.Split('|');
                if (resvNoList == null || resvNoList.Length == 0) return UserCom.RST_ERR;

                for (var i = 0; i < resvNoList.Length; i++)
                {
                    resvNoList[i] = string.Format("'{0}'", resvNoList[i].Replace("'", ""));
                }
                string list = string.Join(",",  resvNoList);

                string fmt = "UPDATE POSMST..MST_RESERV \n"
                           + "   SET CONFIRM    = 'Y'   \n"
                           + "     , UPD_ID     = '{4}' \n"         // @upd_id
                           + "     , UPD_DT     = '{5}' \n"         // @upd_dt
                           + " WHERE CMP_CD     = '{0}' \n"         // @cmp_cd
                           + "   AND STOR_CD    = '{1}' \n"         // @stor_cd
                           + "   AND RESERV_NO IN ({2}) \n"         // @reserv_no
                           + "   AND FILLER1    = '{3}' \n"                                                             // Add, 2017.03.06, 연습모드
                           ;
                string sql = string.Format(fmt
                                         , m_cPosStatus.Base.CmpCd
                                         , m_cPosStatus.Base.StoreNo
                                         , list
                                         , m_cPosStatus.Base.TrainingFlag                                               // Add, 2017.03.06, 연습모드 
                                         , m_cPosStatus.Base.CashierNo
                                         , DateTime.Now.ToString("yyyyMMddHHmmss")
                                         );

                int ret = m_cMstService.Update(new string[] { sql });
                return ret == UserCom.OK ? UserCom.RST_OK : UserCom.RST_ERR;
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "Exception." + ex.Message);
                return UserCom.RST_ERR + ex.Message;
            }
        }

        /// <summary>
        /// 예약번호 (yyMM + 000000)
        /// </summary>
        /// <param name="reserveDate"></param>
        /// <returns></returns>
        private string GetReserveNo(string reserveDate)
        {
            try
            {
                string yymm = reserveDate.Substring(2, 4);
                string fmt = "SELECT ISNULL(MAX(RESERV_NO), '') AS SEQ FROM POSMST..MST_RESERV WHERE CMP_CD = '{0}' AND STOR_CD = '{1}' AND RESERV_NO LIKE '{2}%' ";
                string sql = string.Format(fmt, m_cPosStatus.Base.CmpCd, m_cPosStatus.Base.StoreNo, yymm);

                DataTable dtData = m_cMstService.Select(new string[] { sql });
                if (dtData == null || dtData.Rows.Count <= 0) return string.Empty;

                int temp = 0;
                string maxNo = CmUtil.GetDataRowStr(dtData.Rows[0], "SEQ");
                if (string.IsNullOrWhiteSpace(maxNo))
                {
                    temp = 1;
                }
                else
                {
                    temp = CmUtil.IntParse(maxNo.Substring(4, 6)) + 1;
                }

                return string.Format("{0}{1, 6:000000}", yymm, temp);
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "Exception." + ex.Message);
                return string.Empty; 
            }
        }

        private string ConvertDBStr(string str)
        {
            return str.Replace("'", "''");
        }
    }
}
