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

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

using System.Data;
using System.Collections;

using System.Security.Cryptography;
using System.Net;
using System.Net.Sockets;
using System.Xml;


/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 중국 위쳇페이 기프트카드-Bai Rong
// 작  성  자 : 김기락
// 변경  이력 : 2017.09.11 최초 작성
/*-----------------------------------------------------------------------------------------------*/

namespace Cosmos.Service
{
    class XiaoChengxuGiftCard : PaymentBase, IPaymentUs
    {
        protected PosStatus m_cPosStatus = new PosStatus();
        private INetworkHttp m_cNetworkHttp = null;

        public XiaoChengxuGiftCard()
        {
            m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
            m_cNetworkHttp = (INetworkHttp)sManager.InitServiceInstance(ServiceLists.AGENT_NETWORK.DLL, ServiceLists.AGENT_NETWORK.NETWORK_HTTP);
        }

        #region SearchPayment 결제 조회
        /// <summary>
        /// 결제 조회
        /// </summary>
        /// <param name="aParam"></param>
        /// <param name="aRet"></param>
        /// <returns></returns>
        public string SearchPayment(string[] aParam, ref string[] aRet)
        {
            string sRet = UserCom.RST_ERR;

            try
            {

            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                   System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            finally
            {
                //여전법 대응!
                //////////////////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref aParam);
                //////////////////////////////////////////////////////////////////////////////////
            }
            return sRet;
        }
        #endregion

        #region GetPayment 결제 정보 획득
        /// <summary>
        /// 결제 정보 획득
        /// </summary>
        /// <param name="aParam"></param>
        /// <returns></returns>
        public object GetPayment(string[] aParam)
        {
            return m_cPayItem;
        }
        #endregion

        #region SetPayment 결제 등록
        /// <summary>
        /// 결제 등록
        /// </summary>
        /// <param name="aParam"></param>
        /// <returns></returns>
        public string SetPayment(string[] aParam)
        {
            string sRet = UserCom.RST_ERR;         
            string sPosMenuKey = "", sInPutType = "", sInPutData = "", sInEncData = "";


            int total_fee = 0; //결제할 금액
            int gift_card_used_fee = 0;//실제 소비된 금액           
            string returnString = string.Empty;
            string[] aReturnString = null;

            returnString = sRet + "^" + total_fee.ToString() + "^" + gift_card_used_fee.ToString() + "^0";

            try
            {
                sPosMenuKey = aParam[0];                     // 메뉴키
                sInPutType = aParam[1];                      // 입력구분 (카드 번호 리딩 타입..)
                sInPutData = aParam[2];                      // 입력데이터 ( 카드 번호)
                sInEncData = aParam[3];                      // 카드데이터 ( encrypt 카드 번호)
                double nPayAmt = CmUtil.DoubleParse(aParam[4]);     // 대상금액
                
                total_fee = (int)CmUtil.DoubleMultiplication(nPayAmt, 100);

                m_cPayItem = new Column.TR_PAYMENT.DATA();      // 결과 저장 변수 생성
                m_cPayItem.PAY_WAY_CD = GetMenuKeyToPayWayCd(sPosMenuKey);  //  MST_PAY_DC.PAY_DC_GRP_TYPE
                m_cPayItem.PAY_DTL_CD_01 = GetMenuKeyToPayDtlCd(sPosMenuKey);  //  MST_PAY_DC.PAY_DC_CD

                sRet = ExecuteIrt(PosConst.CANCEL_DIV.NORMAL, ItemConst.XIAO_GIFTCARD_TRAN_TYPE.APPROVE
                                , sInPutType, sInPutData, sInEncData, nPayAmt
                                , "", "", "", ""
                                , ref gift_card_used_fee);

                if (sRet != UserCom.RST_OK)
                {
                    returnString = sRet + "^" + total_fee.ToString() + "^" + gift_card_used_fee.ToString() + "^" + GetUsePayAmt(nPayAmt, gift_card_used_fee).ToString();
                    return returnString;
                }

                returnString = sRet + "^" + total_fee.ToString() + "^" + gift_card_used_fee.ToString() + "^" + GetUsePayAmt(nPayAmt,gift_card_used_fee).ToString();
             
                // 결제 아이템 추가
                ArrayList alPayItem = (ArrayList)StateObject.GetItemObject(Column.TR_PAYMENT.ITEM);     // 결제 내역 받아 오기
                m_cPayItem.SEQ = alPayItem.Count + 1;
                alPayItem.Add(m_cPayItem);

                m_cDataService.UpdatePluAmount();       // 상품 합계금액 계산(거래해더)
                m_cDataService.UpdatePayAmount();       // 결제 금액 재 계산 처리

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

                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     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 (함수명))
                                     ex.ToString());

            }
            finally
            {
                //여전법 대응!
                //////////////////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref sInPutData);
                CmUtil.ZeroFillClear(ref sInEncData);
                CmUtil.ZeroFillClear(ref aParam);
                //////////////////////////////////////////////////////////////////////////////////
            }

