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

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

namespace Cosmos.Service
{
    class VanSpcnCommon : IVanCommonUs
    {
        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        private PosStatus m_cPosStatus = new PosStatus();                           // 기본정보 참조
        private TranStatus m_cTrnStatus = new TranStatus();                         // 거래정보 참조  
      
        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스

        public VanSpcnCommon()
        {
            m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
            m_cTrnStatus = (TranStatus)StateObject.TRAN;    // POS 거래정보                        
            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
        }

        #region 키 다운로드 요청
        /// <summary>
        /// 키 다운로드 요청
        /// </summary>        
        /// <returns></returns>
        public string KeyDownLoad(string[] aParam)
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                string sSendData = string.Empty;// 송신 전문
                string sRecvData = "";         // 수신 전문
                
                // 다운로드 요청 전문 바디 생성                
                string[] aIrtBody = new string[Column.POS_REQ_DOWNLOAD.LEN.Length];
                aIrtBody[Column.POS_REQ_DOWNLOAD.SEQ.ReqLineInfo] = "A";                            // 회선정보
                aIrtBody[Column.POS_REQ_DOWNLOAD.SEQ.ReqPosIp] = "";                                // 포스정보
                aIrtBody[Column.POS_REQ_DOWNLOAD.SEQ.ReqPosDllVer] = m_cPosStatus.Base.PosNo;       // 포스모듈버젼
                aIrtBody[Column.POS_REQ_DOWNLOAD.SEQ.ReqPosSeq] = "";                               // 포스일련번호
                aIrtBody[Column.POS_REQ_DOWNLOAD.SEQ.ReqShopAccountNo] = "1208518096";              // 사업자번호
                aIrtBody[Column.POS_REQ_DOWNLOAD.SEQ.ReqFiller] = "";                               // Filler                
                aIrtBody[Column.POS_REQ_DOWNLOAD.SEQ.ReqETX] = PosConst.VAN_HEXA.ETX;
                aIrtBody[Column.POS_REQ_DOWNLOAD.SEQ.ReqCR] = PosConst.VAN_HEXA.CR;
                
                //다운로드 요청 전문 생성
                sSendData = ItemColumn.MakeMessage(aIrtBody, Column.POS_REQ_DOWNLOAD.LEN, Column.POS_REQ_DOWNLOAD.TYPE);

                // 가맹점 정보 획득(회사승인ID,점포승인ID)
                string sCmpApprID = PosMstManager.GetMstVan(ItemConst.TR_ITEM_ID.CREDITCARD_ITEM, ItemConst.TR_ITEM_ID.CREDITCARD.CREDIT_CARD, PosMst.MST_VAN.DATA.CMP_APPR_ID);
                string sApprID = PosMstManager.GetMstVan(ItemConst.TR_ITEM_ID.CREDITCARD_ITEM, ItemConst.TR_ITEM_ID.CREDITCARD.CREDIT_CARD, PosMst.MST_VAN.DATA.APPR_ID);
                
                // 다운로드 요청 전문 헤더 생성
                sSendData = m_cDataCommon.MakeCreditCardHeader(PosConst.POS_VAN_MASTER.REQ_DOWNLOAD, sSendData.Length, sCmpApprID, sApprID) + sSendData;

                // 다운로드 요청 전문 전송
                sRet = m_cDataCommon.ExecuteCardIrt(PosConst.POS_VAN_MASTER.REQ_DOWNLOAD, sSendData, ref sRecvData, true, "");
                if (sRet != UserCom.RST_OK) return sRet;
                
                byte[] bytes = Encoding.Default.GetBytes(sRecvData);
                int nNowPos = 0;                    
                string[] aIrtDTLRsp = new string[Column.POS_RES_DOWNLOAD.LEN.Length];
                ItemColumn.ParseMessage(Column.POS_RES_DOWNLOAD.LEN, Column.POS_RES_DOWNLOAD.TYPE, bytes, ref nNowPos, ref aIrtDTLRsp);
                    
