using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading;
using System.Reflection;

using Newtonsoft.Json;

using Cosmos.Common;
using Cosmos.BaseFrame;
using Cosmos.UserFrame;
using Cosmos.ServiceProvider;
using System.Data;
using Cosmos.CommonManager;
using System.IO;

namespace Cosmos.BackgroundDown
{
    class BackgroundDownMain : IWatcher, IWatcherBack
    {
        #region 클래스 변수 선언
        /// <summary>
        /// StateServer Object (StateServer 객체)
        /// </summary>
        private StateServer StateObject = (StateServer)StateServer.GetInstance();

        /// <summary>
        /// POS Status Value (POS 상태값)
        /// </summary>
        private PosStatus m_cPosStatus = null;

        /// <summary>
        /// Master Down Thread (Master Down 스레드)
        /// </summary>
        private Thread m_tBGDownProc = null;

        /// <summary>
        /// Master Down Proc Operation Yes/No (Master Down Proc 작동여부)
        /// </summary>
        private bool m_BGDOWNProcRunning = false;

        /// <summary>
        /// Thread Waiting Time (스레드 대기시간 ms)
        /// </summary>
        private int m_ThreadSleepTerm = 1000 * 60 * 60;

        /// <summary>
        /// 다운로드 모듈
        /// </summary>
        private Svr2Tran m_cSvr2Tran = null; 
        /// <summary>
        /// 데이터베이스 모듈
        /// </summary>
        private DatabaseMssql m_cSqlDbService = null;
        /// <summary>
        /// FTP 모듈
        /// </summary>
        private NetworkFtp m_cNetworkFTP = null;

        /// <summary>
        /// MSSQL DB 관련 객체
        /// </summary>
        private static SqlDB sqlDb = null;

        /// <summary>
        /// POS 프로그램 재기동 여부 체크용
        /// </summary>
        private static bool m_bPGMReboot = false;

        // 전송 소켓
        private static TcpSocket m_sendSocket = null;

        private Hashtable m_htBGMasterList = null;
        #endregion 클래스 변수 선언

        #region 생성자
        public BackgroundDownMain()
        {
            SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출

            m_cPosStatus = (PosStatus)StateObject.POS;

            m_cSqlDbService = new DatabaseMssql();
            m_cSvr2Tran = new Svr2Tran();
            m_cNetworkFTP = new NetworkFtp();
        }
        #endregion

        #region Master Down 데몬 기동/종료
        public void Start()
        {
            try
            {
                m_tBGDownProc = new Thread(new ThreadStart(ThreadBackgroundDownRun));
                m_BGDOWNProcRunning = true;
                m_tBGDownProc.Start();
            }
            catch(Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_DEBUG,
                                     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);
            }
        }

