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

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

namespace Cosmos.Service
{
    class SaleOpen : IDataServiceUs
    {
        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private PosStatus m_cPosStatus = new PosStatus();                           //기본정보 참조
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        private IMasterUs m_cMstService = null;                                     // 마스터 인터페이스

        protected IDataCommonUs m_cDataCommon = null;                               // 판매공통 모듈

        public SaleOpen()
        {
            m_cPosStatus = (PosStatus)StateObject.POS;                              // POS 기본정보
            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
            m_cMstService = (IMasterUs)sManager.InitServiceInstance(ServiceLists.ASV_MASTER.DLL, ServiceLists.ASV_MASTER.POS_MASTER);
        }

        /// <summary>
        /// 영업개시
        /// </summary>
        /// <returns></returns>
        public string Execute(string[] aParam)
        {
            string sRet = UserCom.RST_ERR;

            try
            {
                // 영업개시 IRT => 필요 값 (영업일자, 담당자번호)
                sRet = SaleOpenIrt(aParam[0], aParam[1], aParam[2]);
                if (sRet != UserCom.RST_OK) return sRet;

                sRet = UserCom.RST_OK;
            }
            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 sRet;
        }

        private string SaleOpenIrt(string sOpenDate, string sCashierNo, string sOpenType)
        {
            string sReturn = UserCom.RST_ERR;

            try
            {
                Hashtable htSendData = new Hashtable();
                Hashtable htRecvData = new Hashtable();

                htSendData.Add(Column.IQ_OPEN_REQ.DATA.INQ_TYPE, ItemConst.IRT_INQ_TYPE.OPEN_REQ);
                htSendData.Add(Column.IQ_OPEN_REQ.DATA.SALE_DT, sOpenDate);
                htSendData.Add(Column.IQ_OPEN_REQ.DATA.STOR_CD, m_cPosStatus.Base.StoreNo);
                htSendData.Add(Column.IQ_OPEN_REQ.DATA.POS_NO, m_cPosStatus.Base.PosNo);
                htSendData.Add(Column.IQ_OPEN_REQ.DATA.OP_NO, sCashierNo);
                htSendData.Add(Column.IQ_OPEN_REQ.DATA.OP_PWD, CmUtil.RPadH("", 16));
                htSendData.Add(Column.IQ_OPEN_REQ.DATA.OPEN_TY, sOpenType);
                htSendData.Add(Column.IQ_OPEN_REQ.DATA.SYS_DATE, System.DateTime.Now.ToString("yyyyMMddhhmmss"));
                htSendData.Add(Column.IQ_OPEN_REQ.DATA.RES_CD, "");
                htSendData.Add(Column.IQ_OPEN_REQ.DATA.RES_MSG, CmUtil.RPadH("", 100));

                string sRet = m_cDataCommon.ExecutePosIrt(ItemConst.COMM_MSG_TYPE.POSIRT, m_cPosStatus.Base.CommSvrIp, (int)m_cPosStatus.Base.PayInqPort, 10000, htSendData, ref htRecvData);
                if (sRet != UserCom.RST_OK)
                {
                    return sReturn;
                }

                if (htRecvData[Column.IQ_OPEN_RSP.DATA.RES_CD].ToString() != "00")
                {
                    sReturn = htRecvData[Column.IQ_OPEN_RSP.DATA.RES_MSG].ToString();
                    return sReturn;
                }

                //string sSysDateTime = htRecvData[Column.IQ_OPEN_RSP.DATA.SYS_DATE].ToString();

                //// 시스템 일자 동기화 => 영업개시 IRT 응답 전문에 있는 날짜로 설정
                //if (sSysDateTime.Length == 14)
                //{
                //    DateTime date;
                //    if (DateTime.TryParse(sSysDateTime.Substring(0, 4) + "-" + sSysDateTime.Substring(4, 2) + "-" + sSysDateTime.Substring(6, 2) +
                //        " " + sSysDateTime.Substring(8, 2) + ":" + sSysDateTime.Substring(10, 2) + ":" + sSysDateTime.Substring(12, 2), out date))
                //        BsUtil.SetSystemDateTime(date);
                //}

                sReturn = UserCom.RST_OK;
            }
            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 sReturn;
        }