            //return sRet;
            return returnString;
        }

        #endregion

        #region CancelPayment 결제 취소
        public string CancelPayment(string[] aParam)
        {
            //gift card 는 취소 기능 없음
            string sRet = UserCom.RST_ERR;
            string sInPutType = "", sInPutData = "", sInEncData = "";

            try
            {
                //특정 메시지 알람 필요

                

            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                   System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            finally
            {
                //여전법 대응!
                //////////////////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref sInPutData);
                CmUtil.ZeroFillClear(ref sInEncData);
                CmUtil.ZeroFillClear(ref aParam);
                //////////////////////////////////////////////////////////////////////////////////
            }
            return sRet;
        }
        #endregion

        #region RefundPayment 결제 반품   
        
        public string RefundPayment(string[] aParam)
        {
            //gift card 는 반품 기능 없음
            string sRet = UserCom.RST_ERR;
            string sInPutType = "", sInPutData = "", sInEncData = "";

            try
            {
                int nPayRow = CmUtil.IntParse(aParam[0]); // 취소할 행번호
                // 내역 받아 오기
                ArrayList alPayItem = (ArrayList)StateObject.GetItemObject(Column.TR_PAYMENT.ITEM);
                m_cPayItem = (Column.TR_PAYMENT.DATA)alPayItem[nPayRow];

                //기프트카드는 반품 기능을 지원하지 않으므로 전화취소만 처리 가능
                //sInPutType = m_cPayItem.OCCUR_ENTRY_05;          // 입력구분
                //sInMskData = m_cPayItem.OCCUR_ENTRY_01;          // 입력데이터(마스킹)
                //sInEncData = m_cPayItem.CanFiller1;              // 카드데이터(암호화)
                if (m_cPayItem.OCCUR_ENTRY_08.ToString() != ItemConst.PAY_APP_DIV.NORMAL)
                {
                    m_cPayItem.OCCUR_ENTRY_06 = m_cPayItem.OCCUR_ENTRY_02;  // 원승인번호
                    m_cPayItem.OCCUR_ENTRY_07 = m_cPayItem.OCCUR_ENTRY_03;  // 원승인일자
                    sRet = UserCom.RST_OK;
                }
                else
                {
                    sRet = UserCom.RST_ERR;
                }

                CmUtil.ZeroFillClear(ref m_cPayItem.CanFiller1);

                return sRet;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                   System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            finally
            {
                //여전법 대응!
                //////////////////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref sInPutData);
                CmUtil.ZeroFillClear(ref sInEncData);
                CmUtil.ZeroFillClear(ref aParam);
                //////////////////////////////////////////////////////////////////////////////////
            }
            return sRet;
        }
        #endregion

        #region SetMenualPayment
        public string SetMenualPayment(string[] aParam)
        {
            throw new NotImplementedException();
        }
        #endregion

        #region  ExecuteIrt
        /// <summary>
        /// 결제
        /// </summary>
        /// <param name="sTradeDiv">결제/취소/반품 구분</param>
        /// <param name="sTrType">결제/반품 코드 구분</param>
        /// <param name="sInPutType">카드번호</param>
        /// <param name="sInPutData">카드번호</param>
        /// <param name="sInEncData">카드번호</param>
        /// <param name="nPayAmt">결제할 금액</param>
        /// <param name="sApprDate"></param>
        /// <param name="sApprNo"></param>
        /// <param name="sOrdTransID"></param>
        /// <param name="sOrgPayID"></param>
        /// <returns></returns>
        public string ExecuteIrt(string sTradeDiv, string sTrType
                               , string sInPutType, string sInPutData, string sInEncData, double nPayAmt
                               , string sApprDate, string sApprNo, string sOrdTransID, string sOrgPayID
                               , ref int gift_card_used_fee) // 결제시에 파라메타 4개는 실제 사용되지 않음
        {
            //var ran = new Random();  
            
            string sRet = UserCom.RST_ERR;
            string sTransID = DateTime.Now.ToString("yyMMddHHmmssfff") + new Random().Next(9).ToString();//order_num_pos 

            try
            {
                // 승인업체 코드 조회
                string sVanCD = PosMstManager.GetMstPayDc(m_cPayItem.PAY_WAY_CD, m_cPayItem.PAY_DTL_CD_01, PosMst.MST_PAY_DC.DATA.APPR_VEND_CD);//MST_PAY_DC.APPR_VEND_CD

                // 연습모드이면 연습 데이터 설정
                if( m_cPosStatus.Base.TrainingFlag == "1" || m_cPosStatus.Mst.TestStorYn == "1")
                {
                    return SetTrainingData(sTradeDiv, sTrType, sInPutType, sInPutData, sInEncData, nPayAmt, sApprDate, sApprNo, sTransID, sOrdTransID, sOrgPayID);
                }

                Hashtable htRecvData = new Hashtable();
                if (sTradeDiv == PosConst.CANCEL_DIV.NORMAL)
                {
                    sRet = ExecuteXmlIrt(sTradeDiv, m_cPayItem.PAY_WAY_CD, m_cPayItem.PAY_DTL_CD_01, sVanCD, sTrType
                                        , sInPutType, sInPutData, sInEncData, nPayAmt
                                        , sTransID, sOrdTransID, sApprNo, sOrgPayID
                                        , ref htRecvData, ref gift_card_used_fee);
                   
                    if (sRet != UserCom.RST_OK) return sRet;
                }
              
                double nUsePayAmt = GetUsePayAmt(nPayAmt, gift_card_used_fee);//실제 소비된 금액
                #region 승인 상태 설정

                m_cPayItem.PAY_AMT = nUsePayAmt;

                m_cPayItem.PAY_DTL_CD_02 = "";                                                                      // 캠페인코드
                m_cPayItem.PAY_DTL_CD_03 = "";
                m_cPayItem.PAY_DTL_CD_04 = "";
                m_cPayItem.PAY_DTL_CD_05 = PosConst.PAY_DC_TYPE.PAY;

                m_cPayItem.AMT_ENTRY_01 = nUsePayAmt;                                                                  // 사용포인트
                m_cPayItem.AMT_ENTRY_02 = 0;                                                                        // 제휴 할인 금액
                m_cPayItem.AMT_ENTRY_03 = 0;
                m_cPayItem.AMT_ENTRY_04 = 0;
                m_cPayItem.AMT_ENTRY_05 = 0;
                m_cPayItem.AMT_ENTRY_06 = 0;
                m_cPayItem.AMT_ENTRY_07 = 0;
                m_cPayItem.AMT_ENTRY_08 = 0;
                m_cPayItem.AMT_ENTRY_09 = 0;
                m_cPayItem.AMT_ENTRY_10 = 0;

                m_cPayItem.OCCUR_ENTRY_01 = sInPutData;                                                             // 카드번호
                if (sTradeDiv == PosConst.CANCEL_DIV.NORMAL)//승인번호
                {
                    //m_cPayItem.OCCUR_ENTRY_02 = htRecvData.ContainsKey("transaction_id") ? htRecvData["transaction_id"].ToString().Trim() : ""; //결제 번호, htRecvData["out_trade_no"].
                    //m_cPayItem.OCCUR_ENTRY_02 = htRecvData.ContainsKey("out_trade_no") ? htRecvData["out_trade_no"].ToString().Trim() : ""; //결제 번호
                    m_cPayItem.OCCUR_ENTRY_02 = sTransID;//위쳇 바이롱에서는 이번호가 상가 주문번호로 승인번호로 사용하여도 됨.
                }
                else
                {
                    m_cPayItem.OCCUR_ENTRY_02 = sApprNo;
                }
                m_cPayItem.OCCUR_ENTRY_03 = DateTime.Now.ToString("yyyyMMdd");                                      // 승인일자
                m_cPayItem.OCCUR_ENTRY_04 = DateTime.Now.ToString("HHmmss");                                        // 승인시간
                m_cPayItem.OCCUR_ENTRY_05 = sInPutType;                                                             // 입력 구분
                m_cPayItem.OCCUR_ENTRY_06 = sApprNo;                                                                // 원승인번호
                m_cPayItem.OCCUR_ENTRY_07 = sApprDate;                                                              // 원승인일자
                m_cPayItem.OCCUR_ENTRY_08 = ItemConst.PAY_APP_DIV.NORMAL;

                if (sTradeDiv == PosConst.CANCEL_DIV.NORMAL)
                {
                    m_cPayItem.OCCUR_ENTRY_09 = sTransID;                                                           // 전송번호
                    m_cPayItem.OCCUR_ENTRY_10 = "10006";                        // 결제구분 (10001:알리페이, 10004:위챗페이)
                }
                else
                {
                    m_cPayItem.OCCUR_ENTRY_09 = sOrdTransID;                                                        // 원전송번호
                    m_cPayItem.OCCUR_ENTRY_10 = sOrgPayID;                                                          // 원결제구분 (10001:알리페이, 10004:위챗페이)
                }

                m_cPayItem.OCCUR_ENTRY_11 = "";
                m_cPayItem.OCCUR_ENTRY_12 = "";
                m_cPayItem.OCCUR_ENTRY_13 = "";
                m_cPayItem.OCCUR_ENTRY_16 = sVanCD;              // VAN 구분
                m_cPayItem.OCCUR_ENTRY_20 = GetPayDtlCdToPayDtlName(m_cPayItem.PAY_WAY_CD, m_cPayItem.PAY_DTL_CD_01);   // 결제수단명 (바이롱...)

                m_cPayItem.CANCEL_DIV = ItemConst.PAY_CANCEL_DIV.NORMAL;            // (cancel 경우에는 CancelPayment() 에서 재설정함. )
                m_cPayItem.BILLSPR_NO = m_cTrnStatus.Sale.BillSplitNo;              // 빌분리 번호

                #endregion


                sRet = UserCom.RST_OK;

                return sRet;            

            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
                
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     UserCom.ERROR_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 (함수명))
                                     ex.ToString());
            }

            return sRet;  
        }

        
        #endregion