        public void Stop()
        {
            try
            {
                m_BGDOWNProcRunning = false;

                int count = 0;
                while(count < 10)
                {
                    if (m_tBGDownProc != null && m_tBGDownProc.IsAlive) m_BGDOWNProcRunning = false;
                    else break;

                    count++;
                    Thread.Sleep(100);
                }

                if (count == 10)
                {
                    UserLog.WriteLogFile(UserCom.LOG_DEBUG,
                                         UserCom.INFO_LEVEL,
                                         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 (함수명))
                                         "Force BackgroundDown Service Stop!!!");
                    m_tBGDownProc.Abort();
                }
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_DEBUG,
                                     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);
            }
        }
        #endregion 

        #region 프로그램 적용을 위한 재부팅 채크
        public bool PGMReBootCheck()
        {
            return m_bPGMReboot;
        }
        #endregion 

        #region BackgroundDown Main
        private void ThreadBackgroundDownRun()
        {
            int iResult = UserCom.NG1;
            string sRet = UserCom.RST_ERR;
            try
            {
                while(m_BGDOWNProcRunning)
                {
                    UserLog.WriteLogFile(UserCom.LOG_DEBUG,
                                         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 (함수명))
                                         "Backgroup Master Down Running");

                    #region 1 - 마스터 Download
                    // 선불POS 이거나 후불MAIN POS 일 경우에만 백그라운드 마스터 다운로드
                    if (m_cPosStatus.Base.PosType != PosConst.POS_TYPE.DEFERRED_PAYMENT ||
                       (m_cPosStatus.Base.PosType == PosConst.POS_TYPE.DEFERRED_PAYMENT && m_cPosStatus.Base.PosCommunicationType == PosConst.MAIN_POS_DIV.MAIN_POS))
                    {
                        if (m_cPosStatus.Base.MasterDown == "1")
                        {
                            // 마스터 배치 적용 성공 시 갱신될 시간
                            String sToBeMstBatchDownTime = DateTime.Now.ToString("yyyyMMddHHmmss");
                            Hashtable htBackgroundMaster = MasterListManager.GetBackgroundMaster();
                            int nFailedCnt = 0;
                            int nSuccessCnt = 0;
                            bool bResult = false;

                            int nTotalMstCnt = htBackgroundMaster.Count;
                            for (int nLoop = 0; nLoop < nTotalMstCnt; nLoop++)
                            {
                                // Dynamically call method.
                                Type type = typeof(BackgroundDownMain);
                                MethodInfo method = type.GetMethod(htBackgroundMaster[nLoop].ToString());

                                iResult = (int)method.Invoke(this, new object[] { m_cPosStatus.Base.MstBatchDownDate
                                                                             , m_cPosStatus.Base.StoreNo
                                                                             , m_cPosStatus.Base.BrandCd
                                                                             , m_cPosStatus.Base.StoreNo });
                                if (iResult < 0)
                                {
                                    nFailedCnt++;
                                    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 (함수명))
                                                         htBackgroundMaster[nLoop].ToString() + " Master(Background) download and insert failure");
                                }
                                else if (iResult > 0)
                                {
                                    nSuccessCnt++;
                                }
                            }

                            if (nFailedCnt == 0 && nSuccessCnt > 0)
                            {
                                m_cPosStatus.Base.MstBatchDownDate = sToBeMstBatchDownTime;

                                // PosSaleInfo.ini 저장
                                UpdatePosSaleInfo();
                            }
                        }
                    }
                    #endregion

                    #region 2 - 프로그램 Download
                    {
                        sRet = UserCom.RST_ERR;
                        sRet = LF_ProgramDownLoad_Search();                                     // DownLoad 목록 조회
                        sRet = LF_ProgramDownLoad();                                            // DownLoad 실행
                        //sRet = PGMUpdate_Apply(PosConst.PGM_UPDATE_DOWN_DIV.UPDATE);        // 프로그램 적용
                    }
                    #endregion

                    #region 마스터 수신 SQL 보정시 삭제
                    // update by wani(20170818) - Background Master Download Break;
                    m_BGDOWNProcRunning = false;
                    #endregion

                    int nNowSleepTerm = 0;
                    while(nNowSleepTerm < m_ThreadSleepTerm)
                    {
                        if (m_BGDOWNProcRunning == false) break;
                        Thread.Sleep(100);
                        nNowSleepTerm += 100;
                    }
                }
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_DEBUG,
                                    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);
            }
        }
        #endregion

        #region 마스터 요청 전문 생성
        private Hashtable GetPosMasterReqData(string sMasterDiv, string sUpdDt, string sStoreCd, string sSubStoreCd, string ProcCd)
        {
            Hashtable htReqData = null;
            try
            {
                htReqData = new Hashtable();

                // INQ Type 설정
                htReqData.Add(Column.IQ_POSMASTER_REQ.DATA.InqType, ItemConst.IRT_INQ_TYPE.POSMASTER_REQ);
                // 마스터 요청 구분 설정
                htReqData.Add(Column.IQ_POSMASTER_REQ.DATA.MasterDiv, sMasterDiv);
                // 점포코드 설정
                htReqData.Add(Column.IQ_POSMASTER_REQ.DATA.StorCd, sStoreCd);
                // SUB 점포코드 설정
                htReqData.Add(Column.IQ_POSMASTER_REQ.DATA.SubStorCd, sSubStoreCd);
                // 변경 일시 설정
                htReqData.Add(Column.IQ_POSMASTER_REQ.DATA.UpdDt, sUpdDt);
                // 전송데이터 Count 설정
                htReqData.Add(Column.IQ_POSMASTER_REQ.DATA.DataCount, string.Empty);
                // 요청코드 설정
                htReqData.Add(Column.IQ_POSMASTER_REQ.DATA.ProcCd, ProcCd);
                // 응답코드 설정
                htReqData.Add(Column.IQ_POSMASTER_REQ.DATA.ResCd, string.Empty);
            }
            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);
            }
            return htReqData;
        }
        #endregion 마스터 요청 전문 생성

        #region 마스터 요청/응답 전문 송수신 모듈
        /// <summary>
        /// 마스터 요청 전문 SEND / RECEIVE
        /// </summary>
        /// <param name="sIp"></param>
        /// <param name="iPort"></param>
        /// <param name="iTimeout"></param>
        /// <param name="sCommData"></param>
        /// <param name="htData"></param>
        /// <param name="sbRecvData"></param>
        /// <returns></returns>
        private int MstIRTSendReceive(string sIp, int iPort, int iTimeout, string sCommData, Hashtable htData, ref StringBuilder sbRecvData)
        {
            int nStat = BaseCom.NG1;
            string sRecvCommHeader = string.Empty;
            string sRecvData = string.Empty;

            try
            {
                string sJsonSendData = "";
                string sJsonReceiveData = "";
                Hashtable htRecvData = null;

                sbRecvData = new StringBuilder();

                m_sendSocket = new TcpSocket(sIp, iPort, iTimeout);

                // Delay time to close connection is unlimited.
                nStat = m_sendSocket.Connect(-1);

                if(nStat == BaseCom.OK)
                {
                    while(true)
                    {
                        sJsonSendData = JsonConvert.SerializeObject(htData);

                        // sJsonSendData 암호화 처리는 이 곳에서...

                        Byte[] sBytTempBuff = Encoding.UTF8.GetBytes(sJsonSendData);
                        string sDataLen = string.Format("{0:000000}", sBytTempBuff.Length);

                        sCommData = sDataLen + sCommData.Substring(TcpSocket.COMM_MSGLEN);

                        // 마스터 송수신 로그 제거(20170524)
                        //UserLog.WriteLogFile(UserCom.LOG_SOCK,
                        //                     UserCom.WARNING_LEVEL,
                        //                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (Project Name (프로젝트명))
                        //                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                        //                     CmUtil.RPadH("[SEND" + ":" + sIp + ":" + iPort, 27) + "] " + sCommData + sJsonSendData);

                        // 전문 송신
                        nStat = SendReceiveMstData(sCommData + sJsonSendData, ref sJsonReceiveData);
                        if(nStat == BaseCom.OK)
                        {
                            // 마스터 송수신 로그 제거(20170524)
                            //UserLog.WriteLogFile(UserCom.LOG_SOCK,
                            //                     UserCom.WARNING_LEVEL,
                            //                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (Project Name (프로젝트명))
                            //                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                            //                     CmUtil.RPadH("[RECV" + ":" + sIp + ":" + iPort, 27) + "] " + sJsonReceiveData);

                            if(sJsonReceiveData != null && sJsonReceiveData != string.Empty)
                            {
                                sRecvCommHeader = sJsonReceiveData.Substring(0, TcpSocket.COMM_HEAD_LEN);
                                sRecvData = sJsonReceiveData.Substring(TcpSocket.COMM_HEAD_LEN);

                                // sRecvData 복호화 처리는 이 곳에서...

                                htRecvData = JsonConvert.DeserializeObject<Hashtable>(sRecvData);

                                if(int.Parse(htRecvData[Column.IQ_POSMASTER_RSP.DATA.Count].ToString().Trim()) != 0)
                                {
                                    // StringBuilder에 추가
                                    sbRecvData.Append(htRecvData[Column.IQ_POSMASTER_RSP.DATA.Data].ToString());
                                }
                                else
                                {
                                    break;
                                }
                                // 요청전문의 요청 코드 변경
                                htData[Column.IQ_POSMASTER_REQ.DATA.ProcCd] = "1";
                            }
                        }
                        else
                        {
                            return BaseCom.NG1;
                        }
                    }

                    nStat = BaseCom.OK;
                }
            }
            catch (Exception e)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                    "NetworkJSON.IRTSendReceive()", e.ToString());
            }
            finally
            {
                m_sendSocket.Close();
            }

            return nStat;
        }
        private int SendReceiveMstData(string pSendData, ref string pRecvData)
        {
            int nRecvLen = 0;
            int nStat = BaseCom.NG;
            try
            {
                nRecvLen = m_sendSocket.SendReceiveMstData(pSendData, ref pRecvData);
                if (nRecvLen > 0)
                {
                    nStat = BaseCom.OK;
                }
            }
            catch (Exception e)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                    System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                    e.ToString());
            }

            return nStat;
        }
        #endregion 마스터 요청/응답 전문 송수신 모듈

        #region 긴급공지 상태 변경
        /// <summary>
        /// 긴급공지 상태 변경
        /// </summary>
        /// <param name="sMsgCode"></param>
        /// <param name="sMsgDiv"></param>
        /// <param name="sSendFlag"></param>
        /// <returns></returns>
        private int EmgNoteFlgUpdate(string sStartDT, string sMsgCode, string sMsgDiv, string sDownFlag)
        {
            int iRet = UserCom.NG;
            string sQuery = string.Empty;
            try
            {

                if (sStartDT.Trim() == "" || sMsgCode.Trim() == "" || sMsgDiv.Trim() == "") return iRet;

                sqlDb = new SqlDB(m_cPosStatus.Base.LocalDbSource,
                                      m_cPosStatus.Base.LocalDbCatalog,
                                      m_cPosStatus.Base.LocalDbUserID,
                                      m_cPosStatus.Base.LocalDbPassword);

                sQuery += " UPDATE POSMST..MST_EMG_NOTE \n";
                sQuery += "    SET DOWN_YN = '" + sDownFlag + "' \n";
                sQuery += "      , UPD_DT = '" + DateTime.Now.ToString("yyyyMMddHHmmss") + "' \n";

                sQuery += " WHERE 1 = 1 \n";
                sQuery += "   AND CMP_CD   = '" + m_cPosStatus.Base.CmpCd + "' \n";
                sQuery += "   AND STOR_CD  = '" + m_cPosStatus.Base.StoreNo + "' \n";
                sQuery += "   AND POS_NO   = '" + m_cPosStatus.Base.PosNo + "' \n";
                sQuery += "   AND START_DT   = '" + sStartDT + "' \n";
                sQuery += "   AND MSG_CODE = '" + sMsgCode + "' \n";
                sQuery += "   AND MSG_DIV  = '" + sMsgDiv + "' \n";
                sQuery = sQuery.Replace("\t", " ");

                //iRet = m_cSqlDbService.DBExecuteNonQuery (sQuery);

                iRet = sqlDb.DBExecuteNonQuery(sQuery, CommandType.Text, (System.Data.SqlClient.SqlParameter[])null);

            }
            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);
            }

            return iRet;
        }
        #endregion 

        #region Master Download 처리

        #region 19 - 상품 마스터 Download / Insert
        public int MST_ITEM(string sUpdateDT, string sStoreCd, string sSubBrandCd, string sSubStoreCd)
        {
            string sIrtData = string.Empty;
            string sRecvData = string.Empty;
            Hashtable htReqData = null;
            StringBuilder sbRecvData = null;
            int iReturn = BaseCom.NG;

            try
            {
                htReqData = new Hashtable();

                // 마스터 요청 Hashtable Data 생성
                htReqData = GetPosMasterReqData(MasterLists.MST_ITEM.DIV, sUpdateDT, sStoreCd, sSubStoreCd, "0");

                // 마스터 전문 송수신
                iReturn = this.MstIRTSendReceive(m_cPosStatus.Base.CommSvrIp,
                                                 (int)m_cPosStatus.Base.MstPort,
                                                 10000,
                                                 ItemColumn.MakeCommHeader(0, ItemConst.COMM_MSG_TYPE.MSTIRT, sSubBrandCd),
                                                 htReqData,
                                                 ref sbRecvData);

                if(iReturn == BaseCom.OK)
                {
                    // 행구분자(#~)로 구분한 Row Data를 string array에 저장
                    string[] aRowDatas = (sbRecvData.ToString()).Split(new string[] { "#~" }, StringSplitOptions.RemoveEmptyEntries);

                    //System.Console.WriteLine("{0} - start({1})", DateTime.Now.ToString("HH:mm:ss.fff"), aRowDatas.Length.ToString());

                    // DB Insert
                    iReturn = UpdateMST_ITEM(aRowDatas);

                    //System.Console.WriteLine("{0} - end)", DateTime.Now.ToString("HH:mm:ss.fff"));
                }

                return iReturn;
            }
            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);

                return UserCom.NG1;
            }
        }

        private int UpdateMST_ITEM(string[] aRowDatas)
        {
            string sQuery = string.Empty;
            //string sInsQuery = string.Empty;
            //string sUpdQuery = string.Empty;
            string sSQL = string.Empty;
            string[] aParams = null;

            try
            {
                #region UPDATE / INSERT Query
                sQuery = "UPDATE POSMST..MST_ITEM \n"
                       + "   SET L_CLSS = '{4}', M_CLSS = '{5}', S_CLSS = '{6}', FLAVOUR_DIV = '{7}', FLAVOUR_QTY = {8} \n"
                       + "     , FLAVOUR_STOCK = {9}, SHTCUT_ITEMNM = N'{10}', ITEM_NM = N'{11}', TAKE_IN_SALE_AMT = {12}, TAKE_OUT_SALE_AMT = {13} \n"
                       + "     , IF_MENU1 = '{14}', IF_MENU2 = '{15}', OPEN_ITEM_DIV = '{16}', DISPO_ITEM_DIV = '{17}', SUB_SET_MNG_TYPE = '{18}' \n"
                       + "     , ITEM_TAX_AMT_DIV = '{19}', TAKE_IN_VAT_CD = '{20}', TAKE_OUT_VAT_CD = '{21}', ITEM_COST = {22} \n"
                       + "     , SALE_PRMT_YN = '{23}', SALE_NOQ = {24}, FREE_GIFT_YN = '{25}', DC_PRMT_YN = '{26}', ACCUM_PRMT_YN = '{27}' \n"
                       + "     , SVC_FEE_TRGT_YN = '{28}', BTN_ITEM_IMG = '{29}', NEW_ITEM_START_DT = '{30}', NEW_ITEM_FNSH_DT = '{31}', ITEM_TYPE = '{32}' \n"
                       + "     , TIME_BAR_CD_YN = '{33}', DISTBT_EXPIRE_NOD = '{34}', ALCOHOL_ITEM_TYPE = '{35}', SALE_START_DT = '{36}', SALE_FNSH_DT = '{37}' \n"
                       + "     , COOP_CARD_DC_NOADM_YN = '{38}', CAKE_EXCHNG_CPN_USE_POSS_YN = '{39}', ITEM_INFO = N'{40}', CALORY_INFO = N'{41}', SALE_IMG_FILE_NM = '{42}' \n"
                       + "     , FILLER1 = '{43}', FILLER2 = '{44}', FILLER3 = '{45}', FILLER4 = '{46}', FILLER5 = '{47}' \n"
                       + "     , USE_YN = '{48}', UPD_DT = '{49}' \n"
                       + " WHERE CMP_CD = '{0}' \n"
                       + "   AND STOR_CD = '{1}' \n"
                       + "   AND SUB_STOR_CD = '{2}' \n"
                       + "   AND ITEM_CD = '{3}' \n"
                       + "IF @@ROWCOUNT = 0 \n"
                       + "INSERT INTO POSMST..MST_ITEM \n"
                       + "       ( CMP_CD, STOR_CD, SUB_STOR_CD, ITEM_CD, L_CLSS \n"
                       + "       , M_CLSS, S_CLSS, FLAVOUR_DIV, FLAVOUR_QTY, FLAVOUR_STOCK \n"
                       + "       , SHTCUT_ITEMNM, ITEM_NM, TAKE_IN_SALE_AMT, TAKE_OUT_SALE_AMT, IF_MENU1 \n"
                       + "       , IF_MENU2, OPEN_ITEM_DIV, DISPO_ITEM_DIV, SUB_SET_MNG_TYPE, ITEM_TAX_AMT_DIV \n"
                       + "       , TAKE_IN_VAT_CD, TAKE_OUT_VAT_CD, ITEM_COST, SALE_PRMT_YN, SALE_NOQ \n"
                       + "       , FREE_GIFT_YN, DC_PRMT_YN, ACCUM_PRMT_YN, SVC_FEE_TRGT_YN, BTN_ITEM_IMG \n"
                       + "       , NEW_ITEM_START_DT, NEW_ITEM_FNSH_DT, ITEM_TYPE, TIME_BAR_CD_YN, DISTBT_EXPIRE_NOD \n"
                       + "       , ALCOHOL_ITEM_TYPE, SALE_START_DT, SALE_FNSH_DT, COOP_CARD_DC_NOADM_YN, CAKE_EXCHNG_CPN_USE_POSS_YN \n"
                       + "       , ITEM_INFO, CALORY_INFO, SALE_IMG_FILE_NM, FILLER1, FILLER2 \n"
                       + "       , FILLER3, FILLER4, FILLER5, USE_YN, REG_DT ) \n"
                       + "VALUES \n"
                       + "       ( '{0}', '{1}', '{2}', '{3}', '{4}' \n"
                       + "       , '{5}', '{6}', '{7}', {8}, {9} \n"
                       + "       , N'{10}', N'{11}', {12}, {13}, '{14}' \n"
                       + "       , '{15}', '{16}', '{17}', '{18}', '{19}' \n"
                       + "       , '{20}', '{21}', {22}, '{23}', {24} \n"
                       + "       , '{25}', '{26}', '{27}', '{28}', '{29}' \n"
                       + "       , '{30}', '{31}', '{32}', '{33}', '{34}' \n"
                       + "       , '{35}', '{36}', '{37}', '{38}', '{39}' \n"
                       + "       , N'{40}', N'{41}', '{42}', '{43}', '{44}' \n"
                       + "       , '{45}', '{46}', '{47}', '{48}', '{49}' ) \n";
                #endregion UPDATE / INSERT Query

                if (aRowDatas.Length > 0)
                {
                    // 현재 Row Counting
                    int nCnt = 0;

                    sqlDb = new SqlDB(m_cPosStatus.Base.LocalDbSource,
                                      m_cPosStatus.Base.LocalDbCatalog,
                                      m_cPosStatus.Base.LocalDbUserID,
                                      m_cPosStatus.Base.LocalDbPassword);

                    int iRet = UserCom.NG;

                    foreach (string sRowData in aRowDatas)
                    {
                        nCnt++;
                        aParams = sRowData.Split('|');

                        sSQL = string.Format( sQuery
                                            , aParams[0], m_cPosStatus.Base.StoreNo, aParams[2], aParams[3], aParams[4]
                                            , aParams[5], aParams[6], aParams[7], aParams[8], aParams[9]
                                            , aParams[10], aParams[11], aParams[12], aParams[13], aParams[14]
                                            , aParams[15], aParams[16], aParams[17], aParams[18], aParams[19]
                                            , aParams[20], aParams[21], aParams[22], aParams[23], aParams[24]
                                            , aParams[25], aParams[26], aParams[27], aParams[28], aParams[29]
                                            , aParams[30], aParams[31], aParams[32], aParams[33], aParams[34]
                                            , aParams[35], aParams[36], aParams[37], aParams[38], aParams[39]
                                            , aParams[40], aParams[41], aParams[42], aParams[43], aParams[44]
                                            , aParams[45], aParams[46], aParams[47], aParams[48], DateTime.Now.ToString("yyyyMMddHHmmsss"));

                        iRet = sqlDb.DBExecuteNonQuery(sSQL, System.Data.CommandType.Text, (System.Data.SqlClient.SqlParameter[])null);
                        if (iRet != UserCom.OK)
                        {
                            UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                                 UserCom.WARNING_LEVEL,
                                                 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 (함수명))
                                                 sSQL);

                            return UserCom.NG1;
                        }
                    }
                    return UserCom.OK;
                }
                else
                {
                    return UserCom.NG;
                }
            }
            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);

                return UserCom.NG1;
            }
        }
        #endregion 19 - 상품 마스터 Download / Insert

        #region 36 - 캠페인 상품 그룹관리 마스터 Download / Insert
        public int MST_CPI_COMPNT(string sUpdateDT, string sStoreCd, string sSubBrandCd, string sSubStoreCd)
        {
            string sIrtData = string.Empty;
            string sRecvData = string.Empty;
            Hashtable htReqData = null;
            StringBuilder sbRecvData = null;
            int iReturn = BaseCom.NG;

            try
            {
                htReqData = new Hashtable();

                // 마스터 요청 Hashtable Data 생성
                htReqData = GetPosMasterReqData(MasterLists.MST_CPI_COMPNT.DIV, sUpdateDT, sStoreCd, sSubStoreCd, "0");

                // 마스터 전문 송수신
                iReturn = this.MstIRTSendReceive(m_cPosStatus.Base.CommSvrIp,
                                                 (int)m_cPosStatus.Base.MstPort,
                                                 10000,
                                                 ItemColumn.MakeCommHeader(0, ItemConst.COMM_MSG_TYPE.MSTIRT, sSubBrandCd),
                                                 htReqData,
                                                 ref sbRecvData);

                if (iReturn == BaseCom.OK)
                {
                    // 행구분자(#~)로 구분한 Row Data를 string array에 저장
                    string[] aRowDatas = (sbRecvData.ToString()).Split(new string[] { "#~" }, StringSplitOptions.RemoveEmptyEntries);

                    //System.Console.WriteLine("{0} - start({1})", DateTime.Now.ToString("HH:mm:ss.fff"), aRowDatas.Length.ToString());

                    // DB Insert
                    iReturn = UpdateMST_CPI_COMPNT(aRowDatas);

                    //System.Console.WriteLine("{0} - end)", DateTime.Now.ToString("HH:mm:ss.fff"));
                }

                return iReturn;
            }
            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);

                return UserCom.NG1;
            }
        }

        private int UpdateMST_CPI_COMPNT(string[] aRowDatas)
        {
            string sQuery = string.Empty;
            string sSQL = string.Empty;
            //string sInsQuery = string.Empty;
            //string sUpdQuery = string.Empty;
            string[] aParams = null;

            try
            {
                #region UPDATE / INSERT Query
                sQuery = "UPDATE POSMST..MST_CPI_COMPNT \n"
                       + "   SET CPI_COND_TYPE = '{4}', QTY_AMT = {5}, CPI_DC_TYPE = '{6}', DC_RATE_QTY_AMT = {7}, DC_MAX_AMT = {8} \n"
                       + "     , FILLER1 = '{9}', FILLER2 = '{10}', FILLER3 = '{11}', FILLER4 = '{12}', FILLER5 = '{13}' \n"
                       + "     , USE_YN = '{14}', UPD_DT = '{15}' \n"
                       + " WHERE CMP_CD = '{0}' \n"
                       + "   AND STOR_CD = '{1}' \n"
                       + "   AND CPI_CD = '{2}' \n"
                       + "   AND CPI_ITEM_GRP_CD = '{3}' \n"
                       + "IF @@ROWCOUNT = 0 \n"
                       + "INSERT INTO POSMST..MST_CPI_COMPNT \n"
                       + "       ( CMP_CD, STOR_CD, CPI_CD, CPI_ITEM_GRP_CD, CPI_COND_TYPE \n"
                       + "       , QTY_AMT, CPI_DC_TYPE, DC_RATE_QTY_AMT, DC_MAX_AMT, FILLER1 \n"
                       + "       , FILLER2, FILLER3, FILLER4, FILLER5, USE_YN \n"
                       + "       , REG_DT ) \n"
                       + "VALUES \n"
                       + "       ( '{0}', '{1}', '{2}', '{3}', '{4}' \n"
                       + "       , {5}, '{6}', {7}, {8}, '{9}' \n"
                       + "       , '{10}', '{11}', '{12}', '{13}', '{14}' \n"
                       + "       , '{15}' ) \n";
                #endregion UPDATE / INSERT Query

                if (aRowDatas.Length > 0)
                {
                    // 현재 Row Counting
                    int nCnt = 0;

                    sqlDb = new SqlDB(m_cPosStatus.Base.LocalDbSource,
                                      m_cPosStatus.Base.LocalDbCatalog,
                                      m_cPosStatus.Base.LocalDbUserID,
                                      m_cPosStatus.Base.LocalDbPassword);

                    int iRet = UserCom.NG;

                    foreach (string sRowData in aRowDatas)
                    {
                        nCnt++;
                        aParams = sRowData.Split('|');

                        sSQL = string.Format( sQuery
                                            , aParams[0], aParams[1], aParams[2], aParams[3], aParams[4]
                                            , aParams[5], aParams[6], aParams[7], aParams[8], aParams[9]
                                            , aParams[10], aParams[11], aParams[12], aParams[13], aParams[14]
                                            , DateTime.Now.ToString("yyyyMMddHHmmsss"));
                                                
                        iRet = sqlDb.DBExecuteNonQuery(sSQL, System.Data.CommandType.Text, (System.Data.SqlClient.SqlParameter[])null);
                        if (iRet != UserCom.OK)
                        {
                            UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                                 UserCom.WARNING_LEVEL,
                                                 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 (함수명))
                                                 sSQL);

                            return UserCom.NG1;
                        }
                    }
                    return UserCom.OK;
                }
                else
                {
                    return UserCom.NG;
                }
            }
            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);

                return UserCom.NG1;
            }
        }
        #endregion 36 - 캠페인 상품 그룹관리 마스터 Download / Insert

        #region 37 - 캠페인 마스터 Download / Insert
        public int MST_CPI(string sUpdateDT, string sStoreCd, string sSubBrandCd, string sSubStoreCd)
        {
            string sIrtData = string.Empty;
            string sRecvData = string.Empty;
            Hashtable htReqData = null;
            StringBuilder sbRecvData = null;
            int iReturn = BaseCom.NG;

            try
            {
                htReqData = new Hashtable();

                // 마스터 요청 Hashtable Data 생성
                htReqData = GetPosMasterReqData(MasterLists.MST_CPI.DIV, sUpdateDT, sStoreCd, sSubStoreCd, "0");

                // 마스터 전문 송수신
                iReturn = this.MstIRTSendReceive(m_cPosStatus.Base.CommSvrIp,
                                                 (int)m_cPosStatus.Base.MstPort,
                                                 10000,
                                                 ItemColumn.MakeCommHeader(0, ItemConst.COMM_MSG_TYPE.MSTIRT, sSubBrandCd),
                                                 htReqData,
                                                 ref sbRecvData);

                if (iReturn == BaseCom.OK)
                {
                    // 행구분자(#~)로 구분한 Row Data를 string array에 저장
                    string[] aRowDatas = (sbRecvData.ToString()).Split(new string[] { "#~" }, StringSplitOptions.RemoveEmptyEntries);

                    //System.Console.WriteLine("{0} - start({1})", DateTime.Now.ToString("HH:mm:ss.fff"), aRowDatas.Length.ToString());

                    // DB Insert
                    iReturn = UpdateMST_CPI(aRowDatas);

                    //System.Console.WriteLine("{0} - end)", DateTime.Now.ToString("HH:mm:ss.fff"));
                }

                return iReturn;
            }
            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);

                return UserCom.NG1;
            }
        }

        private int UpdateMST_CPI(string[] aRowDatas)
        {
            string sQuery = string.Empty;
            string sSQL = string.Empty;
            //string sInsQuery = string.Empty;
            //string sUpdQuery = string.Empty;
            string[] aParams = null;

            try
            {
                #region UPDATE / INSERT Query
                sQuery = "UPDATE POSMST..MST_CPI \n"
                       + "   SET CPI_NM = N'{3}', STARTDAY = '{4}', FNSHDAY = '{5}', REPT_YN = '{6}', REPT_APPNT_TYPE = '{7}' \n"
                       + "     , REPT_WEEK = '{8}', REPT_DT = '{9}', DUP_APPLY_YN = '{10}', BASIC_RULE_EXCEP_YN = '{11}', TELECOM_COOP_DUP_PRMT_YN = '{12}' \n"
                       + "     , PRRTY = {13}, TRGT_CUST_TYPE = '{14}', CPI_CUST_BNFT_TYPE = '{15}', ITEM_APPLY_METHD = '{16}', CUST_PAY_TYPE = '{17}' \n"
                       + "     , TRGT_AMT_TYPE = '{18}', TRGT_AMT = {19}, QTY_LMT_YN = '{20}', LMT_QTY = {21}, QTY_LMT_STD = '{22}' \n"
                       + "     , HP_CUST_JOIN_LMT_YN = '{23}', HP_CUST_MAX_JOIN_CNT = {24}, HP_CUST_JOIN_LMT_STD = '{25}', BASIC_HP_ACCUM_YN = '{26}', BASIC_HP_ACCUM_STD = '{27}' \n"
                       + "     , ADD_HP_ACCUM_TELECOM_DIV = '{28}', ADD_HP_ACCUM_TRGT_STD = '{29}', ADD_HP_ACCUM_RATE = {30}, ADD_HP_ACCUM_AF_DIV = '{31}', ADD_HP_ACCUM_CD1 = '{32}' \n"
                       + "     , ADD_HP_ACCUM_CD2 = '{33}', OFFER_ID = '{34}', FREE_GIFT_PROVD_STD = '{35}', FREE_GIFT_STD_AMT = {36}, FREE_GIFT_PROVD_QTY = {37} \n"
                       + "     , FREE_GIFT_ADD_SALE_YN = '{38}', CPI_INFO = N'{39}', CPI_EXPLN = N'{40}', LTTR_MAX_GRADE = {41}, CUST_DSP_FILE_DIV = '{42}' \n"
                       + "     , CUST_DSP_FILENM = '{43}', STAMP_QTY = {44}, SOUND_FILE_DIV = '{45}', SOUND_FILE_NM = '{46}', TTS_DSCRP = N'{47}' \n"
                       + "     , SOUND_FILE_PLAY_CHK_PNT = '{48}', USE_YN = '{49}', FILLER1 = '{50}', FILLER2 = '{51}', FILLER3 = '{52}' \n"
                       + "     , FILLER4 = '{53}', FILLER5 = '{54}', UPD_DT = '{55}', JOIN_QUSTN_YN = '{56}', PRGRS_STATUS = '{57}' \n"
                       + "     , ITEM_DUP_PRMT_YN = '{58}', LTTR_MULTI_PRT_YN = '{59}', CPI_DC_PAY_WAY = '{60}', CPI_BILL_NM = N'{61}', QTY_LIMIT_MSG = N'{62}' \n"
                       + "     , HP_CUST_LVL = '{63}', DC_NOADM_PASS_YN = '{64}' \n"

                       //#15583 캠페인 기능 개선 요청 start
                       + "     , MOBILE_CPN_DUP_PRMT_YN = '{65}', HPY_CPN_DUP_PRMT_YN = '{66}' \n"
                       //#15583 캠페인 기능 개선 요청 end

                       + " WHERE CMP_CD = '{0}' \n"
                       + "   AND STOR_CD = '{1}' \n"
                       + "   AND CPI_CD = '{2}' \n"
                       + "IF @@ROWCOUNT = 0 \n"
                       + "INSERT INTO POSMST..MST_CPI \n"
                       + "       ( CMP_CD, STOR_CD, CPI_CD, CPI_NM, STARTDAY \n"
                       + "       , FNSHDAY, REPT_YN, REPT_APPNT_TYPE, REPT_WEEK, REPT_DT \n"
                       + "       , DUP_APPLY_YN, BASIC_RULE_EXCEP_YN, TELECOM_COOP_DUP_PRMT_YN, PRRTY, TRGT_CUST_TYPE \n"
                       + "       , CPI_CUST_BNFT_TYPE, ITEM_APPLY_METHD, CUST_PAY_TYPE, TRGT_AMT_TYPE, TRGT_AMT \n"
                       + "       , QTY_LMT_YN, LMT_QTY, QTY_LMT_STD, HP_CUST_JOIN_LMT_YN, HP_CUST_MAX_JOIN_CNT \n"
                       + "       , HP_CUST_JOIN_LMT_STD, BASIC_HP_ACCUM_YN, BASIC_HP_ACCUM_STD, ADD_HP_ACCUM_TELECOM_DIV, ADD_HP_ACCUM_TRGT_STD \n"
                       + "       , ADD_HP_ACCUM_RATE, ADD_HP_ACCUM_AF_DIV, ADD_HP_ACCUM_CD1, ADD_HP_ACCUM_CD2, OFFER_ID \n"
                       + "       , FREE_GIFT_PROVD_STD, FREE_GIFT_STD_AMT, FREE_GIFT_PROVD_QTY, FREE_GIFT_ADD_SALE_YN, CPI_INFO \n"
                       + "       , CPI_EXPLN, LTTR_MAX_GRADE, CUST_DSP_FILE_DIV, CUST_DSP_FILENM, STAMP_QTY \n"
                       + "       , SOUND_FILE_DIV, SOUND_FILE_NM, TTS_DSCRP, SOUND_FILE_PLAY_CHK_PNT, USE_YN \n"
                       + "       , FILLER1, FILLER2, FILLER3, FILLER4, FILLER5 \n"
                       + "       , REG_DT, JOIN_QUSTN_YN, PRGRS_STATUS, ITEM_DUP_PRMT_YN, LTTR_MULTI_PRT_YN \n"

                       //#15583 캠페인 기능 개선 요청 start
                       //기존
                       //+ "       , CPI_DC_PAY_WAY, CPI_BILL_NM, QTY_LIMIT_MSG, HP_CUST_LVL, DC_NOADM_PASS_YN ) \n"
                       //변경
                       + "       , CPI_DC_PAY_WAY, CPI_BILL_NM, QTY_LIMIT_MSG, HP_CUST_LVL, DC_NOADM_PASS_YN \n"
                       + "       , MOBILE_CPN_DUP_PRMT_YN, HPY_CPN_DUP_PRMT_YN ) \n"
                       //#15583 캠페인 기능 개선 요청 end

                       + "VALUES \n"
                       + "       ( '{0}', '{1}', '{2}', N'{3}', '{4}' \n"
                       + "       , '{5}', '{6}', '{7}', '{8}', '{9}' \n"
                       + "       , '{10}', '{11}', '{12}', {13}, '{14}' \n"
                       + "       , '{15}', '{16}', '{17}', '{18}', {19} \n"
                       + "       , '{20}', {21}, '{22}', '{23}', {24} \n"
                       + "       , '{25}', '{26}', '{27}', '{28}', '{29}' \n"
                       + "       , {30}, '{31}', '{32}', '{33}', '{34}' \n"
                       + "       , '{35}', {36}, {37}, '{38}', N'{39}' \n"
                       + "       , N'{40}', {41}, '{42}', '{43}', {44} \n"
                       + "       , '{45}', '{46}', N'{47}', '{48}', '{49}' \n"
                       + "       , '{50}', '{51}', '{52}', '{53}', '{54}' \n"
                       + "       , '{55}', '{56}', '{57}', '{58}', '{59}' \n"

                       //#15583 캠페인 기능 개선 요청 start
                       //기존
                       //+ "       , '{60}', N'{61}', N'{62}', {63}, '{64}' ) \n";
                       //변경
                       + "       , '{60}', N'{61}', N'{62}', {63}, '{64}' \n"
                       + "       , '{65}', '{66}' ) \n";
                       //#15583 캠페인 기능 개선 요청 end

                #endregion UPDATE / INSERT Query

                if (aRowDatas.Length > 0)
                {
                    // 현재 Row Counting
                    int nCnt = 0;

                    sqlDb = new SqlDB(m_cPosStatus.Base.LocalDbSource,
                                      m_cPosStatus.Base.LocalDbCatalog,
                                      m_cPosStatus.Base.LocalDbUserID,
                                      m_cPosStatus.Base.LocalDbPassword);

                    int iRet = UserCom.NG;

                    foreach (string sRowData in aRowDatas)
                    {
                        nCnt++;
                        aParams = sRowData.Split('|');

                        sSQL = string.Format( sQuery
                                            , aParams[0], aParams[1], aParams[2], aParams[3], aParams[4]
                                            , aParams[5], aParams[6], aParams[7], aParams[8], aParams[9]
                                            , aParams[10], aParams[11], aParams[12], aParams[13], aParams[14]
                                            , aParams[15], aParams[16], aParams[17], aParams[18], aParams[19]
                                            , aParams[20], aParams[21], aParams[22], aParams[23], aParams[24]
                                            , aParams[25], aParams[26], aParams[27], aParams[28], aParams[29]
                                            , aParams[30], aParams[31], aParams[32], aParams[33], aParams[34]
                                            , aParams[35], aParams[36], aParams[37], aParams[38], aParams[39]
                                            , aParams[40], aParams[41], aParams[42], aParams[43], aParams[44]
                                            , aParams[45], aParams[46], aParams[47], aParams[48], aParams[49]
                                            , aParams[50], aParams[51], aParams[52], aParams[53], aParams[54]
                                            , DateTime.Now.ToString("yyyyMMddHHmmsss"), aParams[57], aParams[58], aParams[59], aParams[60]

                                            //#15583 캠페인 기능 개선 요청 start
                                            //기존
                                            //, aParams[61], aParams[62], aParams[63], aParams[64], aParams[65]);
                                            //변경
                                            , aParams[61], aParams[62], aParams[63], aParams[64], aParams[65]
                                            , aParams[66], aParams[67]);
                                            //#15583 캠페인 기능 개선 요청 end

                        iRet = sqlDb.DBExecuteNonQuery(sSQL, System.Data.CommandType.Text, (System.Data.SqlClient.SqlParameter[])null);
                        if (iRet != UserCom.OK)
                        {
                            UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                                 UserCom.WARNING_LEVEL,
                                                 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 (함수명))
                                                 sSQL);

                            return UserCom.NG1;
                        }
                    }
                    return UserCom.OK;
                }
                else
                {
                    return UserCom.NG;
                }
            }
            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);

                return UserCom.NG1;
            }
        }
        #endregion 37 - 캠페인 마스터 Download / Insert

        #region 38 - 캠페인 시간 마스터 Download / Insert
        public int MST_CPI_HOUR(string sUpdateDT, string sStoreCd, string sSubBrandCd, string sSubStoreCd)
        {
            string sIrtData = string.Empty;
            string sRecvData = string.Empty;
            Hashtable htReqData = null;
            StringBuilder sbRecvData = null;
            int iReturn = BaseCom.NG;

            try
            {
                htReqData = new Hashtable();

                // 마스터 요청 Hashtable Data 생성
                htReqData = GetPosMasterReqData(MasterLists.MST_CPI_HOUR.DIV, sUpdateDT, sStoreCd, sSubStoreCd, "0");

                // 마스터 전문 송수신
                iReturn = this.MstIRTSendReceive(m_cPosStatus.Base.CommSvrIp,
                                                 (int)m_cPosStatus.Base.MstPort,
                                                 10000,
                                                 ItemColumn.MakeCommHeader(0, ItemConst.COMM_MSG_TYPE.MSTIRT, sSubBrandCd),
                                                 htReqData,
                                                 ref sbRecvData);

                if (iReturn == BaseCom.OK)
                {
                    // 행구분자(#~)로 구분한 Row Data를 string array에 저장
                    string[] aRowDatas = (sbRecvData.ToString()).Split(new string[] { "#~" }, StringSplitOptions.RemoveEmptyEntries);

                    //System.Console.WriteLine("{0} - start({1})", DateTime.Now.ToString("HH:mm:ss.fff"), aRowDatas.Length.ToString());

                    // DB Insert
                    iReturn = UpdateMST_CPI_HOUR(aRowDatas);

                    //System.Console.WriteLine("{0} - end)", DateTime.Now.ToString("HH:mm:ss.fff"));
                }

                return iReturn;
            }
            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);

                return UserCom.NG1;
            }
        }

        private int UpdateMST_CPI_HOUR(string[] aRowDatas)
        {
            string sQuery = string.Empty;
            string sSQL = string.Empty;
            //string sInsQuery = string.Empty;
            //string sUpdQuery = string.Empty;
            string[] aParams = null;

            try
            {
                #region UPDATE / INSERT Query
                sQuery = "UPDATE POSMST..MST_CPI_HOUR \n"
                       + "   SET START_HOUR = '{4}', FNSH_HOUR = '{5}', FILLER1 = '{6}', FILLER2 = '{7}', FILLER3 = '{8}' \n"
                       + "     , FILLER4 = '{9}', FILLER5 = '{10}', UPD_DT = '{11}', USE_YN = '{12}' \n"
                       + " WHERE CMP_CD = '{0}' \n"
                       + "   AND STOR_CD = '{1}' \n"
                       + "   AND CPI_CD = '{2}' \n"
                       + "   AND DOW_DIV = '{3}' \n"
                       + "IF @@ROWCOUNT = 0 \n"
                       + "INSERT INTO POSMST..MST_CPI_HOUR \n"
                       + "       ( CMP_CD, STOR_CD, CPI_CD, DOW_DIV, START_HOUR \n"
                       + "       , FNSH_HOUR, FILLER1, FILLER2, FILLER3, FILLER4 \n"
                       + "       , FILLER5, REG_DT, USE_YN ) \n"
                       + "VALUES \n"
                       + "       ( '{0}', '{1}', '{2}', '{3}', '{4}' \n"
                       + "       , '{5}', '{6}', '{7}', '{8}', '{9}' \n"
                       + "       , '{10}', '{11}', '{12}' ) \n";
                #endregion UPDATE / INSERT Query

                if (aRowDatas.Length > 0)
                {
                    // 현재 Row Counting
                    int nCnt = 0;

                    sqlDb = new SqlDB(m_cPosStatus.Base.LocalDbSource,
                                      m_cPosStatus.Base.LocalDbCatalog,
                                      m_cPosStatus.Base.LocalDbUserID,
                                      m_cPosStatus.Base.LocalDbPassword);

                    int iRet = UserCom.NG;

                    foreach (string sRowData in aRowDatas)
                    {
                        nCnt++;
                        aParams = sRowData.Split('|');

                        sSQL = string.Format( sQuery
                                            , aParams[0], aParams[1], aParams[2], aParams[3], aParams[4]
                                            , aParams[5], aParams[6], aParams[7], aParams[8], aParams[9]
                                            , aParams[10], DateTime.Now.ToString("yyyyMMddHHmmsss"), aParams[13]);

                        iRet = sqlDb.DBExecuteNonQuery(sSQL, System.Data.CommandType.Text, (System.Data.SqlClient.SqlParameter[])null);
                        if (iRet != UserCom.OK)
                        {
                            UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                                 UserCom.WARNING_LEVEL,
                                                 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 (함수명))
                                                 sSQL);

                            return UserCom.NG1;
                        }
                    }
                    return UserCom.OK;
                }
                else
                {
                    return UserCom.NG;
                }
            }
            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);

                return UserCom.NG1;
            }
        }
        #endregion 38 - 캠페인 시간 마스터 Download / Insert

        #region 39 - 캠페인 상품 마스터 Download / Insert
        public int MST_CPI_ITEM(string sUpdateDT, string sStoreCd, string sSubBrandCd, string sSubStoreCd)
        {
            string sIrtData = string.Empty;
            string sRecvData = string.Empty;
            Hashtable htReqData = null;
            StringBuilder sbRecvData = null;
            int iReturn = BaseCom.NG;

            try
            {
                htReqData = new Hashtable();

                // 마스터 요청 Hashtable Data 생성
                htReqData = GetPosMasterReqData(MasterLists.MST_CPI_ITEM.DIV, sUpdateDT, sStoreCd, sSubStoreCd, "0");

                // 마스터 전문 송수신
                iReturn = this.MstIRTSendReceive(m_cPosStatus.Base.CommSvrIp,
                                                 (int)m_cPosStatus.Base.MstPort,
                                                 10000,
                                                 ItemColumn.MakeCommHeader(0, ItemConst.COMM_MSG_TYPE.MSTIRT, sSubBrandCd),
                                                 htReqData,
                                                 ref sbRecvData);

                if (iReturn == BaseCom.OK)
                {
                    // 행구분자(#~)로 구분한 Row Data를 string array에 저장
                    string[] aRowDatas = (sbRecvData.ToString()).Split(new string[] { "#~" }, StringSplitOptions.RemoveEmptyEntries);

                    //System.Console.WriteLine("{0} - start({1})", DateTime.Now.ToString("HH:mm:ss.fff"), aRowDatas.Length.ToString());

                    // DB Insert
                    iReturn = UpdateMST_CPI_ITEM(aRowDatas);

                    //System.Console.WriteLine("{0} - end)", DateTime.Now.ToString("HH:mm:ss.fff"));
                }

                return iReturn;
            }
            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);

                return UserCom.NG1;
            }
        }

        private int UpdateMST_CPI_ITEM(string[] aRowDatas)
        {
            string sQuery = string.Empty;
            string sSQL = string.Empty;
            //string sInsQuery = string.Empty;
            //string sUpdQuery = string.Empty;
            string[] aParams = null;

            try
            {
                #region UPDATE / INSERT Query
                sQuery = "UPDATE POSMST..MST_CPI_ITEM \n"
                       + "   SET CPI_DC_TYPE = '{7}', DC_RATE_AMT = {8}, FILLER1 = '{9}', FILLER2 = '{10}', FILLER3 = '{11}' \n"
                       + "     , FILLER4 = '{12}', FILLER5 = '{13}', UPD_DT = '{14}', USE_YN = '{15}' \n"
                       + " WHERE CMP_CD = '{0}' \n"
                       + "   AND STOR_CD = '{1}' \n"
                       + "   AND CPI_CD = '{2}' \n"
                       + "   AND SUB_STOR_CD = '{3}' \n"
                       + "   AND CPI_ITEM_GRP_CD = '{4}' \n"
                       + "   AND ITEM_LVL = '{5}' \n"
                       + "   AND ITEM_CD = '{6}' \n"
                       + "IF @@ROWCOUNT = 0 \n"
                       + "INSERT INTO POSMST..MST_CPI_ITEM \n"
                       + "       ( CMP_CD, STOR_CD, CPI_CD, SUB_STOR_CD, CPI_ITEM_GRP_CD \n"
                       + "       , ITEM_LVL, ITEM_CD, CPI_DC_TYPE, DC_RATE_AMT, FILLER1 \n"
                       + "       , FILLER2, FILLER3, FILLER4, FILLER5, REG_DT \n"
                       + "       , USE_YN ) \n"
                       + "VALUES \n"
                       + "       ( '{0}', '{1}', '{2}', '{3}', '{4}' \n"
                       + "       , '{5}', '{6}', '{7}', {8}, '{9}' \n"
                       + "       , '{10}', '{11}', '{12}', '{13}', '{14}' \n"
                       + "       , '{15}' ) \n";
                #endregion UPDATE / INSERT Query

                if (aRowDatas.Length > 0)
                {
                    // 현재 Row Counting
                    int nCnt = 0;

                    sqlDb = new SqlDB(m_cPosStatus.Base.LocalDbSource,
                                      m_cPosStatus.Base.LocalDbCatalog,
                                      m_cPosStatus.Base.LocalDbUserID,
                                      m_cPosStatus.Base.LocalDbPassword);

                    int iRet = UserCom.NG;

                    foreach (string sRowData in aRowDatas)
                    {
                        nCnt++;
                        aParams = sRowData.Split('|');

                        sSQL = string.Format( sQuery
                                            , aParams[0], m_cPosStatus.Base.StoreNo, aParams[2], aParams[3], aParams[4]
                                            , aParams[5], aParams[6], aParams[7], aParams[8], aParams[9]
                                            , aParams[10], aParams[11], aParams[12], aParams[13], DateTime.Now.ToString("yyyyMMddHHmmsss")
                                            , aParams[16]);

                        iRet = sqlDb.DBExecuteNonQuery(sSQL, System.Data.CommandType.Text, (System.Data.SqlClient.SqlParameter[])null);
                        if (iRet != UserCom.OK)
                        {
                            UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                                 UserCom.WARNING_LEVEL,
                                                 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 (함수명))
                                                 sSQL);

                            return UserCom.NG1;
                        }
                    }
                    return UserCom.OK;
                }
                else
                {
                    return UserCom.NG;
                }
            }
            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);

                return UserCom.NG1;
            }
        }
        #endregion 39 - 캠페인 상품 마스터 Download / Insert

        #region 40 - 캠페인 출력메시지 마스터 Download / Insert
        public int MST_CPI_PRT_MSG(string sUpdateDT, string sStoreCd, string sSubBrandCd, string sSubStoreCd)
        {
            string sIrtData = string.Empty;
            string sRecvData = string.Empty;
            Hashtable htReqData = null;
            StringBuilder sbRecvData = null;
            int iReturn = BaseCom.NG;

            try
            {
                htReqData = new Hashtable();

                // 마스터 요청 Hashtable Data 생성
                htReqData = GetPosMasterReqData(MasterLists.MST_CPI_PRT_MSG.DIV, sUpdateDT, sStoreCd, sSubStoreCd, "0");

                // 마스터 전문 송수신
                iReturn = this.MstIRTSendReceive(m_cPosStatus.Base.CommSvrIp,
                                                 (int)m_cPosStatus.Base.MstPort,
                                                 10000,
                                                 ItemColumn.MakeCommHeader(0, ItemConst.COMM_MSG_TYPE.MSTIRT, sSubBrandCd),
                                                 htReqData,
                                                 ref sbRecvData);

                if (iReturn == BaseCom.OK)
                {
                    // 행구분자(#~)로 구분한 Row Data를 string array에 저장
                    string[] aRowDatas = (sbRecvData.ToString()).Split(new string[] { "#~" }, StringSplitOptions.RemoveEmptyEntries);

                    //System.Console.WriteLine("{0} - start({1})", DateTime.Now.ToString("HH:mm:ss.fff"), aRowDatas.Length.ToString());

                    // DB Insert
                    iReturn = UpdateMST_CPI_PRT_MSG(aRowDatas);

                    //System.Console.WriteLine("{0} - end)", DateTime.Now.ToString("HH:mm:ss.fff"));
                }

                return iReturn;
            }
            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);

                return UserCom.NG1;
            }
        }

        private int UpdateMST_CPI_PRT_MSG(string[] aRowDatas)
        {
            string sQuery = string.Empty;
            string sSQL = string.Empty;
            //string sInsQuery = string.Empty;
            //string sUpdQuery = string.Empty;
            string[] aParams = null;

            try
            {
                #region UPDATE / INSERT Query
                sQuery = "UPDATE POSMST..MST_CPI_PRT_MSG \n"
                       + "   SET PRT_EXPAND_TYPE = '{5}', BOLD_YN = '{6}', ALIGN_TYPE = '{7}', MSG_VAL = N'{8}', FILLER1 = '{9}' \n"
                       + "     , FILLER2 = '{10}', FILLER3 = '{11}', FILLER4 = '{12}', FILLER5 = '{13}', UPD_DT = '{14}', PRT_YN = '{15}' \n"
                       + " WHERE CMP_CD = '{0}' \n"
                       + "   AND STOR_CD = '{1}' \n"
                       + "   AND CPI_CD = '{2}' \n"
                       + "   AND CPI_BILL_PRT_AREA_TYPE = '{3}' \n"
                       + "   AND PRT_SEQ = {4} \n"
                       + "IF @@ROWCOUNT = 0 \n"
                       + "INSERT INTO POSMST..MST_CPI_PRT_MSG \n"
                       + "       ( CMP_CD, STOR_CD, CPI_CD, CPI_BILL_PRT_AREA_TYPE, PRT_SEQ \n"
                       + "       , PRT_EXPAND_TYPE, BOLD_YN, ALIGN_TYPE, MSG_VAL, FILLER1 \n"
                       + "       , FILLER2, FILLER3, FILLER4, FILLER5, REG_DT \n"
                       + "       , PRT_YN ) \n"
                       + "VALUES \n"
                       + "       ( '{0}', '{1}', '{2}', '{3}', {4} \n"
                       + "       , '{5}', '{6}', '{7}', N'{8}', '{9}' \n"
                       + "       , '{10}', '{11}', '{12}', '{13}', '{14}' \n"
                       + "       , '{15}' ) \n";
                #endregion UPDATE / INSERT Query

                if (aRowDatas.Length > 0)
                {
                    // 현재 Row Counting
                    int nCnt = 0;

                    sqlDb = new SqlDB(m_cPosStatus.Base.LocalDbSource,
                                      m_cPosStatus.Base.LocalDbCatalog,
                                      m_cPosStatus.Base.LocalDbUserID,
                                      m_cPosStatus.Base.LocalDbPassword);

                    int iRet = UserCom.NG;

                    foreach (string sRowData in aRowDatas)
                    {
                        nCnt++;
                        aParams = sRowData.Split('|');

                        sSQL = string.Format( sQuery
                                            , aParams[0], aParams[1], aParams[2], aParams[3], aParams[4]
                                            , aParams[5], aParams[6], aParams[7], aParams[8], aParams[9]
                                            , aParams[10], aParams[11], aParams[12], aParams[13], DateTime.Now.ToString("yyyyMMddHHmmsss")
                                            , aParams[16]);
                                                                    
                        iRet = sqlDb.DBExecuteNonQuery(sSQL, System.Data.CommandType.Text, (System.Data.SqlClient.SqlParameter[])null);
                        if (iRet != UserCom.OK)
                        {
                            UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                                 UserCom.WARNING_LEVEL,
                                                 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 (함수명))
                                                 sSQL);

                            return UserCom.NG1;
                        }
                    }
                    return UserCom.OK;
                }
                else
                {
                    return UserCom.NG;
                }
            }
            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);

                return UserCom.NG1;
            }
        }
        #endregion 40 - 캠페인 출력메시지 마스터 Download / Insert

        #region 41 - 캠페인 카드 마스터 Downlaod / Insert
        public int MST_CPI_CARD(string sUpdateDT, string sStoreCd, string sSubBrandCd, string sSubStoreCd)
        {
            string sIrtData = string.Empty;
            string sRecvData = string.Empty;
            Hashtable htReqData = null;
            StringBuilder sbRecvData = null;
            int iReturn = BaseCom.NG;

            try
            {
                htReqData = new Hashtable();

                // 마스터 요청 Hashtable Data 생성
                htReqData = GetPosMasterReqData(MasterLists.MST_CPI_CARD.DIV, sUpdateDT, sStoreCd, sSubStoreCd, "0");

                // 마스터 전문 송수신
                iReturn = this.MstIRTSendReceive(m_cPosStatus.Base.CommSvrIp,
                                                 (int)m_cPosStatus.Base.MstPort,
                                                 10000,
                                                 ItemColumn.MakeCommHeader(0, ItemConst.COMM_MSG_TYPE.MSTIRT, sSubBrandCd),
                                                 htReqData,
                                                 ref sbRecvData);

                if (iReturn == BaseCom.OK)
                {
                    // 행구분자(#~)로 구분한 Row Data를 string array에 저장
                    string[] aRowDatas = (sbRecvData.ToString()).Split(new string[] { "#~" }, StringSplitOptions.RemoveEmptyEntries);

                    //System.Console.WriteLine("{0} - start({1})", DateTime.Now.ToString("HH:mm:ss.fff"), aRowDatas.Length.ToString());

                    // DB Insert
                    iReturn = UpdateMST_CPI_CARD(aRowDatas);

                    //System.Console.WriteLine("{0} - end)", DateTime.Now.ToString("HH:mm:ss.fff"));
                }

                return iReturn;
            }
            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);

                return UserCom.NG1;
            }
        }

        private int UpdateMST_CPI_CARD(string[] aRowDatas)
        {
            string sQuery = string.Empty;
            string sSQL = string.Empty;
            //string sInsQuery = string.Empty;
            //string sUpdQuery = string.Empty;
            string[] aParams = null;

            try
            {
                #region UPDATE / INSERT Query
                sQuery = "UPDATE POSMST..MST_CPI_CARD \n"
                       + "   SET CHECK_VAL = '{4}', LOC = {5}, FILLER1 = '{6}', FILLER2 = '{7}', FILLER3 = '{8}' \n"
                       + "     , FILLER4 = '{9}', FILLER5 = '{10}', UPD_DT = '{11}', USE_YN = '{12}' \n"
                       + " WHERE CMP_CD = '{0}' \n"
                       + "   AND STOR_CD = '{1}' \n"
                       + "   AND CPI_CD = '{2}' \n"
                       + "   AND CARD_PRFX_CD = '{3}' \n"
                       + "IF @@ROWCOUNT = 0 \n"
                       + "INSERT INTO POSMST..MST_CPI_CARD \n"
                       + "       ( CMP_CD, STOR_CD, CPI_CD, CARD_PRFX_CD, CHECK_VAL \n"
                       + "       , LOC, FILLER1, FILLER2, FILLER3, FILLER4 \n"
                       + "       , FILLER5, REG_DT, USE_YN ) \n"
                       + "VALUES \n"
                       + "       ( '{0}', '{1}', '{2}', '{3}', '{4}' \n"
                       + "       , {5}, '{6}', '{7}' ,'{8}', '{9}' \n"
                       + "       , '{10}', '{11}', '{12}' ) \n";
                #endregion UPDATE / INSERT Query

                if (aRowDatas.Length > 0)
                {
                    // 현재 Row Counting
                    int nCnt = 0;

                    sqlDb = new SqlDB(m_cPosStatus.Base.LocalDbSource,
                                      m_cPosStatus.Base.LocalDbCatalog,
                                      m_cPosStatus.Base.LocalDbUserID,
                                      m_cPosStatus.Base.LocalDbPassword);

                    int iRet = UserCom.NG;

                    foreach (string sRowData in aRowDatas)
                    {
                        nCnt++;
                        aParams = sRowData.Split('|');

                        sSQL = string.Format( sQuery
                                            , aParams[0], aParams[1], aParams[2], aParams[3], aParams[4]
                                            , aParams[5], aParams[6], aParams[7], aParams[8], aParams[9]
                                            , aParams[10], DateTime.Now.ToString("yyyyMMddHHmmsss"), aParams[13]);
                                                
                        iRet = sqlDb.DBExecuteNonQuery(sSQL, System.Data.CommandType.Text, (System.Data.SqlClient.SqlParameter[])null);
                        if (iRet != UserCom.OK)
                        {
                            UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                                 UserCom.WARNING_LEVEL,
                                                 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 (함수명))
                                                 sSQL);

                            return UserCom.NG1;
                        }
                    }
                    return UserCom.OK;
                }
                else
                {
                    return UserCom.NG;
                }
            }
            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);

                return UserCom.NG1;
            }
        }
        #endregion 41 - 캠페인 카드 마스터 Downlaod / Insert

        #region 42 - 캠페인 복권 출력 메시지 관리 마스터 Download / Insert
        public int MST_CPI_LTTR_PRT(string sUpdateDT, string sStoreCd, string sSubBrandCd, string sSubStoreCd)
        {
            string sIrtData = string.Empty;
            string sRecvData = string.Empty;
            Hashtable htReqData = null;
            StringBuilder sbRecvData = null;
            int iReturn = BaseCom.NG;

            try
            {
                htReqData = new Hashtable();

                // 마스터 요청 Hashtable Data 생성
                htReqData = GetPosMasterReqData(MasterLists.MST_CPI_LTTR_PRT.DIV, sUpdateDT, sStoreCd, sSubStoreCd, "0");

                // 마스터 전문 송수신
                iReturn = this.MstIRTSendReceive(m_cPosStatus.Base.CommSvrIp,
                                                 (int)m_cPosStatus.Base.MstPort,
                                                 10000,
                                                 ItemColumn.MakeCommHeader(0, ItemConst.COMM_MSG_TYPE.MSTIRT, sSubBrandCd),
                                                 htReqData,
                                                 ref sbRecvData);

                if (iReturn == BaseCom.OK)
                {
                    // 행구분자(#~)로 구분한 Row Data를 string array에 저장
                    string[] aRowDatas = (sbRecvData.ToString()).Split(new string[] { "#~" }, StringSplitOptions.RemoveEmptyEntries);

                    //System.Console.WriteLine("{0} - start({1})", DateTime.Now.ToString("HH:mm:ss.fff"), aRowDatas.Length.ToString());

                    // DB Insert
                    iReturn = UpdateMST_CPI_LTTR_PRT(aRowDatas);

                    //System.Console.WriteLine("{0} - end)", DateTime.Now.ToString("HH:mm:ss.fff"));
                }

                return iReturn;
            }
            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);

                return UserCom.NG1;
            }
        }

        private int UpdateMST_CPI_LTTR_PRT(string[] aRowDatas)
        {
            string sQuery = string.Empty;
            string sSQL = string.Empty;
            //string sInsQuery = string.Empty;
            //string sUpdQuery = string.Empty;
            string[] aParams = null;

            try
            {
                #region UPDATE / INSERT Query
                sQuery = "UPDATE POSMST..MST_CPI_LTTR_PRT \n"
                       + "   SET MSG_VAL = N'{5}', PRT_EXPAND_TYPE = '{6}', BOLD_YN = '{7}', ALIGN_TYPE = '{8}', FILLER1 = '{9}' \n"
                       + "     , FILLER2 = '{10}', FILLER3 = '{11}', FILLER4 = '{12}', FILLER5 = '{13}', PRT_YN = '{14}' \n"
                       + "     , UPD_DT = '{15}' \n"
                       + " WHERE CMP_CD = '{0}' \n"
                       + "   AND STOR_CD = '{1}' \n"
                       + "   AND CPI_CD = '{2}' \n"
                       + "   AND GRADE = {3} \n"
                       + "   AND PRT_SEQ = {4} \n"
                       + "IF @@ROWCOUNT = 0 \n"
                       + "INSERT INTO POSMST..MST_CPI_LTTR_PRT \n"
                       + "       ( CMP_CD, STOR_CD, CPI_CD, GRADE, PRT_SEQ \n"
                       + "       , MSG_VAL, PRT_EXPAND_TYPE, BOLD_YN, ALIGN_TYPE, FILLER1 \n"
                       + "       , FILLER2, FILLER3, FILLER4, FILLER5, PRT_YN \n"
                       + "       , REG_DT ) \n"
                       + "VALUES \n"
                       + "       ( '{0}', '{1}', '{2}', {3}, {4} \n"
                       + "       , N'{5}', '{6}', '{7}', '{8}', '{9}' \n"
                       + "       , '{10}', '{11}', '{12}', '{13}', '{14}' \n"
                       + "       , '{15}' ) \n";
                #endregion UPDATE / INSERT Query

                if (aRowDatas.Length > 0)
                {
                    // 현재 Row Counting
                    int nCnt = 0;

                    sqlDb = new SqlDB(m_cPosStatus.Base.LocalDbSource,
                                      m_cPosStatus.Base.LocalDbCatalog,
                                      m_cPosStatus.Base.LocalDbUserID,
                                      m_cPosStatus.Base.LocalDbPassword);

                    int iRet = UserCom.NG;

                    foreach (string sRowData in aRowDatas)
                    {
                        nCnt++;
                        aParams = sRowData.Split('|');

                        sSQL = string.Format( sQuery
                                            , aParams[0], aParams[1], aParams[2], aParams[3], aParams[4]
                                            , aParams[5], aParams[6], aParams[7], aParams[8], aParams[9]
                                            , aParams[10], aParams[11], aParams[12], aParams[13], aParams[14]
                                            , DateTime.Now.ToString("yyyyMMddHHmmsss"));
                                                
                        iRet = sqlDb.DBExecuteNonQuery(sSQL, System.Data.CommandType.Text, (System.Data.SqlClient.SqlParameter[])null);
                        if (iRet != UserCom.OK)
                        {
                            UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                                 UserCom.WARNING_LEVEL,
                                                 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 (함수명))
                                                 sSQL);

                            return UserCom.NG1;
                        }
                    }
                    return UserCom.OK;
                }
                else
                {
                    return UserCom.NG;
                }
            }
            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);

                return UserCom.NG1;
            }
        }
        #endregion 42 - 캠페인 복권 출력 메시지 관리 마스터 Download / Insert

        #endregion Master Download 처리

        #region PosSaleInfo.INI 저장 처리
        private string UpdatePosSaleInfo()
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                CmMessage cmPosSaleInfo = CmMessage.MakeMessageFromFile(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosSaleInfo);

                cmPosSaleInfo.GetMessage("CHECKOVER").MakeMessageOverWrite("MstBatchDownDate", m_cPosStatus.Base.MstBatchDownDate);
                
                // 파일저장
                cmPosSaleInfo.MakeFileFromMessage(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosSaleInfo);

                sRet = UserCom.RST_OK;
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_DEBUG,
                                    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);
            }
            return sRet;
        }
        #endregion

        #region 프로그램 백그라운드 다운로드 대상 조회 요청
        /// <summary>
        /// 프로그램 백그라운드 다운로드 대상 조회 요청
        /// </summary>
        /// <returns></returns>
        private string LF_ProgramDownLoad_Search()
        {
            string sGroup = PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_20;
            string sKind = PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_20_DIV.ALL_PGM;
            string sDownDiv = "A";

            Hashtable htRecvData = new Hashtable();     // 프로그램 업데이트 FTP 서버 정보
            string[] sRecvData = {""};                  // 프로그램 업데이트 목록

            string sRet = UserCom.RST_ERR;
            DataTable dtData = new DataTable();
            string sQuery = "";
            string sLocalPath = BaseCom.NxDownPath;

            string[] aRecvData = null;

            string sFTP_IP = "";
            int iFTP_Port = 0;
            string sFTP_ID = "";
            string sFTP_Pwd = "";

            string sApplyDate = "";
            string sApplyTime = "";
            string sFilePath = "";
            string sFileNm = "";
            string sFileVer = "";
            string sFileSeq = "";
            string sDeployDate = "";
            string sDeployTime = "";
            string sDeployDT = "";
            string sUseYn = "";
            string sData = "";

            int iRet = -1; 

            try
            {
                // DB Connect
                //m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource, m_cPosStatus.Base.LocalDbCatalog, m_cPosStatus.Base.LocalDbUserID, m_cPosStatus.Base.LocalDbPassword);

                sqlDb = new SqlDB(m_cPosStatus.Base.LocalDbSource,
                                      m_cPosStatus.Base.LocalDbCatalog,
                                      m_cPosStatus.Base.LocalDbUserID,
                                      m_cPosStatus.Base.LocalDbPassword);

                // 프로그램 배포 조회
                sQuery = "";
                sQuery += "SELECT * \n";
                sQuery += " FROM POSMST..MST_EMG_NOTE  \n";
                sQuery += " WHERE  \n";
                sQuery += " 	CMP_CD	= '" + m_cPosStatus.Base.CmpCd + "' \n";
                sQuery += " AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "' \n";
                sQuery += " AND POS_NO  = '" + m_cPosStatus.Base.PosNo + "' \n";
                sQuery += " AND MSG_DIV	= '" + ItemConst.NOTE_MSG_DIV.EMG + "' \n";
                sQuery += " AND MSG_TYPE = '1' \n";                                                 // 구분 (0:일반, 1:재시작)
                sQuery += " AND DOWN_YN <> '1' \n";                                                 // 다운로드 구분 (1:다운로드 완료, 0:미처리)
                sQuery += " AND START_DT >= '" + DateTime.Now.ToString("yyyyMMdd") + "' \n";        // 영업일로 하게되면 개점 이전에 적용되지 않아 서버에서 받은 시스템 일자로 조회
                sQuery += " AND USE_YN  = '" + PosConst.MST_USE_YN.YES + "' \n";
                sQuery += " ORDER BY REG_DT \n";
                sQuery = sQuery.Replace("\t", " ");

                //iRet = m_cSqlDbService.DBSelect(sQuery, out dtData);

                iRet = sqlDb.DBDataTableSelect(sQuery, CommandType.Text, (System.Data.SqlClient.SqlParameter[])null, out dtData);

                if (dtData != null && dtData.Rows.Count > 0)
                {
                    foreach (DataRow dr in dtData.Rows)
                    {
                        // 서버 조회
                        sRet = m_cSvr2Tran.PGMUpdate(sGroup + sKind, sDownDiv, ref sRecvData, ref htRecvData);
                        if (sRet == UserCom.RST_OK)
                        {
                            sData = htRecvData[Column.IQ_PGMUPDATE_RSP.DATA.VALUE].ToString();
                            if (CmUtil.IsNull(sData) == true || sData.Trim().Length <= 0)
                            {
                                // 상태값 변경
                                // 프로그램이 아니고 일반 재시작 필요시
                                EmgNoteFlgUpdate(CmUtil.GetDataRowStr(dr, "START_DT"), CmUtil.GetDataRowStr(dr, "MSG_CODE"), CmUtil.GetDataRowStr(dr, "MSG_DIV"), "1");
                            }

                            for (int iLoop = 0; iLoop < sRecvData.Length; iLoop++)
                            {
                                sData = sRecvData[iLoop].ToString();
                                if (CmUtil.IsNull(sData) == true || sData.Trim().Length <= 0) continue;

                                sFTP_IP = htRecvData[Column.IQ_PGMUPDATE_RSP.DATA.FTP_IP].ToString();
                                iFTP_Port = CmUtil.IntParse(htRecvData[Column.IQ_PGMUPDATE_RSP.DATA.FTP_PORT].ToString());
                                sFTP_ID = htRecvData[Column.IQ_PGMUPDATE_RSP.DATA.FTP_ID].ToString();
                                sFTP_Pwd = htRecvData[Column.IQ_PGMUPDATE_RSP.DATA.FTP_PWD].ToString();

                                aRecvData = sRecvData[iLoop].Split(new string[] { "|" }, StringSplitOptions.None);
                                sGroup = aRecvData[0].ToString();               // 그룹
                                sKind = aRecvData[1].ToString();                // 배포구분 : 01:프로그램, 02:프로그램(기타), 03:객면 컨텐츠, 04:상품이미지, 20:영수증 로고 이미지, 21:서명패드 펌웨어, 22:서명패드 동영상, 23:서명패드 이미지
                                sApplyDate = aRecvData[3].ToString();           // 적용일자
                                sApplyTime = aRecvData[10].ToString();          // 적용시간
                                sFilePath = aRecvData[4].ToString();            // 파일위치
                                if (CmUtil.RightH(sFilePath, 1) != "/") sFilePath += "/";
                                sFileNm = aRecvData[5].ToString();              // 파일명
                                sFileVer = aRecvData[6].ToString();             // 파일버전
                                sFileSeq = aRecvData[7].ToString();             // 파일Seq
                                sDeployDate = aRecvData[8].ToString();          // 다운일자
                                sDeployTime = aRecvData[9].ToString();          // 다운시간
                                sDeployDT = aRecvData[11].ToString();           // 배포일자
                                sUseYn = "1";                                   // 사용유무

                                // 다운로드 이력 저장
                                sRet = m_cSvr2Tran.PGMUpdate_History_Isert(sGroup + sKind, sFileSeq, sFileVer, sFileNm, sApplyDate, sApplyTime, "", sDeployDate, sDeployTime, sFTP_IP, iFTP_Port.ToString(), sFTP_ID, sFTP_Pwd, sFilePath, "0", sDeployDT, sUseYn);
                            }

                            if (sRet != UserCom.RST_ERR)
                            {
                                // 다운로드 목록 체크 
                                sRet = LF_ProgramDownLoad();

                                if (sRet != UserCom.RST_ERR)
                                {
                                    // 상태값 변경
                                    EmgNoteFlgUpdate(CmUtil.GetDataRowStr(dr, "START_DT"), CmUtil.GetDataRowStr(dr, "MSG_CODE"), CmUtil.GetDataRowStr(dr, "MSG_DIV"), "1");
                                }
                            }                            
                        }
                        else
                        {
                            // 프로그램이 아니고 일반 재시작 필요시
                            EmgNoteFlgUpdate(CmUtil.GetDataRowStr(dr, "START_DT"), CmUtil.GetDataRowStr(dr, "MSG_CODE"), CmUtil.GetDataRowStr(dr, "MSG_DIV"), "1");
                        }
                    }
                }
                sRet = UserCom.RST_OK;
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_DEBUG,
                                    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);
            }
            return sRet;
        }
        #endregion

        #region 프로그램 백그라운드 다운로드
        /// <summary>
        /// 프로그램 백그라운드 다운로드 대상 조회 요청
        /// </summary>
        /// <returns></returns>
        private string LF_ProgramDownLoad()
        { 
            string sKind = "";
            string sDownDiv = "A";

            string sRet = UserCom.RST_ERR;
            DataTable dtData = new DataTable();
            string sQuery = "";
            string sLocalPath = BaseCom.NxDownPath;
            string sApplyType = "";

            string sFTP_IP = "";
            int iFTP_Port = 0;
            string sFTP_ID = "";
            string sFTP_Pwd = "";

            string sApplyDate = "";
            string sApplyTime = "";
            string sFilePath = "";
            string sFileNm = "";
            string sFileVer = "";
            string sFileSeq = "";
            string sDeployDate = "";
            string sDeployTime = "";
            string sDeployDT = "";
            string sUseYn = "";
            int iRet = -1;

            string sMsg = "";

            try
            {
                // DB Connect
                //m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource, m_cPosStatus.Base.LocalDbCatalog, m_cPosStatus.Base.LocalDbUserID, m_cPosStatus.Base.LocalDbPassword);

                sqlDb = new SqlDB(m_cPosStatus.Base.LocalDbSource,
                                      m_cPosStatus.Base.LocalDbCatalog,
                                      m_cPosStatus.Base.LocalDbUserID,
                                      m_cPosStatus.Base.LocalDbPassword);

                // 프로그램 다운로드 이력조회 후 다운로드 시작
                sQuery = "";
                sQuery += "SELECT * \n";
                sQuery += " FROM POSMST..MST_PGM_VER_NEW \n";
                sQuery += " WHERE \n";
                sQuery += " 	CMP_CD	    = '" + m_cPosStatus.Base.CmpCd + "'\n";
                sQuery += " AND STOR_CD     = '" + m_cPosStatus.Base.StoreNo + "'\n";
                sQuery += " AND POS_NO      = '" + m_cPosStatus.Base.PosNo + "'\n";
                sQuery += " AND APP_TYPE    NOT IN('2') \n";                                                // 적용구분(1:다운완료, 2:적용완료, F:다운실패, E:적용실패)
                sQuery += " AND DOWN_DIV    <> '1' \n";
                sQuery += " AND ISNULL(DEPLOY_DATE, '') + ISNULL(DEPLOY_TIME, '') <= '" + DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.ToString("HHmm") + "'\n";
                sQuery += " AND ISNULL(USE_YN, '1') = '" + PosConst.MST_USE_YN.YES + "'  \n";
                sQuery += " ORDER BY 1, 2, 3, 4, 5, 6 \n";
                sQuery = sQuery.Replace("\t", " ");

                //iRet = m_cSqlDbService.DBSelect(sQuery, out dtData);
                iRet = sqlDb.DBDataTableSelect(sQuery, CommandType.Text, (System.Data.SqlClient.SqlParameter[])null, out dtData);

                if (dtData != null && dtData.Rows.Count > 0)
                {
                    foreach (DataRow dr in dtData.Rows)
                    { 
                        sKind = CmUtil.GetDataRowStr(dr, PosMst.MST_PGM_VER.DATA.KIND);

                        sFTP_IP = CmUtil.GetDataRowStr(dr, "FTP_IP");
                        iFTP_Port = CmUtil.IntParse(CmUtil.GetDataRowStr(dr, "FTP_PORT"));
                        sFTP_ID = CmUtil.GetDataRowStr(dr, "FTP_ID");
                        sFTP_Pwd = CmUtil.GetDataRowStr(dr, "FTP_PWD");

                        sApplyDate = CmUtil.GetDataRowStr(dr, "APPLY_DATE");            // 적용일자
                        sApplyTime = CmUtil.GetDataRowStr(dr, "APPLY_TIME");            // 적용시간
                        sFilePath = CmUtil.GetDataRowStr(dr, "FTP_FILEPATH");           // 파일위치
                        if (CmUtil.RightH(sFilePath, 1) != "/") sFilePath += "/";
                        sFileNm = CmUtil.GetDataRowStr(dr, "FILE_NM");                  // 파일명
                        sFileVer = CmUtil.GetDataRowStr(dr, "FILE_VER");                // 파일버전
                        sFileSeq = CmUtil.GetDataRowStr(dr, "FILE_SEQ");                // 파일Seq
                        sDeployDate = CmUtil.GetDataRowStr(dr, "DEPLOY_DATE");          // 다운로드일자
                        sDeployTime = CmUtil.GetDataRowStr(dr, "DEPLOY_TIME");          // 다운로드시간
                        sDeployDT = CmUtil.GetDataRowStr(dr, "DEPLOY_DT");              // 배포일자
                        sUseYn = "1";                                                   // 사용유무

                        // 이전에 받은파일이 있는지 체크
                        if (CmUtil.Exists(BaseCom.NxBackPath + PosConst.BACKUP_PATH.PGM + sFileNm) != true)
                        {
                            if (m_cNetworkFTP.Connect(sFTP_IP, sFTP_ID, sFTP_Pwd, 10, iFTP_Port) == 0)
                            {
                                // FTP 다운로드
                                CmUtil.FileDelete(sLocalPath + sFileNm);
                                iRet = m_cNetworkFTP.Download(sFilePath, sLocalPath, sFileNm, ref sMsg, m_cPosStatus.Base.FtpConnType);

                                if (iRet != 0)
                                {
                                    sApplyType = ItemConst.PGM_DOWN_STATE.DownLoad_Fail;

                                    UserLog.WriteLogFile(UserCom.LOG_DEBUG,
                                                        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 (함수명))
                                                        MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0282) + "\n" + sMsg);
                                }
                                else
                                {
                                    // 다운로드만 적용
                                    sApplyType = ItemConst.PGM_DOWN_STATE.DownLoad_OK;
                                }
                            }
                            else
                            {
                                // 다운로드 실패
                                sApplyType = ItemConst.PGM_DOWN_STATE.DownLoad_Fail;
                            }
                        }
                        else
                        {
                            // 다운로드만 적용
                            sApplyType = ItemConst.PGM_DOWN_STATE.DownLoad_OK;

                            // 백업된 파일을 다운로드 폴더에 복사
                            CmUtil.FileCopy(sFileNm, BaseCom.NxBackPath + PosConst.BACKUP_PATH.PGM, sLocalPath, "");
                        }

                        // 다운로드 이력 저장
                        sRet = m_cSvr2Tran.PGMUpdate_History_Isert(sKind, sFileSeq, sFileVer, sFileNm, sApplyDate, sApplyTime, sApplyType, sDeployDate, sDeployTime, sFTP_IP, iFTP_Port.ToString(), sFTP_ID, sFTP_Pwd, sFilePath, "1", sDeployDT, sUseYn);

                        // 수신 상태 전송
                        sRet = m_cSvr2Tran.PGMUpdate_Complete(sKind, sApplyType, sFileNm, sFileSeq, sFileVer, sDownDiv, sDeployDate, sDeployDT);
                    }
                }                
            }
            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);
            }
            return sRet;
        }
        #endregion

        #region 다운로드 프로그램 적용
        /// <summary>
        /// 다운로드 프로그램 적용
        /// </summary>
        /// <returns></returns>
        private string PGMUpdate_Apply(string sDownDiv)
        {
            string sRet = UserCom.RST_ERR;
            string sApplyType = "";
            int iRet = -1;

            string sUnzip_RCPTLOGO_Path = BaseCom.NxImgPath + @"RCPTLOGO\";
            string sUnzip_SIGNPAD_Path = BaseCom.NxDonglePath;
            string sUnzip_PGM_Path = BaseCom.NxDownPath + @"PGM\";
            string sUnzip_IMG_Path = BaseCom.NxDownPath;

            string sDelete_CAMPAIGN_Path = BaseCom.NxDownPath + @"CDP\CAMPAIGN\";
            string sDelete_CDP_COM_Path = BaseCom.NxDownPath + @"CDP\CDP_COM\";
            string sDelete_CUSTOMER_Path = BaseCom.NxDownPath + @"CDP\CUSTOMER\";
            string sDelete_ITEM_Path = BaseCom.NxDownPath + @"CDP\ITEM\";
            string sDelete_TEST_MODE_Path = BaseCom.NxDownPath + @"CDP\TEST_MODE\";
            string sDelete_ETC_Path = BaseCom.NxDownPath + @"CDP\ETC\";
            string sUnzipPath = "";
            DataTable dtData = new DataTable();

            string sGroup = "";
            string sKind = ""; 

            string sFTP_IP = "";
            int iFTP_Port = 0;
            string sFTP_ID = "";
            string sFTP_Pwd = "";

            string sApplyDate = "";
            string sApplyTime = "";
            string sFilePath = "";
            string sFileNm = "";
            string sFileVer = "";
            string sFileSeq = "";
            string sDeployDate = "";
            string sDeployTime = "";
            string sDeployDT = "";
            string sUseYn = "";

            bool bUnZIp = false;
            try
            {
                // DB Connect
                m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource, m_cPosStatus.Base.LocalDbCatalog, m_cPosStatus.Base.LocalDbUserID, m_cPosStatus.Base.LocalDbPassword);

                string sQuery = "";
                sQuery = "";
                sQuery += "SELECT *  \n";
                sQuery += " FROM POSMST..MST_PGM_VER_NEW  \n";
                sQuery += " WHERE  \n";
                sQuery += " 	CMP_CD	    = '" + m_cPosStatus.Base.CmpCd + "' \n";
                sQuery += " AND STOR_CD     = '" + m_cPosStatus.Base.StoreNo + "' \n";
                sQuery += " AND POS_NO      = '" + m_cPosStatus.Base.PosNo + "' \n";
                sQuery += " AND APP_TYPE    = '1' \n";                                                // 적용구분(1:다운완료, 2:적용완료, F:다운실패, E:적용실패)
                //sQuery += " AND ISNULL(APPLY_DATE, '') <= '" + m_cPosStatus.Base.SaleDate + "'\n";     // 영업일로 하게되면 개점 이전에 적용되지 않아 서버에서 받은 시스템 일자로 조회
                //sQuery += " AND ISNULL(APPLY_DATE, '') + ISNULL(APPLY_TIME, '0000')	<= '" + m_cPosStatus.Base.SaleDate + DateTime.Now.ToString("HHmm") + "'\n";     // 영업일로 하게되면 개점 이전에 적용되지 않아 서버에서 받은 시스템 일자로 조회
                sQuery += " AND ISNULL(APPLY_DATE, '') + ISNULL(APPLY_TIME, '')	<= '" + DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.ToString("HHmm") + "'\n";     // 영업일로 하게되면 개점 이전에 적용되지 않아 서버에서 받은 시스템 일자로 조회
                sQuery += " AND ISNULL(USE_YN, '1') = '" + PosConst.MST_USE_YN.YES + "'  \n";
                sQuery += " ORDER BY 1, 2, 3, 4, 5, 6  \n";
                sQuery = sQuery.Replace("\t", " ");

                iRet = m_cSqlDbService.DBSelect(sQuery, out dtData);

                if (dtData != null && dtData.Rows.Count > 0)
                {
                    foreach (DataRow dr in dtData.Rows)
                    {
                        sGroup = CmUtil.MidH(CmUtil.GetDataRowStr(dr, PosMst.MST_PGM_VER.DATA.KIND), 0, 2);
                        sKind = CmUtil.GetDataRowStr(dr, PosMst.MST_PGM_VER.DATA.KIND);

                        sFTP_IP = CmUtil.GetDataRowStr(dr, "FTP_IP");
                        iFTP_Port = CmUtil.IntParse(CmUtil.GetDataRowStr(dr, "FTP_PORT"));
                        sFTP_ID = CmUtil.GetDataRowStr(dr, "FTP_ID");
                        sFTP_Pwd = CmUtil.GetDataRowStr(dr, "FTP_PWD");

                        sApplyDate = CmUtil.GetDataRowStr(dr, "APPLY_DATE");            // 적용일자
                        sApplyTime = CmUtil.GetDataRowStr(dr, "APPLY_TIME");            // 적용시간
                        sFilePath = CmUtil.GetDataRowStr(dr, "FTP_FILEPATH");           // 파일위치
                        if (CmUtil.RightH(sFilePath, 1) != "/") sFilePath += "/";
                        sFileNm = CmUtil.GetDataRowStr(dr, "FILE_NM");                  // 파일명
                        sFileVer = CmUtil.GetDataRowStr(dr, "FILE_VER");                // 파일버전
                        sFileSeq = CmUtil.GetDataRowStr(dr, "FILE_SEQ");                // 파일Seq
                        sDeployDate = CmUtil.GetDataRowStr(dr, "DEPLOY_DATE");          // 다운로드일자
                        sDeployTime = CmUtil.GetDataRowStr(dr, "DEPLOY_TIME");          // 다운로드시간
                        sDeployDT = CmUtil.GetDataRowStr(dr, "DEPLOY_DT");              // 배포일자
                        sUseYn = "1";                                                   // 사용유무

                        if (sFileNm.Trim() == "") continue;

                        CmUtil.CreateDirectory(sUnzip_PGM_Path);
                        CmUtil.CreateDirectory(sUnzip_IMG_Path);
                        CmUtil.CreateDirectory(BaseCom.NxBackPath + PosConst.BACKUP_PATH.PGM);

                        if (CmUtil.RightH(sFileNm, 3).ToUpper() == "ZIP")
                        {
                            if (sGroup == PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_10)
                                sUnzipPath = sUnzip_IMG_Path;                                  // 이미지
                            else if (sGroup == PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_20)
                                sUnzipPath = sUnzip_PGM_Path;                                   // POS 프로그램
                            else if (sGroup == PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_30)
                                sUnzipPath = sUnzip_RCPTLOGO_Path;                              // 영수증 로고 이미지
                            else if (sGroup == PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_40 || sGroup == PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_50 || sGroup == PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_60)
                                sUnzipPath = sUnzip_SIGNPAD_Path;                               // 서명패드
                            else sUnzipPath = sUnzip_PGM_Path;                                  // 프로그램


                            // 파일 존재 여부 체크
                            if (File.Exists(BaseCom.NxDownPath + sFileNm) != true)
                            {
                                // 적용 상태
                                sApplyType = ItemConst.PGM_DOWN_STATE.Update_Fail;

                                // 다운로드 이력 저장
                                sRet = m_cSvr2Tran.PGMUpdate_History_Isert(sKind, sFileSeq, sFileVer, sFileNm, sApplyDate, sApplyTime, sApplyType, sDeployDate, sDeployTime, sFTP_IP, iFTP_Port.ToString(), sFTP_ID, sFTP_Pwd, sFilePath, "1", sDeployDT, sUseYn);
                                if (sRet != UserCom.RST_OK) continue;

                                // 수신 상태 전송
                                sRet = m_cSvr2Tran.PGMUpdate_Complete(sKind, sApplyType, sFileNm, sFileSeq, sFileVer, sDownDiv, sDeployDate, sDeployDT);
                                if (sRet != UserCom.RST_OK) continue;

                                continue;
                            }

                            // 압축 해제
                            CmUtil.UnZipFile(sUnzipPath, BaseCom.NxDownPath + sFileNm);


                            // 압축 파일 BACKUP으로 이동
                            if (sGroup == PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_20)
                            {
                                // PGM인 경우 차후 복구용으로 별도 위치로 이동한다.
                                CmUtil.FileMove(BaseCom.NxDownPath + sFileNm, BaseCom.NxBackPath + PosConst.BACKUP_PATH.PGM + sFileNm);

                                // POSSTART.EXE가 존재하면 BIN폴더에 덮어쓴다.
                                CmUtil.FileCopy("PosStart.exe", sUnzipPath, BaseCom.NxBinPath, "");

                                bUnZIp = true;
                            }
                            else
                            {
                                // 적용후 zip 파일 삭제
                                CmUtil.FileDelete(BaseCom.NxDownPath + sFileNm);
                            }
                        }
                        else
                        {
                            // 일반 파일이면 적용폴더로 그대로 이동
                            CmUtil.FileMove(BaseCom.NxDownPath + sFileNm, sUnzipPath + sFileNm);
                        }

                        // 적용 상태
                        sApplyType = ItemConst.PGM_DOWN_STATE.Update_OK;

                        // 다운로드 이력 저장
                        sRet = m_cSvr2Tran.PGMUpdate_History_Isert(sKind, sFileSeq, sFileVer, sFileNm, sApplyDate, sApplyTime, sApplyType, sDeployDate, sDeployTime, sFTP_IP, iFTP_Port.ToString(), sFTP_ID, sFTP_Pwd, sFilePath, "1", sDeployDT, sUseYn);
                        if (sRet != UserCom.RST_OK) continue;

                        // 수신 상태 전송
                        sRet = m_cSvr2Tran.PGMUpdate_Complete(sKind, sApplyType, sFileNm, sFileSeq, sFileVer, sDownDiv, sDeployDate, sDeployDT);
                        if (sRet != UserCom.RST_OK) continue;

                        if (sGroup == PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_20)
                        {
                            // 이전 파일 삭제
                            PGM_FileDelete(sKind, sFileVer, sFileSeq);

                            // 프로그램 버전정보 설정
                            SetProgramVerIni(sKind, sFileVer, sFileSeq);
                        }
                    }
                }

                // 사용자 알림 메시지 체크용 설정
                m_bPGMReboot = bUnZIp;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);

                // 수신 상태 전송
                sApplyType = ItemConst.PGM_DOWN_STATE.Update_Fail;
                sRet = m_cSvr2Tran.PGMUpdate_Complete(sKind, sApplyType, sFileNm, sFileSeq, sFileVer, sDownDiv, sDeployDate, sDeployDT);
            }
            return sRet;
        }
        #endregion

        #region 다운로드 프로그램 삭제 (현재 버전과 이전 버전 이외 삭제)
        /// <summary>
        /// 다운로드 프로그램 삭제 (현재 버전과 이전 버전 이외 삭제) 
        /// </summary>
        /// <returns></returns>
        private string PGM_FileDelete(string sKind, string sFileVer, string sFileSeq)
        {
            string sRet = UserCom.RST_ERR;
            string sUnzipPath = BaseCom.NxBackPath + PosConst.BACKUP_PATH.PGM;
            int iRet = -1;
            DataTable dtData = new DataTable();

            string sFileNm = "";

            try
            {
                // DB Connect
                m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource
                                                    , m_cPosStatus.Base.LocalDbCatalog
                                                    , m_cPosStatus.Base.LocalDbUserID
                                                    , m_cPosStatus.Base.LocalDbPassword);
                string sQuery = "";
                sQuery = "";
                sQuery += "SELECT \n";
                sQuery += "		KIND \n";
                sQuery += "	,	FILE_VER \n";
                sQuery += "	,	FILE_SEQ \n";
                sQuery += "	,	FILE_NM \n";
                sQuery += "FROM POSMST..MST_PGM_VER_NEW \n";
                sQuery += "WHERE  \n";
                sQuery += "	   CMP_CD	= '" + m_cPosStatus.Base.CmpCd + "'\n";
                sQuery += "AND STOR_CD  = '" + m_cPosStatus.Base.StoreNo + "'\n";
                sQuery += "AND POS_NO	= '" + m_cPosStatus.Base.PosNo + "'\n";
                sQuery += "AND KIND	    = '" + sKind + "'\n";
                sQuery += "AND APP_TYPE	<> '1' \n";                                  // 적용구분(1:다운완료, 2:적용완료, F:다운실패, E:적용실패)
                sQuery += "AND FILE_VER + CONVERT(VARCHAR(5), FILE_SEQ) < '" + sFileVer + sFileSeq + "'\n";
                sQuery += "AND FILE_VER + CONVERT(VARCHAR(5), FILE_SEQ) NOT IN(SELECT ISNULL(MAX(FILE_VER + CONVERT(VARCHAR(5), FILE_SEQ)), 0) \n";
                sQuery += "					FROM POSMST..MST_PGM_VER_NEW \n";
                sQuery += "					WHERE  \n";
                sQuery += "	                    CMP_CD	= '" + m_cPosStatus.Base.CmpCd + "'\n";
                sQuery += "                 AND STOR_CD  = '" + m_cPosStatus.Base.StoreNo + "'\n";
                sQuery += "                 AND POS_NO	= '" + m_cPosStatus.Base.PosNo + "'\n";
                sQuery += "                 AND KIND	    = '" + sKind + "'\n";
                sQuery += "                 AND APP_TYPE	<> '1' \n";                                  // 적용구분(1:다운완료, 2:적용완료, F:다운실패, E:적용실패)
                sQuery += "                 AND FILE_VER + CONVERT(VARCHAR(5), FILE_SEQ) <> '" + sFileVer + sFileSeq + "'\n";
                sQuery += "                 AND ISNULL(USE_YN, '1') = '" + PosConst.MST_USE_YN.YES + "'  \n";
                sQuery += "                 ) \n";
                sQuery += "AND ISNULL(USE_YN, '1') = '" + PosConst.MST_USE_YN.YES + "'  \n";
                sQuery += "ORDER BY 1, 2, 3 \n";

                sQuery = sQuery.Replace("\t", " ");

                iRet = m_cSqlDbService.DBSelect(sQuery, out dtData);

                if (dtData != null && dtData.Rows.Count > 0)
                {
                    foreach (DataRow dr in dtData.Rows)
                    {
                        sKind = CmUtil.GetDataRowStr(dr, PosMst.MST_PGM_VER.DATA.KIND);
                        sFileNm = CmUtil.GetDataRowStr(dr, PosMst.MST_PGM_VER.DATA.FILE_NM);

                        if (sFileNm.Trim() == "") continue;

                        // 이전 파일 삭제
                        CmUtil.FileDelete(sUnzipPath + sFileNm);
                    }
                }
            }
            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;
        }
        #endregion

        #region 프로그램 버전 ini 저장
        private string SetProgramVerIni(string sKind, string sVer, string sSeq)
        {
            string sRet = UserCom.RST_ERR;

            try
            {
                // 프로그램 버전정보 설정
                switch (sKind)
                {
                    case PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_20 + PosConst.PGM_UPDATE_TYPE.POSDOWN_GROUP_20_DIV.POS_PGM10:
                        {
                            m_cPosStatus.Ver.ProgramVer = sVer;
                            m_cPosStatus.Ver.ProgramVerSeq = sSeq;
                            break;
                        }
                }

                // 프로그램 버전 INI 파일 설정
                CmMessage cmPosConfig = CmMessage.MakeMessageFromFile(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosConfig);
                cmPosConfig.GetMessage("PGMVER").MakeMessageOverWrite("ProgramVer" + CmUtil.MidH(sKind, 2, 2), sVer);
                cmPosConfig.GetMessage("PGMVER").MakeMessageOverWrite("ProgramVerSeq" + CmUtil.MidH(sKind, 2, 2), sSeq);
                cmPosConfig.MakeFileFromMessage(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosConfig);
                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;
        }
        #endregion 
    }
}