        public string SetData(object oParam)
        {
            string sReturn = UserCom.RST_ERR;
            string sQuery = "";

            try
            {
                string sSaleDate = (string)oParam;  // 영업일자

                ////////////////////////////////////////////////////////////////////////////////
                // 거래번호 초기화
                ////////////////////////////////////////////////////////////////////////////////
                {
                    sQuery = " SELECT ISNULL(MAX(TRADE_NO), '0') AS TRADE_NO";
                    sQuery += " FROM POSLOG..TR_SALE_HEADER";
                    sQuery += " WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "'";
                    sQuery += "  AND SALE_DT = '" + sSaleDate + "'";
                    sQuery += "  AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "'";
                    sQuery += "  AND POS_NO = '" + m_cPosStatus.Base.PosNo + "'";

                    DataTable dtDataInfo = m_cMstService.Select(new string[] { sQuery });

                    m_cPosStatus.Base.TradeNo = "00001";
                    if (dtDataInfo != null && dtDataInfo.Rows.Count > 0)
                    {
                        string sMaxNo = dtDataInfo.Rows[0]["TRADE_NO"].ToString();
                        m_cPosStatus.Base.TradeNo = string.Format("{0:00000}", CmUtil.IntParse(sMaxNo) + 1);
                    }
                }

                ////////////////////////////////////////////////////////////////////////////////
                // 등록번호 초기화
                ////////////////////////////////////////////////////////////////////////////////
                {
                    sQuery = " SELECT ISNULL(MAX(REG_NO), '0') AS REG_NO";
                    sQuery += " FROM POSLOG..ETC_SALE_HEADER";
                    sQuery += " WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "'";
                    sQuery += "  AND SALE_DT = '" + sSaleDate + "'";
                    sQuery += "  AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "'";
                    sQuery += "  AND POS_NO = '" + m_cPosStatus.Base.PosNo + "'";

                    DataTable dtDataInfo = m_cMstService.Select(new string[] { sQuery });

                    m_cPosStatus.Base.RegNo = "00001";
                    if (dtDataInfo != null && dtDataInfo.Rows.Count > 0)
                    {
                        string sMaxNo = dtDataInfo.Rows[0]["REG_NO"].ToString();
                        m_cPosStatus.Base.RegNo = string.Format("{0:00000}", CmUtil.IntParse(sMaxNo) + 1);
                    }
                }

                ////////////////////////////////////////////////////////////////////////////////
                // 중간마감 차수 초기화
                ////////////////////////////////////////////////////////////////////////////////
                {
                    sQuery = " SELECT ISNULL(MAX(MID_CLOSE_SEQ), '0') AS MID_CLOSE_SEQ";
                    sQuery += " FROM POSLOG..TR_SALE_HEADER";
                    sQuery += " WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "'";
                    sQuery += "  AND SALE_DT = '" + sSaleDate + "'";
                    sQuery += "  AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "'";
                    sQuery += "  AND POS_NO = '" + m_cPosStatus.Base.PosNo + "'";
                    sQuery += "  AND TRADE_KINDPER = '" + ItemConst.TRAN_KIND.STATEMENT.MIDDLE_ADJUSTMENT + "' ";
                    sQuery += "  AND ISNULL(MID_CLOSE_SEQ, '0') <> '99' ";

                    DataTable dtDataInfo = m_cMstService.Select(new string[] { sQuery });

                    m_cPosStatus.Base.MidCloseSeq = "01";
                    if (dtDataInfo != null && dtDataInfo.Rows.Count > 0)
                    {
                        string sMaxNo = dtDataInfo.Rows[0]["MID_CLOSE_SEQ"].ToString();
                        m_cPosStatus.Base.MidCloseSeq = string.Format("{0:00}", CmUtil.IntParse(sMaxNo) + 1);
                    }
                }

                m_cPosStatus.Base.MsgSeqNo = "00001";
                // 개점 완료 FLAG 설정
                m_cPosStatus.Base.OpenClose = "1";
                // 영업일자 설정
                m_cPosStatus.Base.SaleDate = sSaleDate;
                // 개점 시간 저장.
                m_cPosStatus.Base.OpenDateTime = DateTime.Now.ToString("yyyyMMddHHmmss");

                // 거래번호 INI 파일 설정
                CmMessage m_PosConf = CmMessage.MakeMessageFromFile(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosSaleInfo);

                m_PosConf.GetMessage("MSGNO").MakeMessageOverWrite("MsgSeqNo", m_cPosStatus.Base.MsgSeqNo);
                m_PosConf.GetMessage("MSGNO").MakeMessageOverWrite("RegNo", m_cPosStatus.Base.RegNo);
                m_PosConf.GetMessage("MSGNO").MakeMessageOverWrite("TradeNo", m_cPosStatus.Base.TradeNo);
                m_PosConf.GetMessage("MSGNO").MakeMessageOverWrite("MidCloseSeq", m_cPosStatus.Base.MidCloseSeq);

                // 일자, 마감여부 INI 파일 설정
                m_PosConf.GetMessage("POSOPEN").MakeMessageOverWrite("OpenClose", m_cPosStatus.Base.OpenClose);
                m_PosConf.GetMessage("POSOPEN").MakeMessageOverWrite("SaleDate", sSaleDate);

                m_PosConf.GetMessage("POSOPEN").MakeMessageOverWrite("OpenDateTime", m_cPosStatus.Base.OpenDateTime);

                m_PosConf.MakeFileFromMessage(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosSaleInfo);

                // INI 파일 백업 주석 처리(20170927)
                // INI 백업처리
                //CmUtil.FileCopy(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosConfig, BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosConfig + ".bak", false);
                //CmUtil.FileCopy(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosSaleInfo, BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosSaleInfo + ".bak", false);
                //CmUtil.FileCopy(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosDevice, BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosDevice + ".bak", false);
                //CmUtil.FileCopy(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.CommPort, BaseCom.NxIniPath + PosConst.INI_FILE_NAME.CommPort + ".bak", false);

                DeletePosLogFile();         // 로그파일 삭제 처리
                DeletePosTrData();          // 거래데이터 삭제 처리

                DeleteMST_ORD();            // 후불 정보 초기화

                DeleteInterFaceFile();      // 외부 인터페이스 파일 삭제
                
                sReturn = UserCom.RST_OK;

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

        /// <summary>
        /// 데이터획득
        /// </summary>
        /// <param name="aParam">
        /// 0:MAINPOS_LAST_OPEN_DATE
        /// </param>
        /// <returns></returns>
        public object GetData(string[] aParam)
        {
            var ret = UserCom.RST_ERR;
            try
            {
                if (aParam.Length == 0) return ret;

                var cmd = aParam[0];
                switch (cmd)
                { 
                    case "CHECK_SUBPOS_OPEN":
                        ret = CheckSubPosOpen();
                        break;
                }

                return ret; 
            }
            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 UserCom.RST_ERR + ex.Message;
            }
        }

        /// <summary>
        /// 후불주문포스 개점 가능여부 및 메인포스 개점일자 조회 
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// 메인포스 개점 후 후불주문포스 개점이 가능
        /// </remarks>        
        private string CheckSubPosOpen()
        {
            try
            {
                // 후불 주문포스 일때만 조회 
                if (m_cPosStatus.Base.PosType != PosConst.POS_TYPE.DEFERRED_PAYMENT) return UserCom.RST_IGNORE;
                if (m_cPosStatus.Base.PosCommunicationType != PosConst.MAIN_POS_DIV.SUB_POS) return UserCom.RST_IGNORE;
                // 메인포스 정보 확인 
                if (string.IsNullOrWhiteSpace(m_cPosStatus.Base.MainPosNo)) return UserCom.RST_ERR + POS_MESSAGE.ERROR.MSG_0379;

                // m_cTrnStatus.Head.TradeDiv               // TRADE_DIV
                // m_cTrnStatus.Head.TrainModeYn            // TRAIN_MODE_YN
                // m_cTrnStatus.Head.TradeKind              // TRADE_KINDPER
                // public const string POS_OPEN = "97";     // 개점
                // public const string POS_CLOSE = "98";    // 폐점

                // 메인POS의 최근 개점정보 조회 
                var sql = "SELECT TOP 1 SALE_DT, TRADE_DIV, TRADE_KINDPER \n"
                        + "  FROM POSLOG..ETC_SALE_HEADER      \n"
                        + " WHERE CMP_CD         = '" + m_cPosStatus.Base.CmpCd + "' \n"
                        + "   AND STOR_CD        = '" + m_cPosStatus.Base.StoreNo + "' \n"
                        + "   AND POS_NO         = '" + m_cPosStatus.Base.MainPosNo + "' \n"
                        + "   AND TRAIN_MODE_YN  = '" + ItemConst.TRAINING_FLAG.TRAINING_NO + "' \n"
                        + "   AND TRADE_KINDPER IN ( '" + ItemConst.TRAN_KIND.LOG.POS_OPEN + "','" + ItemConst.TRAN_KIND.LOG.POS_CLOSE + "' ) \n"
                        + " ORDER BY SYS_DT DESC , PAY_TIME DESC \n"
                        ;
                DataTable dt = m_cMstService.Select(new string[] { sql });
                if (dt == null || dt.Rows.Count == 0)
                    return UserCom.RST_ERR + POS_MESSAGE.ERROR.MSG_0663;

                var mainOpenDate = CmUtil.GetDataRowStr(dt.Rows[0], "SALE_DT").Trim();
                var mainTradeDiv = CmUtil.GetDataRowStr(dt.Rows[0], "TRADE_DIV").Trim();
                var mainTradeKind = CmUtil.GetDataRowStr(dt.Rows[0], "TRADE_KINDPER").Trim();

                // 오픈여부 확인 => 정산취소 일때도 영업개시 가능하게(2017.06.20)
                if ((mainTradeDiv == ItemConst.TRAN_DIV.NORMAL && mainTradeKind == ItemConst.TRAN_KIND.LOG.POS_OPEN)
                    || (mainTradeDiv == ItemConst.TRAN_DIV.REFUND && mainTradeKind == ItemConst.TRAN_KIND.LOG.POS_CLOSE))
                {
                    // 개점일자 확인 
                    if (CmUtil.LongParse(mainOpenDate) < CmUtil.LongParse(DateTime.Now.ToString("yyyyMMdd")))
                        return UserCom.RST_ERR + POS_MESSAGE.ERROR.MSG_0663;
                }
                else
                {
                    return UserCom.RST_ERR + POS_MESSAGE.ERROR.MSG_0663;
                }
                //// 오픈여부 확인
                //if (mainTradeDiv != ItemConst.TRAN_DIV.NORMAL || mainTradeKind != ItemConst.TRAN_KIND.LOG.POS_OPEN) 
                //    return UserCom.RST_ERR + POS_MESSAGE.ERROR.MSG_0663;
                //// 개점일자 확인 
                //if (CmUtil.LongParse(mainOpenDate) < CmUtil.LongParse(DateTime.Now.ToString("yyyyMMdd")))
                //    return UserCom.RST_ERR + POS_MESSAGE.ERROR.MSG_0663;

                // 주문포스 개점 가능 
                return UserCom.RST_OK + mainOpenDate;
            }
            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 UserCom.RST_ERR + ex.Message;
            }
        }