        #region 기프트 카드 결제 요청
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sTradeDiv"></param>
        /// <param name="sPAY_WAY_CD">결제 수단 코드</param>
        /// <param name="sPAY_DTL_CD_01">결제 수단 상세 코드</param>
        /// <param name="sVanCD"></param>
        /// <param name="sTrType"></param>
        /// <param name="sInPutType"></param>
        /// <param name="sInPutData"></param>
        /// <param name="sInEncData"></param>
        /// <param name="nPayAmt"></param>
        /// <param name="sTransID"></param>
        /// <param name="sOrdTransID"></param>
        /// <param name="sApprNo"></param>
        /// <param name="sOrgPayID"></param>
        /// <param name="htRecvData"></param>
        /// <returns></returns>
        private string ExecuteXmlIrt(string sTradeDiv, string sPAY_WAY_CD, string sPAY_DTL_CD_01, string sVanCD, string sTrType
                                   , string sInPutType, string sInPutData, string sInEncData, double nPayAmt
                                   , string sTransID, string sOrdTransID , string sApprNo, string sOrgPayID
                                   , ref Hashtable htRecvData, ref int gift_card_used_fee)
        {
         
            string sRet = UserCom.RST_ERR;
            
           
            
            try
            {
                #region try
                string order_num_pos = sTransID;               
              
                // 전문 생성 
                string stSendData = MakeGiftCardBodyData(sInEncData, nPayAmt, sTransID);
                string sWriteSendData = CmUtil.MakeLogDataToMask(false, sInEncData, stSendData);//로그에는 카드 번호 일부 숨김 처리

                // 요청 - 승인로그 저장   (판매구분, [0]결제수단, [1]결제상세코드, [2]전문구분, [3]요청구분, [4]카드번호, [5]결제금액, [6]승인번호, [7]승인일자, [8]승인시간, [9]응답상태값, [10]응답메시지, [11]전문)
                m_cDataCommon.SetSaleApprLog(sTradeDiv, new string[] { sPAY_WAY_CD, sPAY_DTL_CD_01, sTrType, "S", sInPutData, nPayAmt.ToString(), "", "", "", "", "", sWriteSendData });

                UserLog.WriteLogFile(UserCom.LOG_OP, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                               System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                               "[gift card send data:" + stSendData);
                
                //전문 송.수신
                string sRespData = string.Empty;
                int iRet = m_cNetworkHttp.HttpPOST_SendReceive(WeXiaoConfig.GIFTCARD_URL, "text/xml", stSendData, ref  sRespData);
                if (iRet != BaseCom.OK)
                {
                    if (m_bErrMsgShow == true) WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0158));
                    
                    return sRet;
                }
                                
