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

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

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 온라인쿠폰 발행(중국)
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Service
{
    class OnLineCouponPrt : OnLineCouponBase, IPaymentUs
    {
        /// <summary>
        /// 마스터 인터페이스
        /// </summary>
        protected IMasterUs m_cMstService = null;

        /// <summary>
        /// 현재 등록중인 기타 정보
        /// </summary>
        protected Column.TR_ETC.DATA m_cEtcItem = null;

        public OnLineCouponPrt()
        {
            m_cMstService = (IMasterUs)sManager.InitServiceInstance(ServiceLists.ASV_MASTER.DLL, ServiceLists.ASV_MASTER.POS_MASTER);
        }

        #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);
            }
            return sRet;
        }
        #endregion

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

        #region SetPayment 결제 등록
        /// <summary>
        /// 온라인 쿠폰 발행
        /// </summary>
        /// <param name="aParam"></param>
        /// <returns></returns>
        public string SetPayment(string[] aParam)
        {
            string sRet = UserCom.RST_ERR;
            string sQuery = "";
            string sInPutType = "", sInPutData = "";

            try
            {
                if (m_cTrnStatus.Head.TradeDiv != ItemConst.TRAN_DIV.NORMAL) return sRet;

                // 온라인 쿠폰 발행 마스터 체크
                sQuery = " SELECT * FROM POSMST..MST_ONLINE_CPN ";
                sQuery += " WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "'";
                sQuery += "   AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "'";
                sQuery += "   AND '" + m_cPosStatus.Base.SaleDate + "' BETWEEN START_DAY AND FNSH_DAY ";
                sQuery += "   AND CPN_STAT  = 'C'";                 // C:확정
                sQuery += "   AND USE_YN  = '" + PosConst.MST_USE_YN.YES + "'";
                sQuery += " ORDER BY PRRTY, START_DAY DESC, CPN_DIV DESC ";
                
                DataTable dtOnLineCpnMst = m_cMstService.Select(new string[] { sQuery });
                if (dtOnLineCpnMst == null || dtOnLineCpnMst.Rows.Count <= 0) return sRet;

                int nPluCount = 0; double nPluAmount = 0;                           // 상품라인수, 상품금액
                string sPluInfo = GetSalePluInfo(ref nPluCount, ref nPluAmount);    // 상품정보 생성
                if (nPluCount <= 0) return sRet;

                m_cEtcItem = new Column.TR_ETC.DATA();
                m_cEtcItem.ETC_WAY_CD = ItemConst.TR_ITEM_ID.ETC_INFO_ITEM;
                m_cEtcItem.ETC_DTL_CD_01 = ItemConst.TR_ITEM_ID.ETC_INFO.ONLINE_CPN;

                string sTranKind = "10";    // 거래구분	요청구분	2	N	10 : 발행, 20 : 승인)
                // 온라인쿠폰 승인(금액설정 => 총매출, 받을금액 JIN확인(07.01.05))
                sRet = ExecuteOnLineCouponIrt(PosConst.CANCEL_DIV.NORMAL, sTranKind, sInPutType, sInPutData, m_cTrnStatus.Head.TotSaleAmt, nPluCount, m_cTrnStatus.Sale.NetSaleAmt, sPluInfo, "", "");
                if (sRet != UserCom.RST_OK) return sRet;

                //1	쿠폰구분코드 5	년(2자리)+순번(3자리)
                string sCpnDiv = m_cEtcItem.OCCUR_ENTRY_01.Substring(0, 5);
                foreach (DataRow dr in dtOnLineCpnMst.Rows)
                {
                    if (CmUtil.GetDataRowStr(dr, "CPN_DIV") == sCpnDiv)
                    {
                        m_cEtcItem.OCCUR_ENTRY_12 = CmUtil.GetDataRowStr(dr, "START_DAY");  // 시작일자
                        m_cEtcItem.OCCUR_ENTRY_13 = CmUtil.GetDataRowStr(dr, "FNSH_DAY");   // 종료일자
                        m_cEtcItem.HP_RESERVED = CmUtil.GetDataRowStr(dr, "PRT_MSG");       // 출력정보
                        break;
                    }
                }

                // 기타 아이템 추가
                ArrayList alEtcItem = (ArrayList)StateObject.GetItemObject(Column.TR_ETC.ITEM);
                m_cEtcItem.SEQ = alEtcItem.Count + 1;
                alEtcItem.Add(m_cEtcItem);
                
            }
            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 CancelPayment 결제 취소
        /// <summary>
        /// 결제 취소
        /// </summary>
        /// <param name="aParam"></param>
        /// <returns></returns>
        public string CancelPayment(string[] aParam)
        {
            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);
            }
            return sRet;
        }
        #endregion

        #region RefundPayment 결제 반품
        /// <summary>
        /// 결제 반품
        /// </summary>
        /// <param name="aParam"></param>
        /// <returns></returns>
        public string RefundPayment(string[] aParam)
        {
            string sRet = UserCom.RST_ERR;

            string sInPutType = "", sInPutData = "";

            try
            {
                int nPayRow = CmUtil.IntParse(aParam[0]);   // 취소할 행번호

                // 결제 내역 받아 오기
                ArrayList alEtcItem = (ArrayList)StateObject.GetItemObject(Column.TR_ETC.ITEM);
                m_cEtcItem = (Column.TR_ETC.DATA)alEtcItem[nPayRow];

                sInPutType = m_cEtcItem.OCCUR_ENTRY_05;         // 입력구분
                sInPutData = m_cEtcItem.OCCUR_ENTRY_01;         // 입력데이터

                if (m_cEtcItem.OCCUR_ENTRY_08.ToString() != ItemConst.PAY_APP_DIV.NORMAL)
                {
                    m_cEtcItem.OCCUR_ENTRY_06 = m_cEtcItem.OCCUR_ENTRY_02;              // 원승인번호
                    m_cEtcItem.OCCUR_ENTRY_07 = m_cEtcItem.OCCUR_ENTRY_03;              // 원승인일자
                }
                else
                {
                    string sApprDate = m_cEtcItem.OCCUR_ENTRY_03 + m_cEtcItem.OCCUR_ENTRY_04;   // 승인일자
                    string sApprNo = m_cEtcItem.OCCUR_ENTRY_02;     // 승인번호

                    string sTranKind = "10";    // 거래구분	요청구분	2	N	10 : 발행, 20 : 승인)
                    sRet = ExecuteOnLineCouponIrt(PosConst.CANCEL_DIV.CANCEL, sTranKind, sInPutType, sInPutData, 0, 0, 0, "", sApprDate, sApprNo);
                    if (sRet != UserCom.RST_OK) return sRet;
                }
                
                sRet = UserCom.RST_OK;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                   System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            return sRet;
        }
        #endregion

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

        #region 온라인쿠폰 발행 조회
        /// <summary>
        /// 온라인쿠폰 발행조회
        /// </summary>
        public string ExecuteOnLineCouponIrt(string sTradeDiv, string sTranKind, string sInPutType, string sInPutData, double nTotSaleAmt, int nPluCount, double nNetSaleAmt, string sPluInfo, string sApprDate, string sApprNo)
        {
            string sRet = UserCom.RST_ERR;
            string sVanCode = "", sServerIP = "", sServerPort = "";
            try
            {
                // 연습모드이면 연습 데이터 설정
                if (m_cPosStatus.Base.TrainingFlag == "1" || m_cPosStatus.Mst.TestStorYn == "1") return sRet;

                sVanCode = PosMstManager.GetMstPayDc(m_cEtcItem.ETC_WAY_CD, m_cEtcItem.ETC_DTL_CD_01, PosMst.MST_PAY_DC.DATA.APPR_VEND_CD);         // 승인업체코드
                sServerIP = PosMstManager.GetMstVan(m_cEtcItem.ETC_WAY_CD, m_cEtcItem.ETC_DTL_CD_01, PosMst.MST_VAN.DATA.IP);
                sServerPort = PosMstManager.GetMstVan(m_cEtcItem.ETC_WAY_CD, m_cEtcItem.ETC_DTL_CD_01, PosMst.MST_VAN.DATA.PORT);
                if (sVanCode == "" || sServerIP == "" || sServerPort == "") return sRet;
                
                // 전송 데이터 생성
                string sSendData = MakeOnLineCouponSendData(sTradeDiv, sTranKind, sInPutType, sInPutData, nTotSaleAmt, nPluCount, nNetSaleAmt, sPluInfo, sApprDate, sApprNo);

                // 전문 송수신 처리
                string[] aIrtRsp = new string[Column.POS_RES_ONLINE_COUPON.LEN.Length];
                if (ExecuteTcpSocket(sServerIP, sServerPort, sSendData, ref aIrtRsp) == false) return UserCom.RST_ERR;  // 송수신

                // 응답코드 체크
                if (aIrtRsp[Column.POS_RES_ONLINE_COUPON.SEQ.ResCD] != "0000") return UserCom.RST_ERR;
                
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////
                // 쿠폰발행
                ///////////////////////////////////////////////////////////////////////////////////////////////////////////
                if (sTradeDiv == PosConst.CANCEL_DIV.NORMAL)
                {
                    m_cEtcItem.AMT_ENTRY_01 = CmUtil.DoubleParse(aIrtRsp[Column.POS_RES_ONLINE_COUPON.SEQ.TotCpnAmt]);   // 받은금액(액면금액)
                    m_cEtcItem.AMT_ENTRY_02 = CmUtil.DoubleParse(aIrtRsp[Column.POS_RES_ONLINE_COUPON.SEQ.DisCpnAmt]);   // 할인금액
                    m_cEtcItem.AMT_ENTRY_03 = CmUtil.DoubleParse(aIrtRsp[Column.POS_RES_ONLINE_COUPON.SEQ.NetCpnAmt]);   // 발행금액
                    m_cEtcItem.AMT_ENTRY_10 = nNetSaleAmt;          // 대상상품금액

                    m_cEtcItem.OCCUR_ENTRY_01 = aIrtRsp[Column.POS_RES_ONLINE_COUPON.SEQ.CouponNo].Trim();               // 쿠폰번호
                    m_cEtcItem.OCCUR_ENTRY_02 = aIrtRsp[Column.POS_RES_ONLINE_COUPON.SEQ.ApprNo].Trim();                 // 승인번호
                    m_cEtcItem.OCCUR_ENTRY_03 = CmUtil.MidH(aIrtRsp[Column.POS_RES_ONLINE_COUPON.SEQ.ApprDT], 0, 8);     // 승인일자
                    m_cEtcItem.OCCUR_ENTRY_04 = CmUtil.MidH(aIrtRsp[Column.POS_RES_ONLINE_COUPON.SEQ.ApprDT], 8, 6);     // 승인시간
                    m_cEtcItem.OCCUR_ENTRY_05 = "";
                    m_cEtcItem.OCCUR_ENTRY_06 = "";                                 // 원승인번호
                    m_cEtcItem.OCCUR_ENTRY_07 = "";                                 // 원승인일자
                    m_cEtcItem.OCCUR_ENTRY_08 = ItemConst.PAY_APP_DIV.NORMAL;       // 승인구분
                    m_cEtcItem.OCCUR_ENTRY_16 = sVanCode;                           // VAN 구분
                    m_cEtcItem.OCCUR_ENTRY_18 = "";                                 // 가맹점번호
                    m_cEtcItem.OCCUR_ENTRY_19 = GetCouponKindName(m_cEtcItem.OCCUR_ENTRY_01);       // 쿠폰종류명
                    m_cEtcItem.OCCUR_ENTRY_20 = GetPayDtlCdToPayDtlName(m_cEtcItem.ETC_WAY_CD, m_cEtcItem.ETC_DTL_CD_01);   // 결제수단명
                    m_cEtcItem.OCCUR_ENTRY_21 = GetPayDtlCdToCashBillYn(m_cEtcItem.ETC_WAY_CD, m_cEtcItem.ETC_DTL_CD_01);   // 현금영수증 발행여부

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

                    m_cEtcItem.HP_CUST_NAME = aIrtRsp[Column.POS_RES_ONLINE_COUPON.SEQ.CpnName].Trim();        // 쿠폰명
                }
                else
                {
                    m_cEtcItem.OCCUR_ENTRY_02 = aIrtRsp[Column.POS_RES_ONLINE_COUPON.SEQ.ApprNo].Trim();                 // 승인번호
                    m_cEtcItem.OCCUR_ENTRY_03 = CmUtil.MidH(aIrtRsp[Column.POS_RES_ONLINE_COUPON.SEQ.ApprDT], 0, 8);     // 승인일자
                    m_cEtcItem.OCCUR_ENTRY_04 = CmUtil.MidH(aIrtRsp[Column.POS_RES_ONLINE_COUPON.SEQ.ApprDT], 8, 6);     // 승인시간
                    m_cEtcItem.OCCUR_ENTRY_06 = sApprNo;                            // 원승인번호
                    m_cEtcItem.OCCUR_ENTRY_07 = sApprDate.Substring(0, 8);          // 원승인일자
                }
                
                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

        /// <summary>
        /// 온라인 쿠폰 TCP 전문 송수신 처리
        /// </summary>
        /// <param name="sServerIP"></param>
        /// <param name="sServerPort"></param>
        /// <param name="sSendData"></param>
        /// <param name="saRecv"></param>
        /// <returns></returns>
        public bool ExecuteTcpSocket(string sServerIP, string sServerPort, string sSendData, ref string[] saRecv)
        {
            try
            {
                // 데이터 송신
                byte[] byteSend = Encoding.Default.GetBytes(sSendData);
                // 데이터 수신
                byte[] byteRecv = new byte[4096];

                int nRecvLen = m_cDataCommon.ExecuteTcpClientIrt("ExecuteOnLineCoupon", sServerIP, CmUtil.IntParse(sServerPort), 10000, byteSend, ref byteRecv, 0);
                if (nRecvLen <= 0)
                {
                    return false;
                }

                // 수신데이터 파싱
                int nNowPos = 0;
                ItemColumn.ParseMessage(Column.POS_RES_ONLINE_COUPON.LEN, Column.POS_RES_ONLINE_COUPON.TYPE, byteRecv, ref nNowPos, ref saRecv);

                return true;
            }
            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 false;
        }


    }
}