        /// <summary>
        /// POS 로그파일 삭제
        /// </summary>
        private void DeletePosLogFile()
        {
            try
            {
                // 로그 파일 백업 처리
                for (int i = 10; i < 30; i++)
                {
                    CmUtil.BackUpLogToZipFile(BaseCom.NxLogPath, DateTime.Now.AddDays(-1 * i));
                }

                // 1개월 이전 로그 데이터 삭제
                // DateTime dtDelDate = DateTime.Now.AddMonths(-1);   2017.10.19 수정
                // 3개월 이전 데이터 삭제
                DateTime dtDelDate = DateTime.Now.AddMonths(-1 * 3);
                

                // 로그 파일 삭제 처리
                CmUtil.DeleteDirectoryInFile(BaseCom.NxLogPath, dtDelDate, 0);
                
                CmUtil.DeleteDirectoryInFile(BaseCom.NxBinPath + @"spcn_log\", dtDelDate, 0);
                CmUtil.DeleteDirectoryInFile(BaseCom.NxBinPath + @"spcncat_log\", dtDelDate, 0);
                CmUtil.DeleteDirectoryInFile(BaseCom.NxBinPath + @"spcndg_log\", dtDelDate, 0);
                CmUtil.DeleteDirectoryInFile(BaseCom.NxBinPath + @"SpcnLog\", dtDelDate, 0);
                CmUtil.DeleteDirectoryInFile(BaseCom.NxBinPath + @"spcnsecu_log\", dtDelDate, 0);
                CmUtil.DeleteDirectoryInFile(BaseCom.NxDataPath + @"SIGN\", dtDelDate, 0);

                // 7일 이전 마스터 백업 삭제
                dtDelDate = DateTime.Now.AddDays(-1 * 7);
                CmUtil.DeleteDirectoryInFile(BaseCom.NxBackPath + PosConst.BACKUP_PATH.DB, dtDelDate, 0);

                //#20171102 MST_ITEM_BAR_CD 마스터 수신 로그 생성 start
                //MST_ITEM_BAR_CD 로그 3일 이전 로그 데이터 삭제
                /*
                dtDelDate = DateTime.Now.AddDays(-1 * 3);
                CmUtil.DeleteDirectoryInFile(BaseCom.NxLogPath + @"MST_BAR\", dtDelDate, 0);
                */
                //#20171102 MST_ITEM_BAR_CD 마스터 수신 로그 생성 end
            }
            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>
        /// <returns></returns>
        public void DeletePosTrData()
        {
            try
            {
                //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // 3개월 이전 데이터 삭제
                //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                string sDelDate = DateTime.Now.AddMonths(-1 * 3).ToString("yyyyMMdd");

                //#20170901 TR_SALE_APPR_LOG, TR_STOR_EMP_WORK 데이터 보관주기 7일로 변경 start
                string sDel7Date = DateTime.Now.AddDays(-1 * 7).ToString("yyyyMMdd");
                //#20170901 TR_SALE_APPR_LOG, TR_STOR_EMP_WORK 데이터 보관주기 7일로 변경 end

                //#20170901 TR_SALE_APPR_LOG, TR_STOR_EMP_WORK 데이터 보관주기 7일로 변경 start
                //기존
                //string[] saQuery = new string[29];
                //변경
                string[] saQuery = new string[31];
                //#20170901 TR_SALE_APPR_LOG, TR_STOR_EMP_WORK 데이터 보관주기 7일로 변경 end
                saQuery[0] = " DELETE POSLOG..TR_CASHIER_TEST WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[1] = " DELETE POSLOG..TR_P_BOX_DTPER_STOCK WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND STOCK_DT < '" + sDelDate + "' ";
                saQuery[2] = " DELETE POSLOG..TR_SALE_ADMT WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[3] = ""; // " DELETE POSLOG..TR_SALE_ADMT_CHECK WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";

                //#20170901 TR_SALE_APPR_LOG, TR_STOR_EMP_WORK 데이터 보관주기 7일로 변경 start
                //기존
                //saQuery[4] = " DELETE POSLOG..TR_SALE_APPR_LOG WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                //변경
                saQuery[4] = " DELETE POSLOG..TR_SALE_APPR_LOG WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDel7Date + "' ";
                //#20170901 TR_SALE_APPR_LOG, TR_STOR_EMP_WORK 데이터 보관주기 7일로 변경 end

                saQuery[5] = " DELETE POSLOG..TR_SALE_CPI_RSLT WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[6] = " DELETE POSLOG..TR_SALE_DETAIL WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[7] = ""; // " DELETE POSLOG..TR_SALE_DPST_WTHDR WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[8] = " DELETE POSLOG..TR_SALE_ETC WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[9] = " DELETE POSLOG..TR_SALE_GUESTCNT WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[10] = " DELETE POSLOG..TR_SALE_HEADER WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[11] = " DELETE POSLOG..TR_SALE_JOURNAL WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[12] = " DELETE POSLOG..TR_SALE_PAY WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[13] = " DELETE POSLOG..TR_SALE_SIGN_LOG WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[14] = " DELETE POSLOG..TR_STOR_EMP WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND WORK_DT < '" + sDelDate + "' ";
                saQuery[15] = " DELETE POSLOG..TR_STORE_CLAIM WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[16] = " DELETE POSLOG..TR_STORE_VISIT WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND VISIT_DT < '" + sDelDate + "' ";
                saQuery[17] = " DELETE POSLOG..ETC_INTEGRITY_LOG WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[18] = " DELETE POSLOG..ETC_RESERV_INFO WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[19] = " DELETE POSLOG..ETC_SALE_CPI_RSLT WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[20] = " DELETE POSLOG..ETC_SALE_DETAIL WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[21] = " DELETE POSLOG..ETC_SALE_ETC WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[22] = " DELETE POSLOG..ETC_SALE_GUESTCNT WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[23] = " DELETE POSLOG..ETC_SALE_HEADER WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[24] = " DELETE POSLOG..ETC_SALE_JOURNAL WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[25] = " DELETE POSLOG..ETC_SALE_PAY WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[26] = " DELETE POSLOG..ETC_SALE_DPST_WTHDR WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[27] = " DELETE POSLOG..ETC_STOR_EQU_CHECK_LIST WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                saQuery[28] = " DELETE POSLOG..ETC_STOR_EQU_CHECK_DETAIL WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";

                //#20170901 TR_SALE_APPR_LOG, TR_STOR_EMP_WORK 데이터 보관주기 7일로 변경 start
                //TR_HPAPP_AFTER_SAVE 데이터 삭제 기능 추가
                saQuery[29] = " DELETE POSLOG..TR_STOR_EMP_WORK WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND WORK_DT < '" + sDel7Date + "' ";
                saQuery[30] = " DELETE POSLOG..TR_HPAPP_AFTER_SAVE WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND SALE_DT < '" + sDelDate + "' ";
                //#20170901 TR_SALE_APPR_LOG, TR_STOR_EMP_WORK 데이터 보관주기 7일로 변경 end

                m_cMstService.Delete(saQuery);

                //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // 종료일 31일 이전 마스터 삭제
                //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                string sMstDelDate = DateTime.Now.AddDays(-1 * 31).ToString("yyyyMMdd");

                string[] saMstQuery = new string[10];
                saMstQuery[0] = " DELETE POSMST..MST_CPI_CARD FROM POSMST..MST_CPI_CARD A " +
                                " JOIN POSMST..MST_CPI B ON A.CMP_CD=B.CMP_CD AND A.STOR_CD=B.STOR_CD AND A.CPI_CD=B.CPI_CD" +
                                " WHERE B.CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND B.FNSHDAY < '" + sMstDelDate + "' ";
                saMstQuery[1] = " DELETE POSMST..MST_CPI_COMPNT FROM POSMST..MST_CPI_COMPNT A " +
                                " JOIN POSMST..MST_CPI B ON A.CMP_CD=B.CMP_CD AND A.STOR_CD=B.STOR_CD AND A.CPI_CD=B.CPI_CD" +
                                " WHERE B.CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND B.FNSHDAY < '" + sMstDelDate + "' ";
                saMstQuery[2] = " DELETE POSMST..MST_CPI_HOUR FROM POSMST..MST_CPI_HOUR A " +
                                " JOIN POSMST..MST_CPI B ON A.CMP_CD=B.CMP_CD AND A.STOR_CD=B.STOR_CD AND A.CPI_CD=B.CPI_CD" +
                                " WHERE B.CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND B.FNSHDAY < '" + sMstDelDate + "' ";
                saMstQuery[3] = " DELETE POSMST..MST_CPI_ITEM FROM POSMST..MST_CPI_ITEM A " +
                                " JOIN POSMST..MST_CPI B ON A.CMP_CD=B.CMP_CD AND A.STOR_CD=B.STOR_CD AND A.CPI_CD=B.CPI_CD" +
                                " WHERE B.CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND B.FNSHDAY < '" + sMstDelDate + "' ";
                saMstQuery[4] = " DELETE POSMST..MST_CPI_LTTR_PRT FROM POSMST..MST_CPI_LTTR_PRT A " +
                                " JOIN POSMST..MST_CPI B ON A.CMP_CD=B.CMP_CD AND A.STOR_CD=B.STOR_CD AND A.CPI_CD=B.CPI_CD" +
                                " WHERE B.CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND B.FNSHDAY < '" + sMstDelDate + "' ";
                saMstQuery[5] = " DELETE POSMST..MST_CPI_PRT_MSG FROM POSMST..MST_CPI_PRT_MSG A " +
                                " JOIN POSMST..MST_CPI B ON A.CMP_CD=B.CMP_CD AND A.STOR_CD=B.STOR_CD AND A.CPI_CD=B.CPI_CD" +
                                " WHERE B.CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND B.FNSHDAY < '" + sMstDelDate + "' ";
                saMstQuery[6] = " DELETE POSMST..MST_CPI WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND FNSHDAY < '" + sMstDelDate + "' ";
                saMstQuery[7] = " DELETE POSMST..MST_CUST_DSP WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND FNSH_DT < '" + sDelDate + "' ";
                saMstQuery[8] = " DELETE POSMST..MST_ONLINE_CPN WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND FNSH_DAY < '" + sDelDate + "' ";
                
                //20170410 등록일자 기준으로 -7 이전꺼는 삭제
                saMstQuery[9] = " DELETE POSMST..MST_EMG_NOTE WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' " + 
                                " AND DATEADD(DAY,-7, GETDATE()) > CONVERT(DATETIME, SUBSTRING(REG_DT,1,4) + '-' + SUBSTRING(REG_DT,5,2) + '-' + SUBSTRING(REG_DT,7,2) + ' ' + SUBSTRING(REG_DT,9,2) + ':' + + SUBSTRING(REG_DT,11,2) + ':' + SUBSTRING(REG_DT,13,2)) ";

                m_cMstService.Delete(saMstQuery);

            }
            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>
        /// <returns></returns>
        public void DeleteMST_ORD()
        {
            try
            {
                #region 후불 정보 초기화
                string[] saMstQuery = new string[8];

                if (m_cPosStatus.Base.PosCommunicationType == PosConst.MAIN_POS_DIV.MAIN_POS)
                {
                    // 테이블마스터 매출정보 삭제
                    saMstQuery[0] = ""; 
                    saMstQuery[0] += " UPDATE POSMST..MST_TBL ";
                    saMstQuery[0] += "    SET TBL_USE_DIV = '0'";
                    saMstQuery[0] += "      , CUST_CNT = 0";
                    saMstQuery[0] += "      , FIRST_ORD_HOUR = ''";
                    saMstQuery[0] += "      , ORD_AMT = 0";
                    saMstQuery[0] += "      , TBL_OP_DIV = '0'";
                    saMstQuery[0] += "      , OP_FLOOR_CD = ''";
                    saMstQuery[0] += "      , OP_TBL_NO = ''";
                    saMstQuery[0] += "      , PAY_CMPT_DIV = ''";
                    saMstQuery[0] += "      , FILLER1 = ''";
                    saMstQuery[0] += "      , FILLER2 = ''";
                    saMstQuery[0] += "      , FILLER3 = ''";                                                               // Add, 2017.02.22, 테이블그룹순번
                    saMstQuery[0] += "  WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' ";
                    saMstQuery[0] += "    AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "' ";

                    // 주문데이터 삭제
                    saMstQuery[1] = " DELETE POSMST..MST_ORD ";

                    // 주방데이터 삭제
                    saMstQuery[2] = " DELETE POSMST..MST_KTCH_ORD_MSG ";

                    // 추가주방데이터 삭제
                    saMstQuery[3] = " DELETE POSMST..MST_KTCH_ORD_MSG_ADD ";

                    // 주방프린터 데이터 삭제
                    saMstQuery[4] = " DELETE POSMST..MST_KPS_ORD_MSG ";
                    
                    // KDS 데이터 삭제
                    saMstQuery[5] = " DELETE POSMST..MST_KDS_ORD_MSG ";

                    // 좌석메모 데이터 삭제 
                    saMstQuery[6] = " DELETE POSMST..MST_SEAT_MEMO ";

                    // 후불매장 주문번호 테이블 삭제 
                    saMstQuery[7] = "DELETE POSMST..MST_ORD_SEQ \n"
                                  + " WHERE CMP_CD      = '" + m_cPosStatus.Base.CmpCd + "' \n"
                                  + "   AND STOR_CD     = '" + m_cPosStatus.Base.StoreNo + "' \n"
                                  //#20171026 복합매장 메인포스가 아닌 주문포스인 경우 자기POS번호에 설정된 IP로 메인포스 IP 설정 start
                                  //+ "   AND SUB_STOR_CD = '" + (string.IsNullOrWhiteSpace(m_cPosStatus.Base.SubShopNo) ? m_cPosStatus.Base.StoreNo : m_cPosStatus.Base.SubShopNo) + "' \n"
                                  //#20171026 복합매장 메인포스가 아닌 주문포스인 경우 자기POS번호에 설정된 IP로 메인포스 IP 설정 end
                                  + "   AND SALE_DATE   < '" + DateTime.Now.AddDays(-7).ToString("yyyyMMdd") + "' ";

                    m_cMstService.Delete(saMstQuery);
                }
                #endregion
            }
            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>
        /// <returns></returns>
        public void DeleteInterFaceFile()
        {
            string sFileName = null;
            try
            {
                #region 외부 인터페이스 파일 삭제 

                if (m_cPosStatus.Base.PosCommunicationType == PosConst.MAIN_POS_DIV.MAIN_POS)
                {
                    // 3.왕진활현 인터페이스 파일
                    sFileName = @"C:\HOME\IMPORT\possalesdata.txt";
                    if (File.Exists(sFileName)) File.Delete(sFileName);                   
                }
                #endregion

            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
    }
}