                // 수신 처리
                bool isCheckSign = false;
                WeXiaoData result = new WeXiaoData();
                //SortedDictionary<string, object> dicResult = result.FromResponse(sRespData, ref htRecvData, ref isCheckSign);
                result.FromResponse(sRespData, ref htRecvData, ref isCheckSign);

                string return_code = string.Empty; string return_msg = string.Empty;
                string result_code = string.Empty; string err_code = string.Empty; string err_code_des = string.Empty;
                

                if (result.IsKeyValue("return_code"))
                {
                    #region
                    return_code = result.GetValue("return_code").ToString();
                    return_msg = result.IsKeyValue("return_msg") ? result.GetValue("return_msg").ToString() : "";

                    result_code = result.IsKeyValue("result_code") ? result.GetValue("result_code").ToString() : "";
                    err_code = result.IsKeyValue("err_code") ? result.GetValue("err_code").ToString() : "";
                    err_code_des = result.IsKeyValue("err_code_des") ? result.GetValue("err_code_des").ToString() : "";

                    gift_card_used_fee = result.IsKeyValue("gift_card_used_fee") ? int.Parse(result.GetValue("gift_card_used_fee").ToString()) : 0;
                    #endregion
                }

                string sWriteRecvData = CmUtil.MakeLogDataToMask(false, sInEncData, sRespData);
                m_cDataCommon.SetSaleApprLog(sTradeDiv, new string[] { sPAY_WAY_CD, sPAY_DTL_CD_01, sTrType, "R", sInPutData, nPayAmt.ToString(), sTransID, DateTime.Now.ToString("yyyyMMdd"), DateTime.Now.ToString("HHmmss"), return_code + "," + result_code, "return_msg:" + return_msg + ",err_code_des:" + err_code_des, sWriteRecvData });