                if (aIrtDTLRsp[Column.POS_RES_DOWNLOAD.SEQ.ResStatus] != "O")
                {
                    return string.Format("|{0} - {1}{2}", sRet, aIrtDTLRsp[Column.POS_RES_DOWNLOAD.SEQ.ResMessage1], aIrtDTLRsp[Column.POS_RES_DOWNLOAD.SEQ.ResCode]);
                }
                return UserCom.RST_OK;
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.ERROR, UserCom.ERROR_LEVEL, 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>        
        /// <returns></returns>
        public string RuleFileDownLoad(string[] aParam)
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                // 가맹점 정보 획득(회사승인ID,점포승인ID)
                string sCmpApprID = PosMstManager.GetMstVan(ItemConst.TR_ITEM_ID.CREDITCARD_ITEM, ItemConst.TR_ITEM_ID.CREDITCARD.CREDIT_CARD, PosMst.MST_VAN.DATA.CMP_APPR_ID);
                string sApprID = PosMstManager.GetMstVan(ItemConst.TR_ITEM_ID.CREDITCARD_ITEM, ItemConst.TR_ITEM_ID.CREDITCARD.CREDIT_CARD, PosMst.MST_VAN.DATA.APPR_ID);
                if (sCmpApprID == "" || sApprID == "") return sRet;

