using System;
using System.Text; 
using System.Collections;
using System.Data;

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

using Newtonsoft.Json;
/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 영수증 반품 / 서버 시간 조회 처리
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.BackgroundDown
{
    class Svr2Tran
    {
        #region 변수 선언 및 생성자
        /// <summary>
        /// StateServer Object (StateServer 객체)
        /// </summary>
        private StateServer StateObject = (StateServer)StateServer.GetInstance();

        private NetworkJSON m_cNetJSONService;
        private DatabaseMssql m_cSqlDbService = null;
        Hashtable m_htRecvData = null;                                              // 통신 수신 데이터 (JSON)
        private frmPosIrtMessage m_cfPosIrtMsg = null;

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

        private bool m_bIRTComplete = false; 
        /// <summary>
        /// 생성자
        /// </summary>
        public Svr2Tran()
        {
            SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출

            m_cPosStatus = (PosStatus)StateObject.POS;

            m_cNetJSONService = new NetworkJSON();
            m_cSqlDbService = new DatabaseMssql();
            m_cfPosIrtMsg = new frmPosIrtMessage();

            m_bIRTComplete = false;
        }
        #endregion
         
        #region 서버 시간 조회
        /// <summary>
        /// 서버 시간 조회
        /// </summary>
        /// <returns></returns>
        public string ServerSysDateTime()
        {
            Hashtable htRecvData = new Hashtable();
            Hashtable htSendData = new Hashtable();

            string sRet = UserCom.RST_ERR;
            string sGetDate = "";

            try
            {
                // 서버 조회
                htSendData.Add(Column.IQ_SYSDATE_REQ.DATA.INQ_TYPE, ItemConst.IRT_INQ_TYPE.SYSDATETIME);
                htSendData.Add(Column.IQ_SYSDATE_REQ.DATA.RES_CD, "");
                htSendData.Add(Column.IQ_SYSDATE_REQ.DATA.POS_HOUR, "");
                htSendData.Add(Column.IQ_SYSDATE_REQ.DATA.REG_NO, "");
                htSendData.Add(Column.IQ_SYSDATE_REQ.DATA.TRADE_NO, "");
                htSendData.Add(Column.IQ_SYSDATE_REQ.DATA.SYS_YMDHMS, "");

                sRet = ExecutePosIrt(ItemConst.COMM_MSG_TYPE.POSIRT, m_cPosStatus.Base.CommSvrIp, (int)m_cPosStatus.Base.SysInfoPort, 5000, htSendData, ref htRecvData, false);
                if (sRet == UserCom.RST_OK)
                {
                    if (htRecvData[Column.IQ_SYSDATE_REQ.DATA.RES_CD].ToString() == "00")
                    {
                        sGetDate = htRecvData[Column.IQ_SYSDATE_REQ.DATA.SYS_YMDHMS].ToString();

                        if (sGetDate.Trim().Length == 14) BsUtil.SetSystemDateTime(sGetDate);

                        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 
         
        #region 프로그램 업데이트 목록 조회
        /// <summary>
        /// 프로그램 업데이트 목록 조회
        /// </summary> 
        /// <param name="sKind"></param>
        /// <param name="sDownDiv"></param>
        /// <param name="aRecvData"></param>
        /// <param name="htRecvData"></param>
        /// <returns></returns>
        public string PGMUpdate(string sKind, string sDownDiv, ref string[] aRecvData, ref Hashtable htRecvData)
        {
            Hashtable htSendData = new Hashtable();

            string sRet = UserCom.RST_ERR;

            try
            {
                // 서버 조회
                htSendData.Add(Column.IQ_PGMUPDATE_REQ.DATA.INQ_TYPE, ItemConst.IRT_INQ_TYPE.PGMUPDATE);
                htSendData.Add(Column.IQ_PGMUPDATE_REQ.DATA.FILE_GROUP, CmUtil.MidH(sKind, 0, 2));
                htSendData.Add(Column.IQ_PGMUPDATE_REQ.DATA.FILE_KIND, CmUtil.MidH(sKind, 2, 2));
                htSendData.Add(Column.IQ_PGMUPDATE_REQ.DATA.FILE_APP_TY, "0");
                htSendData.Add(Column.IQ_PGMUPDATE_REQ.DATA.FILE_YMDHMS, DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.ToString("HHmmss"));
                htSendData.Add(Column.IQ_PGMUPDATE_REQ.DATA.DOWN_DIV, sDownDiv);

                sRet = ExecutePosIrt(ItemConst.COMM_MSG_TYPE.POSIRT, m_cPosStatus.Base.CommSvrIp, (int)m_cPosStatus.Base.SysInfoPort, 10000, htSendData, ref htRecvData, false);
                if (sRet == UserCom.RST_OK)
                {
                    if (htRecvData[Column.IQ_PGMUPDATE_RSP.DATA.RES_CD].ToString() == "00" || htRecvData[Column.IQ_PGMUPDATE_RSP.DATA.RES_CD].ToString() == "01")
                    {
                        // 00:정상, 01:데이터 없음
                        aRecvData = htRecvData[Column.IQ_PGMUPDATE_RSP.DATA.VALUE].ToString().Split(new string[] { "#~" }, StringSplitOptions.None);

                        sRet = UserCom.RST_OK;
                    }
                    else
                    {
                        sRet = UserCom.RST_ERR;
                    }
                }
            }
            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 파일 변경 완료 요청
        /// <summary>
        /// 파일 변경 완료 요청
        /// </summary>
        /// <param name="sKind"></param>
        /// <param name="sAppType"></param>
        /// <param name="sFileName"></param>
        /// <param name="sFileSeq"></param>
        /// <param name="sFileVer"></param>
        /// <param name="sDownDiv"></param>
        /// <param name="sDeployDate"></param>
        /// <param name="sDeployDT"></param>
        /// <returns></returns>
        public string PGMUpdate_Complete(string sKind, string sAppType, string sFileName, string sFileSeq, string sFileVer, string sDownDiv, string sDeployDate, string sDeployDT)
        {
            Hashtable htSendData = new Hashtable();
            Hashtable htRecvData = new Hashtable();

            string sRet = UserCom.RST_ERR;

            try
            {
                if (sFileVer.Trim() == "") return sRet;

                // 서버 조회
                htSendData.Add(Column.IQ_PGMUPDATE_COMPLETE_REQ.DATA.INQ_TYPE, ItemConst.IRT_INQ_TYPE.PGMUPDATECOMPLTE);
                htSendData.Add(Column.IQ_PGMUPDATE_COMPLETE_REQ.DATA.FILE_GROUP, CmUtil.MidH(sKind, 0, 2));
                htSendData.Add(Column.IQ_PGMUPDATE_COMPLETE_REQ.DATA.FILE_KIND, CmUtil.MidH(sKind, 2, 2));
                htSendData.Add(Column.IQ_PGMUPDATE_COMPLETE_REQ.DATA.FILE_APP_TY, sAppType);
                htSendData.Add(Column.IQ_PGMUPDATE_COMPLETE_REQ.DATA.FILE_NM, sFileName);
                htSendData.Add(Column.IQ_PGMUPDATE_COMPLETE_REQ.DATA.FILE_VER, sFileVer);
                htSendData.Add(Column.IQ_PGMUPDATE_COMPLETE_REQ.DATA.FILE_SEQ, sFileSeq);
                htSendData.Add(Column.IQ_PGMUPDATE_COMPLETE_REQ.DATA.RES_CD, "");
                htSendData.Add(Column.IQ_PGMUPDATE_COMPLETE_REQ.DATA.DOWN_DIV, sDownDiv);
                htSendData.Add(Column.IQ_PGMUPDATE_COMPLETE_REQ.DATA.DEPLOY_DT, sDeployDate);
                htSendData.Add(Column.IQ_PGMUPDATE_COMPLETE_REQ.DATA.REG_DT, sDeployDT);

                sRet = ExecutePosIrt(ItemConst.COMM_MSG_TYPE.POSIRT, m_cPosStatus.Base.CommSvrIp, (int)m_cPosStatus.Base.SysInfoPort, 10000, htSendData, ref htRecvData, false);
                if (sRet == UserCom.RST_OK)
                {
                    if (htRecvData[Column.IQ_PGMUPDATE_COMPLETE_REQ.DATA.RES_CD].ToString() == "00")
                    {
                        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
         
        #region 프로그램 적용 및 이력 관리
        /// <summary>
        /// 프로그램 이력 관리
        /// </summary>
        /// <param name="sKind"></param>
        /// <param name="sFileSeq"></param>
        /// <param name="sFileVer"></param>
        /// <param name="sFileNm"></param>
        /// <param name="sApplyDate"></param>
        /// <param name="sApplyTime"></param>
        /// <param name="sApplyType"></param>
        /// <param name="sDeployDate"></param>
        /// <param name="sDeployTime"></param>
        /// <param name="sFTP_IP"></param>
        /// <param name="sFTP_Port"></param>
        /// <param name="sFTP_ID"></param>
        /// <param name="sFTP_Pwd"></param>
        /// <param name="sFTP_FILEPATH"></param>
        /// <param name="sDOWN_DIV"></param>
        /// <returns></returns>
        public string PGMUpdate_History_Isert(string sKind, string sFileSeq, string sFileVer, string sFileNm, string sApplyDate, string sApplyTime, string sApplyType, string sDeployDate, string sDeployTime, string sFTP_IP, string sFTP_Port, string sFTP_ID, string sFTP_Pwd, string sFTP_FILEPATH, string sDOWN_DIV, string sDeployDT, string sUseYn)
        {
            string sRet = UserCom.RST_ERR;
            int iRet = -1;

            try
            {
                string sQuery = "";
                sQuery = "";
                sQuery += "IF EXISTS(SELECT CMP_CD \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.Trim() + "' \n";
                sQuery += "            AND FILE_SEQ    = '" + sFileSeq.Trim() + "' \n";
                sQuery += "            AND FILE_VER    = '" + sFileVer.Trim() + "') \n";
                sQuery += "	BEGIN  \n";
                sQuery += "		UPDATE POSMST..MST_PGM_VER_NEW  \n";
                sQuery += "		    SET  \n";
                sQuery += "			    FILE_NM     = '" + sFileNm.Trim() + "' \n";
                sQuery += "		    ,	APPLY_DATE  = '" + sApplyDate.Trim() + "' \n";
                sQuery += "		    ,	APPLY_TIME  = '" + sApplyTime.Trim() + "' \n";
                sQuery += "		    ,	APP_TYPE    = '" + sApplyType + "' \n";
                sQuery += "		    ,	DEPLOY_DATE  = '" + sDeployDate.Trim() + "' \n";
                sQuery += "		    ,	DEPLOY_TIME  = '" + sDeployTime.Trim() + "' \n";
                sQuery += "		    ,	FTP_IP      = '" + sFTP_IP.Trim() + "' \n";
                sQuery += "		    ,	FTP_PORT    = '" + sFTP_Port.Trim() + "' \n";
                sQuery += "		    ,	FTP_ID      = '" + sFTP_ID.Trim() + "' \n";
                sQuery += "		    ,	FTP_PWD     = '" + sFTP_Pwd.Trim() + "' \n";
                sQuery += "		    ,	FTP_FILEPATH     = '" + sFTP_FILEPATH.Trim() + "' \n";
                sQuery += "		    ,	DOWN_DIV    = '" + sDOWN_DIV.Trim() + "' \n";
                sQuery += "		    ,	UPD_DT      = CONVERT(VARCHAR(8), GETDATE(), 112) + REPLACE(CONVERT(VARCHAR(8), GETDATE(), 108), ':', '') \n";
                sQuery += "		    ,	DEPLOY_DT   = '" + sDeployDT.Trim() + "' \n";
                sQuery += "         ,   USE_YN      = '" + sUseYn.Trim() + "' \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.Trim() + "' \n";
                sQuery += "            AND FILE_SEQ    = '" + sFileSeq.Trim() + "' \n";
                sQuery += "            AND FILE_VER    = '" + sFileVer.Trim() + "' \n";
                sQuery += "	END  \n";
                sQuery += "ELSE  \n";
                sQuery += "	BEGIN  \n";
                sQuery += "		INSERT INTO POSMST..MST_PGM_VER_NEW  \n";
                sQuery += "			(CMP_CD, STOR_CD, POS_NO, KIND, FILE_SEQ, FILE_VER, FILE_NM, APPLY_DATE, APPLY_TIME, APP_TYPE, DEPLOY_DATE, DEPLOY_TIME, FTP_IP, FTP_PORT, FTP_ID, FTP_PWD, FTP_FILEPATH, DOWN_DIV, REG_DT, DEPLOY_DT, USE_YN)  \n";
                sQuery += "		VALUES(  \n";
                sQuery += "			    '" + m_cPosStatus.Base.CmpCd + "' \n";
                sQuery += "			,	'" + m_cPosStatus.Base.StoreNo + "' \n";
                sQuery += "			,	'" + m_cPosStatus.Base.PosNo + "' \n";
                sQuery += "			,	'" + sKind.Trim() + "' \n";
                sQuery += "			,	'" + sFileSeq.Trim() + "' \n";
                sQuery += "			,	'" + sFileVer.Trim() + "' \n";
                sQuery += "			,	'" + sFileNm.Trim() + "' \n";
                sQuery += "			,	'" + sApplyDate.Trim() + "' \n";
                sQuery += "			,	'" + sApplyTime.Trim() + "' \n";
                sQuery += "			,	'" + sApplyType + "' \n";
                sQuery += "			,	'" + sDeployDate.Trim() + "' \n";
                sQuery += "			,	'" + sDeployTime.Trim() + "' \n";
                sQuery += "			,	'" + sFTP_IP.Trim() + "' \n";
                sQuery += "			,	'" + sFTP_Port.Trim() + "' \n";
                sQuery += "			,	'" + sFTP_ID.Trim() + "' \n";
                sQuery += "			,	'" + sFTP_Pwd.Trim() + "' \n";
                sQuery += "			,	'" + sFTP_FILEPATH.Trim() + "' \n";
                sQuery += "			,	'" + sDOWN_DIV.Trim() + "' \n";
                sQuery += "			,	CONVERT(VARCHAR(8), GETDATE(), 112) + REPLACE(CONVERT(VARCHAR(8), GETDATE(), 108), ':', '')  \n";
                sQuery += "			,	'" + sDeployDT.Trim() + "' \n";
                sQuery += "         ,   '" + sUseYn.Trim() + "' \n";
                sQuery += "		)  \n";
                sQuery += "	END  \n";
                sQuery = sQuery.Replace("\t", " ");

                m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource, m_cPosStatus.Base.LocalDbCatalog, m_cPosStatus.Base.LocalDbUserID, m_cPosStatus.Base.LocalDbPassword);
                iRet = m_cSqlDbService.DBExecuteNonQuery(new string[] { sQuery });

                if (iRet == 1) 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 

        #region POS IRT 전문 송/수신
        /// <summary>
        /// POS IRT 전문 송/수신(점포서버 송수신: 제이슨 이용)
        /// </summary>
        public string ExecutePosIrt(string sMsgType, string sSvrIP, int nSvrPort, int nTimeout, Hashtable htSendData, ref Hashtable htRecvData, bool bVisibleMode)
        {
            string sRet = UserCom.RST_ERR;

            try
            {
                string sCommHead = ItemColumn.MakeCommHeader(0, sMsgType);        // 통신해더 생성

                if (bVisibleMode == false)
                {
                    // 팝업 화면 미표시
                    m_bIRTComplete = true;
                    m_htRecvData = null;

                    Thread thrSecondDisp = new Thread(() => sRet = OnNetworkIRT(sSvrIP, nSvrPort, nTimeout, sCommHead, htSendData));
                    thrSecondDisp.Start();

                    while (m_bIRTComplete == true)
                    {
                        Thread.Sleep(100);
                    }
                    htRecvData = m_htRecvData;
                }
                else
                {
                    string sDispName = string.Format(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0231), "");

                    m_cfPosIrtMsg.PosMessageStr = sDispName;
                    m_cfPosIrtMsg.ServerIp = sSvrIP;
                    m_cfPosIrtMsg.ServerPort = nSvrPort;
                    m_cfPosIrtMsg.TimeOut = nTimeout;
                    m_cfPosIrtMsg.CommHead = sCommHead;
                    m_cfPosIrtMsg.SendData = htSendData;

                    m_cfPosIrtMsg.ShowDialog();

                    if (m_cfPosIrtMsg.RecvRet != UserCom.OK)
                    {
                        sRet = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0158);
                        // 통신 실패 로그
                        UserLog.WriteLogFile(UserCom.LOG_ERROR, UserCom.WARNING_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                            string.Format("SOCKET ERROR,{0},{1}, RET={2}", sSvrIP, nSvrPort, m_cfPosIrtMsg.RecvRet));
                        return sRet;
                    }
                    htRecvData = m_cfPosIrtMsg.RecvData;

                    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


        #region POS IRT 전문 송수신 - 화면 미표시용
        private string OnNetworkIRT(string sServerIp, int nServerPort, int nTimeOut, string sCommHead, Hashtable htSendData)
        {
            string sRet = UserCom.RST_ERR;
            int nRecvRet = -1;
            try
            {
                m_bIRTComplete = true;

                nRecvRet = m_cNetJSONService.IRTSendReceive(sServerIp, nServerPort, nTimeOut, sCommHead, htSendData, ref m_htRecvData);

                if (nRecvRet == BaseCom.OK) sRet = UserCom.RST_OK;
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR, UserCom.ERROR_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                    "Process Exception !!! " + ex.Message);
            }
            finally
            {
                m_bIRTComplete = false;
            }
            return sRet;
        }
        #endregion

        #region 설정 파일 읽기
        /// <summary>
        /// 설정 파일 읽기
        /// </summary>
        /// <param name="cCfgInfo"></param>
        /// <param name="sGroup"></param>
        /// <param name="sValueName"></param>
        /// <returns></returns>
        private string GetConfigInfo(CmMessage cCfgInfo, string sGroup, string sValueName)
        {
            return GetConfigInfo(cCfgInfo, sGroup, sValueName, "");
        }
        private string GetConfigInfo(CmMessage cCfgInfo, string sGroup, string sValueName, string sDefault)
        {
            try
            {
                string sValue = cCfgInfo.GetMessage(sGroup).GetMessageValue(sValueName);
                if (sValue == null)
                    return sDefault;
                else
                    return sValue;
            }
            catch { }

            return sDefault;
        }
        #endregion 
    }


}