                UserLog.WriteLogFile(UserCom.LOG_OP, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                               System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                               "[gift card receive data:" + sRespData);

                string sErrorMessage = string.Empty;

                #region  명백할 경우 바로 리턴 처리
                if (string.IsNullOrEmpty(return_code))
                {
                    sErrorMessage = "return_code Exception";
                    sRet = UserCom.RST_ERR;                    
                    if (m_bErrMsgShow) WinManager.ErrorMessage(sErrorMessage + "(" + return_code + ")");                 
                    return sRet;                    
                }
                if (!return_code.ToUpper().Equals(WeXiaoConfig.SUCCESS))//인터페이스 실패
                {
                    sErrorMessage = return_msg;
                    sRet = UserCom.RST_ERR;                   

                    if (m_bErrMsgShow) WinManager.ErrorMessage(sErrorMessage + "(" + return_code + ")");
                                        
                    return sRet;
                }
                //인터페이스 성공, 비지니스 성공
                if (return_code.ToUpper().Equals(WeXiaoConfig.SUCCESS) && result_code.ToUpper().Equals(WeXiaoConfig.SUCCESS))
                {                    
                    sRet = UserCom.RST_OK;
                    return sRet;
                }
                #endregion

                //명백한 오류는 조회 하지 않음
                if (!err_code.ToUpper().Equals(WeXiaoConfig.SYSTEMERROR) && !err_code.ToUpper().Equals(WeXiaoConfig.UNKNOWN))
                {
                    #region
                    //사용자에게 노출 메시지는 상세 코드 필요함. 
                    if (!err_code_des.Equals("")) sErrorMessage = err_code_des + " (err_code:" + err_code + ")";
                    else sErrorMessage = return_msg + " (return_code:" + return_code + ")";
                   
                    sRet = UserCom.RST_ERR;

                    if (m_bErrMsgShow) WinManager.ErrorMessage(sErrorMessage);
                   
                    return sRet;
                    #endregion
                }