                int nMaxRuleIndex = 0;              // 총갯수
                string sResultRuleInfo = "";        // 결과전송용
                for (int nRuleIndex = 1; nRuleIndex < 10; nRuleIndex++)
                {
                    // 룰파일정보 = 기기번호(20) + 룰파일인덱스(1) + SPACE(120)
                    string sSendRuleInfo = CmUtil.RPadH(sApprID, 20) + nRuleIndex.ToString() + CmUtil.RPadH("", 120);
                    
                    // 기기번호(20) + 룰파일인덱스(1) + 룰파일총갯수(1) + 룰파일명(24) + 룰파일크기(4) + 알림글내용(820)
                    string sRecvRuleInfo = ExecuteRuleFileIrt(PosConst.POS_VAN_MASTER.RULE_DOWNLOAD_REQ, sSendRuleInfo);
                    if (sRecvRuleInfo.Length < 50) break;

                    nMaxRuleIndex = CmUtil.IntParse(CmUtil.MidH(sRecvRuleInfo, 21, 1));
                    string sRuleFileName = CmUtil.MidH(sRecvRuleInfo, 22, 24);
                    int nRuleDataLen = CmUtil.IntParse(CmUtil.MidH(sRecvRuleInfo, 46, 4));

                    string sRuleData = "";
                    if ( nRuleDataLen > 0) sRuleData = CmUtil.MidH(sRecvRuleInfo, 50, nRuleDataLen);

                    if (sRuleFileName.Trim() != "" && sRuleData.Trim() != "")
                    {
                        // 룰파일 저장 처리
                        if (System.IO.Directory.Exists(BaseCom.NxMstPath + @"RULE\") == false) System.IO.Directory.CreateDirectory(BaseCom.NxMstPath + @"RULE\");

                        string sFileName = BaseCom.NxMstPath + @"RULE\" + sRuleFileName.Trim() + ".txt";
                        CmUtil.WriteTextFile(sFileName, sRuleData, System.Text.Encoding.UTF8);

                        sResultRuleInfo += sRuleFileName;
                    }

                    if (nRuleIndex >= nMaxRuleIndex) break;
                } 

                // 룰파일 다운로드 결과 전송
                if (sResultRuleInfo != "")
                {
                    // 기기번호(20)+룰파일인덱스(1)+룰파일명1(24) +...
                    string sSendRuleInfo = CmUtil.RPadH(sApprID, 20) + nMaxRuleIndex.ToString() + sResultRuleInfo;

                    // 룰파일 다운로드 결과 전송
                    ExecuteRuleFileIrt(PosConst.POS_VAN_MASTER.RULE_RESULT_REQ, sSendRuleInfo);
                }

                return UserCom.RST_OK;
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.ERROR, UserCom.ERROR_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            return sRet;
        }

        /// <summary>
        /// 룰파일 다운로드 IRT 처리
        /// </summary>        
        /// <returns></returns>
        public string ExecuteRuleFileIrt(string sMsgID, string sSendRuleInfo)
        {
            string sRet = UserCom.RST_ERR;
            string sRecvRuleInfo = "";
            try
            {
                string sSendData = "";      // 송신 전문
                string sRecvData = "";      // 수신 전문

                // 룰파일 다운로드 요청 전문 바디 생성                
                string[] aIrtBody = new string[Column.POS_RULEFILE_DOWNLOAD_REQ.LEN.Length];
                aIrtBody[Column.POS_RULEFILE_DOWNLOAD_REQ.SEQ.RuleKind] = "H";
                aIrtBody[Column.POS_RULEFILE_DOWNLOAD_REQ.SEQ.Filler] = "";
                aIrtBody[Column.POS_RULEFILE_DOWNLOAD_REQ.SEQ.FS] = PosConst.VAN_HEXA.FS;
                aIrtBody[Column.POS_RULEFILE_DOWNLOAD_REQ.SEQ.RuleLen] = String.Format("{0:D4}", CmUtil.LenH(sSendRuleInfo));
                aIrtBody[Column.POS_RULEFILE_DOWNLOAD_REQ.SEQ.RuleInfo] = sSendRuleInfo;
                aIrtBody[Column.POS_RULEFILE_DOWNLOAD_REQ.SEQ.ETX] = PosConst.VAN_HEXA.ETX;
                aIrtBody[Column.POS_RULEFILE_DOWNLOAD_REQ.SEQ.CR] = PosConst.VAN_HEXA.CR;

                // 룰파일 다운로드 요청 전문 생성
                sSendData = ItemColumn.MakeMessage(aIrtBody, Column.POS_RULEFILE_DOWNLOAD_REQ.LEN, Column.POS_RULEFILE_DOWNLOAD_REQ.TYPE);

                // 가맹점 정보 획득(회사승인ID,점포승인ID)
                string sCmpApprID = PosMstManager.GetMstVan(ItemConst.TR_ITEM_ID.CREDITCARD_ITEM, ItemConst.TR_ITEM_ID.CREDITCARD.CREDIT_CARD, PosMst.MST_VAN.DATA.CMP_APPR_ID);
                string sApprID = PosMstManager.GetMstVan(ItemConst.TR_ITEM_ID.CREDITCARD_ITEM, ItemConst.TR_ITEM_ID.CREDITCARD.CREDIT_CARD, PosMst.MST_VAN.DATA.APPR_ID);
                // 룰파일 다운로드 요청 전문 헤더 생성
                sSendData = m_cDataCommon.MakeCreditCardHeader(sMsgID, sSendData.Length, sCmpApprID, sApprID) + sSendData;

                // 룰파일 다운로드 요청 전문 전송
                sRet = m_cDataCommon.ExecuteCardIrt(sMsgID, sSendData, ref sRecvData, true, "");
                if (sRet != UserCom.RST_OK)
                {
                    UserLog.WriteLogFile(UserCom.ERROR, UserCom.INFO_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", sRet);
                    return "";
                }

                byte[] bytes = Encoding.Default.GetBytes(sRecvData);
                int nNowPos = 0;
                string[] aIrtDTLRsp = new string[Column.POS_RULEFILE_DOWNLOAD_RES.LEN.Length];
                ItemColumn.ParseMessage(Column.POS_RULEFILE_DOWNLOAD_RES.LEN, Column.POS_RULEFILE_DOWNLOAD_RES.TYPE, bytes, ref nNowPos, ref aIrtDTLRsp);

                if (aIrtDTLRsp[Column.POS_RULEFILE_DOWNLOAD_RES.SEQ.Status] != "O" || aIrtDTLRsp[Column.POS_RULEFILE_DOWNLOAD_RES.SEQ.ResCode] != "0000")
                {
                    string sErrMsg = string.Format("{0}-{1}:{2}", sRet, aIrtDTLRsp[Column.POS_RULEFILE_DOWNLOAD_RES.SEQ.ResMsg], aIrtDTLRsp[Column.POS_RULEFILE_DOWNLOAD_RES.SEQ.ResCode]);

                    UserLog.WriteLogFile(UserCom.ERROR, UserCom.INFO_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", sErrMsg);
                    return "";
                }

                // 기기번호(20) + 룰파일인덱스(1) + 룰파일총갯수(1) + 룰파일명(24) + 룰파일크기(4) + 알림글내용(820)
                sRecvRuleInfo = aIrtDTLRsp[Column.POS_RULEFILE_DOWNLOAD_RES.SEQ.RuleInfo];

                return sRecvRuleInfo;
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.ERROR, UserCom.ERROR_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            return "";
        }
        #endregion

    }
}