                //요청 상태 조회 
                if (err_code.ToUpper().Equals(WeXiaoConfig.SYSTEMERROR) || err_code.ToUpper().Equals(WeXiaoConfig.UNKNOWN))
                {
                    #region  조회 전문 실행(USERPAYING 일 경우 조회 체크)
                    //30초 동안 최대 10회 진행
                    int retryCount = 0;
                    int maxRetryCount = 10;
                    DateTime startTime = DateTime.Now;
                    TimeSpan durationSec = new TimeSpan(0, 0, 30);//30 초

                    int queryResultCode = 0;//조회 결과 , queryResultCode = 0 : 명확한 오류 발생으로 재조회 하지 않음 , queryResultCode = 1 : 성공, queryResultCode =2 : 다시 조회
                    int query_gift_card_used_fee = 0;//쿼리 조회결과 소비된 금액

                    while (startTime.Add(durationSec) > DateTime.Now && retryCount < maxRetryCount)
                    {
                        query_gift_card_used_fee = 0;
                        retryCount++;
                        WeXiaoData resultWeChatQuery = GiftCardQueryResult(order_num_pos, ref queryResultCode, ref query_gift_card_used_fee);
                        if (queryResultCode == 1) //성공
                        {
                            break;
                        }
                        else if (queryResultCode == 2) //다시 조회 시도
                        {
                            System.Threading.Thread.Sleep(2000);
                            continue;
                        }
                        else // 명확한 오류
                        {
                            break;
                        }
                    }//while end


                    gift_card_used_fee = query_gift_card_used_fee;
                    if (queryResultCode == 1)
                    {
                        sRet = UserCom.RST_OK;
                    }
                    else
                    {
                        sRet = UserCom.RST_ERR;                        
                    }
                    #endregion

                    UserLog.WriteLogFile(UserCom.LOG_OP, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                               System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                               "[gift care query result colde, retry count:" + queryResultCode.ToString() + ","+retryCount.ToString());
                }

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

                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     UserCom.ERROR_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 (함수명))
                                     ex.ToString());
            }
            finally
            {
                //여전법 대응!
                ////////////////////////////////////////////////////////////////////////////////// 
                CmUtil.ZeroFillClear(ref sInPutData);
                CmUtil.ZeroFillClear(ref sInEncData);
                //////////////////////////////////////////////////////////////////////////////////
            }
                        
            return sRet;
        }

        /// <summary>
        /// 기프트카드 body 전문
        /// </summary>        
        /// <param name="sInEncData"></param>
        /// <param name="nPayAmt"></param>
        /// <param name="sTransID">주문번호</param>
        /// <returns></returns>
        public string MakeGiftCardBodyData(string sInEncData, double nPayAmt, string sTransID)
        {

            string order_num_pos = sTransID;// WeXiaoUtil.MakeOutTradeNo(sTransID );
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string create_time = Convert.ToInt64(ts.TotalSeconds).ToString();

            int cost_price = 0;//상품 총 금액
            int total_fee = 0; //결제할 금액
            string body = string.Empty;

            total_fee = (int)CmUtil.DoubleMultiplication(nPayAmt, 100);////CmUtil.IntParse((nPayAmt * 100)).ToString();
            
            //string sApprID = "TEST001";//@@바이롱에서 부여하는 코드..

            WeXiaoData data = new WeXiaoData();
            data.SetValue("order_num_pos", order_num_pos);//주문 번호
            data.SetValue("total_fee", total_fee);
            data.SetValue("gift_card_code", sInEncData);//카드 번호
            data.SetValue("store_num_pos", m_cPosStatus.Base.StoreNo+"_"+m_cPosStatus.Base.PosNo);//점포코드_포스번호
            //data.SetValue("store_num_pos", sApprID);//@@@@@q
            data.SetValue("create_time", create_time);
            data.SetValue("goods_list", GetGoodsDetail(ref cost_price, ref body));
            data.SetValue("marchine_code_pos", WeXiaoUtil.GetPOS_IP());
            data.SetValue("nonce_str", WeXiaoUtil.MakeNonceString());
            data.SetValue("sign", data.MakeSign());

            return data.MakeSendXmlString().Trim();
        }

        /// <summary>
        ///상품 상세 정보
        /// </summary>
        /// <param name="cost_price">상품 전체 금액</param>
        /// <param name="body">상품정보 조합된 json</param>
        /// <returns></returns>
        private string GetGoodsDetail(ref int cost_price, ref string body)
        {
            StringBuilder sbDetail = new StringBuilder();
            ArrayList aSaleItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);

            int nCostPrice_Fen = 0;//상품 전체 가격 (분)
            int nGoodsPrice_Fen = 0; //개당 상품가격 (분)

            sbDetail.Append("{");
            sbDetail.Append("\"cost_price\":2^31,");//상품 가격(할인된 금액 아님)
            sbDetail.Append("\"receipt_id\":\"\",");//영수증 번호
            sbDetail.Append("\"goods_detail\":");
            sbDetail.Append("[");

            if (aSaleItem.Count == 0) sbDetail.Append("{}");//결재창까지 왔다면 이런 경우 없음.
            else
            {
                for (int iRow = 0; iRow < aSaleItem.Count; iRow++)
                {
                    Column.TR_PLU.DATA cSaleItem = (Column.TR_PLU.DATA)aSaleItem[iRow];

                    if (cSaleItem.CANCEL_DIV == PosConst.CANCEL_DIV.CANCEL || cSaleItem.CANCEL_DIV_MAIN == PosConst.CANCEL_DIV.CANCEL) continue; // 지정취소
                    
                    nGoodsPrice_Fen = CmUtil.IntParse((cSaleItem.SALE_AMT * 100).ToString());// (int)(Convert.ToDecimal(cSaleItem.BILL_AMT) * 100);

                    sbDetail.Append("{");
                        sbDetail.Append("\"goods_id\":\"" + cSaleItem.ITEM_PLU_CD + "\",");
                        sbDetail.Append("\"goods_name\":\"" + cSaleItem.ITEM_NAME + "\",");
                        sbDetail.Append("\"quantity\":" + CmUtil.IntParse(cSaleItem.SALE_QTY.ToString()) + ",");
                        sbDetail.Append("\"price\":" + nGoodsPrice_Fen.ToString() + "");
                    sbDetail.Append("}");

                    if (iRow < aSaleItem.Count - 1) sbDetail.Append(",");

                    nCostPrice_Fen += nGoodsPrice_Fen * CmUtil.IntParse(cSaleItem.SALE_QTY.ToString());
                    if (iRow == 0) body = cSaleItem.ITEM_NAME;
                }
            }

            sbDetail.Append("]");
            sbDetail.Append("}");

            cost_price = nCostPrice_Fen;
            return sbDetail.ToString().Replace("2^31", nCostPrice_Fen.ToString());
        }

        #endregion

        #region 기프트카드 결제 조회
        
        /// <summary>
        /// 기프트카드 조회 쿼리 결과
        /// </summary>
        /// <param name="order_num_pos">주문번호</param>
        /// <param name="queryResultCode"></param>
        /// <returns></returns>
        private WeXiaoData GiftCardQueryResult(string order_num_pos, ref int queryResultCode, ref int query_gift_card_used_fee)
        {
            
            string resultXmlString = string.Empty;//조회 결과 xml
            int iRet = GiftCardQuery(order_num_pos, ref resultXmlString);

            if (iRet != BaseCom.OK)
            {
                queryResultCode = 0;// queryResultCode = 0 : 명확한 오류 발생 , queryResultCode = 1 : 성공, queryResultCode =2 : 다시 조회
            }

            bool isCheckSign = false;
            WeXiaoData queryResult = new WeXiaoData();
            queryResult.FromResponse(resultXmlString, ref isCheckSign);


            if (   queryResult.IsKeyValue("return_code") && queryResult.GetValue("return_code").ToString().ToUpper().Equals(WeXiaoConfig.SUCCESS)
                && queryResult.IsKeyValue("result_code") && queryResult.GetValue("result_code").ToString().ToUpper().Equals(WeXiaoConfig.SUCCESS))
            {
                queryResultCode = 1;//조회 성공
                query_gift_card_used_fee = queryResult.IsKeyValue("gift_card_used_fee") ? int.Parse(queryResult.GetValue("gift_card_used_fee").ToString()) : 0;
                return queryResult;
            }
            else
            {
                if (queryResult.IsKeyValue("err_code") && queryResult.GetValue("err_code").ToString().ToUpper().Equals("ORDERNOTEXIST"))//명확한 오류
                {
                    queryResultCode = 0;//오류 발생
                }
                else
                {
                    queryResultCode = 2;//다시 조회 요청
                }
            }

            return queryResult;

        }

        /// <summary>
        /// 기프트카드 조회
        /// </summary>
        /// <param name="order_num_pos">주문번호</param>
        /// <param name="resultXmlString"></param>
        /// <returns></returns>
        private int GiftCardQuery(string order_num_pos, ref string resultXmlString)
        {            
            WeXiaoData data = new WeXiaoData();
            data.SetValue("order_num_pos", order_num_pos);           
            data.SetValue("nonce_str", WeXiaoUtil.MakeNonceString());
            data.SetValue("sign", data.MakeSign());//맨 나중에
            string xmlString = data.MakeSendXmlString();
            int iRet = m_cNetworkHttp.HttpPOST_SendReceive(WeXiaoConfig.GIFTCARD_QUERY_URL, "text/xml", xmlString, ref  resultXmlString);


            UserLog.WriteLogFile(UserCom.LOG_SOCK, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                 System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                 "[Gift card Query SEND<>RECV:" + xmlString+ resultXmlString);

            return iRet;
        }

        #endregion

        /// <summary>
        /// 기프트카드 실제 소비된 금액
        /// </summary>
        /// <param name="nPayAmt"></param>
        /// <param name="gift_card_used_fee"></param>
        /// <returns></returns>
        private double GetUsePayAmt(double nPayAmt, int gift_card_used_fee)
        {
            //실제 결제된 금액 계산
            int total_fee = 0; //결제할 금액
            double nUsePayAmt = nPayAmt;//소비된 금액

            total_fee = (int)CmUtil.DoubleMultiplication(nPayAmt, 100);

            if (total_fee != gift_card_used_fee)
            {
                nUsePayAmt = CmUtil.DoubleDivision(gift_card_used_fee, 100);
            }

            return nUsePayAmt;
        }

        #region 연습모드
        public string SetTrainingData(string sTradeDiv, string sTrType
                                    , string sInPutType, string sInPutData, string sCardData, double nPayAmt
                                    , string sApprDate, string sApprNo, string sTransID, string sOrdTransID, string sOrgPayID)
        {
             string sRet = UserCom.RST_ERR;
             try
             {
                 // 연습모드이면 연습 데이터 설정

                 // 승인업체 코드 조회
                 string sVanCD = PosMstManager.GetMstPayDc(m_cPayItem.PAY_WAY_CD, m_cPayItem.PAY_DTL_CD_01, PosMst.MST_PAY_DC.DATA.APPR_VEND_CD);//MST_PAY_DC.APPR_VEND_CD

                 // 결제구분 (1:결제, 2:할인)
                 DataRow dr = PosMstManager.GetMstPayDc(new string[] { m_cPosStatus.Base.CmpCd, m_cPosStatus.Base.StoreNo, m_cPayItem.PAY_WAY_CD, m_cPayItem.PAY_DTL_CD_01 });

                 m_cPayItem.PAY_AMT = nPayAmt;

                 m_cPayItem.PAY_DTL_CD_02 = "";                                  // 캠페인코드
                 m_cPayItem.PAY_DTL_CD_03 = "";
                 m_cPayItem.PAY_DTL_CD_04 = "";
                 m_cPayItem.PAY_DTL_CD_05 = PosConst.PAY_DC_TYPE.PAY;            // 할인결제구분 (1:결제, 2:할인)

                 m_cPayItem.AMT_ENTRY_01 = nPayAmt;                              // 사용포인트
                 m_cPayItem.AMT_ENTRY_02 = 0;                                    // 제휴 할인 금액
                 m_cPayItem.AMT_ENTRY_03 = 0;                                    // 총포인트
                 m_cPayItem.AMT_ENTRY_04 = 0;                                    // 가용포인트
                 m_cPayItem.AMT_ENTRY_05 = 0;                                    // 잔여포인트
                 m_cPayItem.AMT_ENTRY_08 = 0;

                 m_cPayItem.OCCUR_ENTRY_01 = sInPutData;                         // 카드번호
                 m_cPayItem.OCCUR_ENTRY_02 = "99999999";                         // 승인번호
                 m_cPayItem.OCCUR_ENTRY_03 = DateTime.Now.ToString("yyMMdd");    // 승인일자
                 m_cPayItem.OCCUR_ENTRY_04 = DateTime.Now.ToString("HHmmss");    // 승인시간
                 m_cPayItem.OCCUR_ENTRY_05 = sInPutType;                         // 입력 구분
                 m_cPayItem.OCCUR_ENTRY_06 = sApprNo;                            // 원승인번호(최초에는 없음)
                 m_cPayItem.OCCUR_ENTRY_07 = sApprDate;                          // 원승인일자(최초에는 없음)
                 m_cPayItem.OCCUR_ENTRY_08 = ItemConst.PAY_APP_DIV.NORMAL;       //승인구분

                 if (sTradeDiv == PosConst.CANCEL_DIV.NORMAL)
                 {
                     m_cPayItem.OCCUR_ENTRY_09 = sTransID;                       // 전송번호(HHmmssfff)
                     //if (CmUtil.LeftH(sInPutData, 2) == "13")
                     //    m_cPayItem.OCCUR_ENTRY_10 = "10004";                    // 결제구분 (10001:알리페이, 10004:위챗페이,10005:위챗페이 - 바이롱)
                     //else
                     //    m_cPayItem.OCCUR_ENTRY_10 = "10001";

                     m_cPayItem.OCCUR_ENTRY_10 = "10006";                        //결제구분 (10006:샤오청쉬-기프트카드)
                 }
                 else
                 { //(최초에는 없음, 즉 PosConst.CANCEL_DIV.NORMAL 에는 없음.)
                     m_cPayItem.OCCUR_ENTRY_09 = sOrdTransID;                    // 원전송번호
                     m_cPayItem.OCCUR_ENTRY_10 = sOrgPayID;                      // 원결제구분 (10001:알리페이, 10004:위챗페이)
                 }
                 m_cPayItem.OCCUR_ENTRY_11 = "";
                 m_cPayItem.OCCUR_ENTRY_12 = "";
                 m_cPayItem.OCCUR_ENTRY_13 = "";
                 m_cPayItem.OCCUR_ENTRY_16 = sVanCD;              // VAN 구분
                 m_cPayItem.OCCUR_ENTRY_20 = GetPayDtlCdToPayDtlName(m_cPayItem.PAY_WAY_CD, m_cPayItem.PAY_DTL_CD_01);   // 결제수단명
                 //m_cPayItem.CanFiller1 = sCardData;

                 m_cPayItem.CANCEL_DIV = ItemConst.PAY_CANCEL_DIV.NORMAL;
                 m_cPayItem.BILLSPR_NO = m_cTrnStatus.Sale.BillSplitNo;          // 빌분리 번호

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

                 UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     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 (함수명))
                                     ex.ToString());

             }
             return sRet;
        }

        #endregion
    }
}
