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

using Newtonsoft.Json;

using Cosmos.UserFrame;
using Cosmos.BaseFrame;
using Cosmos.ServiceProvider;
using Cosmos.Common;
using System.Data;
using System.Globalization;

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 해피앱 스탬프
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Service
{
    class HappyAppStamp : IHappyAppStamp
    {
        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 INetworkHttp m_cNetworkHttp = null;
        private IDataServiceUs m_cWebBiz = null;                                    // 웹정보 서비스

        private string m_HPAPPSTAMP_URL = "";

        /// <summary>
        /// 생성자
        /// </summary>
        public HappyAppStamp()
        {
            m_cPosStatus = (PosStatus)StateObject.POS;
            m_cTrnStatus = (TranStatus)StateObject.TRAN;

            m_cNetworkHttp = (INetworkHttp)sManager.InitServiceInstance(ServiceLists.AGENT_NETWORK.DLL, ServiceLists.AGENT_NETWORK.NETWORK_HTTP);
            m_cWebBiz = (IDataServiceUs)sManager.InitServiceInstance(ServiceLists.BSV_BASIC.DLL, ServiceLists.BSV_BASIC.WEB_POS);

        }

        /// <summary>
        /// 해피앱 스탬프 URL 가져오기
        /// </summary>
        /// <returns></returns>
        public bool GetHappyAppStampURL()
        {
            bool bRet = false;

            try
            {
                string stmp = (string)m_cWebBiz.GetData(new string[] { PosKey.MENU_KEY.HPAPP_STAMP });

                if (string.IsNullOrEmpty(stmp) == false)
                {
                    m_HPAPPSTAMP_URL = CmUtil.MidH(stmp, 30, 100).Trim();
                    bRet = true;
                }

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

        /// <summary>
        /// 해피앱 스탬프 가능 여부 확인
        /// </summary>
        /// <returns></returns>
        public string CheckHappyAppStamp()
        {
            string sRet = "";

            // 해피포인트 적립 체크
            ArrayList alEtcItem = (ArrayList)StateObject.GetItemObject(Column.TR_ETC.ITEM);     // 기타 내역 받아 오기
            foreach (Column.TR_ETC.DATA cEtcItem in alEtcItem)
            {
                //#20171024 해피앱 스탬프 기능 해피앱 고객인 경우에만 적용 start
                //해피포인트 적립이나 사용한 경우 해피앱 고객이고 해피포인트 회원번호가 있는 경우 적용
                //기존
                /*
                if (cEtcItem.ETC_WAY_CD == ItemConst.TR_ITEM_ID.ETC_INFO_ITEM && cEtcItem.ETC_DTL_CD_01 == ItemConst.TR_ITEM_ID.ETC_INFO.SAVEPOINT && cEtcItem.OCCUR_ENTRY_02 != "")
                {
                    sRet = cEtcItem.OCCUR_ENTRY_10;
                    break;
                }
                */
                //변경
                if (cEtcItem.ETC_WAY_CD == ItemConst.TR_ITEM_ID.ETC_INFO_ITEM && 
                    cEtcItem.ETC_DTL_CD_01 == ItemConst.TR_ITEM_ID.ETC_INFO.SAVEPOINT &&
                    cEtcItem.OCCUR_ENTRY_02.Trim() != "" &&
                    cEtcItem.OCCUR_ENTRY_12.Trim() == "Y")
                {
                    sRet = cEtcItem.OCCUR_ENTRY_10;
                    break;
                }
                //#20171024 해피앱 스탬프 기능 해피앱 고객인 경우에만 적용 end
            }

            // 해피포인트 사용 체크 -- 적립 내역 없을 때만 체크
            if (sRet == "")
            {
                ArrayList alPayment = (ArrayList)StateObject.GetItemObject(Column.TR_PAYMENT.ITEM);
                foreach (Column.TR_PAYMENT.DATA cPayItem in alPayment)
                {
                    //#20171024 해피앱 스탬프 기능 해피앱 고객인 경우에만 적용 start
                    //해피포인트 적립이나 사용한 경우 해피앱 고객이고 해피포인트 회원번호가 있는 경우 적용
                    //기존
                    //if (cPayItem.PAY_WAY_CD == ItemConst.TR_ITEM_ID.POINT_ITEM && cPayItem.PAY_DTL_CD_01 == ItemConst.TR_ITEM_ID.POINT_USE.HAPPY_POINT)
                    //변경
                    if (cPayItem.PAY_WAY_CD == ItemConst.TR_ITEM_ID.POINT_ITEM && 
                        cPayItem.PAY_DTL_CD_01 == ItemConst.TR_ITEM_ID.POINT_USE.HAPPY_POINT &&
                        cPayItem.OCCUR_ENTRY_12.Trim() == "Y")
                    //#20171024 해피앱 스탬프 기능 해피앱 고객인 경우에만 적용 end
                    {
                        sRet = cPayItem.OCCUR_ENTRY_10;
                        break;
                    }
                }
            }

            if (sRet != "")
            {
                sRet = sRet.Substring(0, 10);
            }

            return sRet;
        }

        /// <summary>
        /// 해피앱 스탬프 등록/취소
        /// </summary>
        /// <returns></returns>
        public void SetHappyAppStamp()
        {
            string sTrxTypCd = "";  // 거래구분
            string sPosNo = "";     // POS번호
            string sSaleDate = "";  // 판매일자
            string sBarData = "";   // 영수증번호

            string sApprId = CommonManager.PosMstManager.GetMstVan(ItemConst.TR_ITEM_ID.POINT_ITEM, ItemConst.TR_ITEM_ID.POINT_USE.HAPPY_POINT, PosMst.MST_VAN.DATA.APPR_ID);

            try
            {
                if (m_HPAPPSTAMP_URL == "")
                {
                    if (GetHappyAppStampURL() == false)
                    {
                        return;
                    }
                }

                // 상품정보
                ArrayList aSaleItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);

                //아이템 리스트 담기
                Hashtable[] htDatail = new Hashtable[aSaleItem.Count];

                for (int iRow = 0; iRow < aSaleItem.Count; iRow++)
                {
                    Column.TR_PLU.DATA cSaleItem = (Column.TR_PLU.DATA)aSaleItem[iRow];
                    htDatail[iRow] = new Hashtable();
                    htDatail[iRow].Add("item", cSaleItem.ITEM_PLU_CD);   // 상품코드
                    htDatail[iRow].Add("qty", (int)cSaleItem.SALE_QTY);  // 수량
                }

                if (m_cTrnStatus.Head.TradeDiv == ItemConst.TRAN_DIV.NORMAL)
                {
                    sTrxTypCd = "10";   //정상
                    sPosNo = m_cTrnStatus.Head.PosNo;
                    sSaleDate = m_cTrnStatus.Head.SaleDate;
                    sBarData = MakeBarData(sPosNo, sSaleDate, m_cTrnStatus.Head.TradeNo);
                }
                else
                {
                    sTrxTypCd = "20";   // 반품
                    sPosNo = m_cTrnStatus.Head.OrgPosNo;
                    sSaleDate = m_cTrnStatus.Head.OrgSaleDate;
                    sBarData = MakeBarData(sPosNo, sSaleDate, m_cTrnStatus.Head.OrgTradeNo);
                }

                //헤더 담기                
                Hashtable htRequest = new Hashtable();
                htRequest.Add("stoCd", m_cPosStatus.Base.StoreNo);           // 유니크한 점포코드
                htRequest.Add("tmnlNo", sApprId);                            // 단말기 번호
                htRequest.Add("mbrNo", m_cTrnStatus.Sale.HappyAppMemNo);     // 회원번호
                htRequest.Add("posNo", sPosNo);                              // POS 번호
                htRequest.Add("trxDt", sSaleDate);                           // 판매일자
                htRequest.Add("rcptNo", sBarData);                           // POS영수증바코드(RCPTNO)     
                htRequest.Add("trxTypCd", sTrxTypCd);                        // 거래유형코드
                htRequest.Add("trxAmt", (int)m_cTrnStatus.Head.TotSaleAmt);  // 결제금액
                htRequest.Add("items", htDatail);                            // 구매상품리스트

                UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                , "SetHappyAppStamp Start !!!");

                Hashtable htResponse = null;
                SendReceiveForHttps(new object[] { m_HPAPPSTAMP_URL, htRequest }, ref htResponse);

                UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                , "SetHappyAppStamp End  !!!");

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

        /// <summary>
        /// Http 통신
        /// </summary>
        /// <param name="aParam"></param>
        /// <param name="htResponse"></param>
        /// <returns></returns>
        public void SendReceiveForHttps(object[] aParam, ref Hashtable htResponse)
        {
            string sUrl;
            Hashtable htRequest;

            try
            {
                sUrl = (string)aParam[0];
                htRequest = (Hashtable)aParam[1];

                htResponse = null;
                string sResp = string.Empty;

                m_cNetworkHttp.HttpJsonPOST_SendReceiveForStamp(sUrl, htRequest, ref htResponse);

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

        /// <summary>
        /// 바코드 생성
        /// </summary>
        /// <param name="sPosNo"></param>
        /// <param name="sSaleDate"></param>
        /// <param name="sTradeNo"></param>
        /// <returns></returns>
        public string MakeBarData(string sPosNo, string sSaleDate, string sTradeNo)
        {
            string sBarData = "";
     
            if (m_cTrnStatus.Head.CmpCd == "PCKR")
            {
                sBarData = "4";
            }
            else if (m_cTrnStatus.Head.CmpCd == "BRKR")
            {
                sBarData = "5";
            }
            else if (m_cTrnStatus.Head.CmpCd == "SLKR")
            {
                sBarData = "6";
            }

            int iStorCdLen = m_cTrnStatus.Head.StoreCd.Length;

            sBarData += sTradeNo.Substring(4, 1);                                               //빌5
            sBarData += sPosNo.Substring(0, 1);                                                 //P1
            sBarData += sSaleDate.Substring(0, 1);                                              //년1
            sBarData += sTradeNo.Substring(3, 1);                                               //빌4
            sBarData += sSaleDate.Substring(1, 1);                                              //년2
            sBarData += sPosNo.Substring(1, 1);                                                 //P2
            sBarData += sSaleDate.Substring(2, 1);                                              //년3
            sBarData += m_cTrnStatus.Head.StoreCd.ToString().Substring(iStorCdLen - 5, 1);      //점3
            sBarData += sSaleDate.Substring(3, 1);                                              //년4
            sBarData += m_cTrnStatus.Head.StoreCd.ToString().Substring(iStorCdLen - 4, 1);      //점4
            sBarData += sSaleDate.Substring(4, 1);                                              //월1
            sBarData += sTradeNo.Substring(2, 1);                                               //빌3
            sBarData += sSaleDate.Substring(5, 1);                                              //월2
            sBarData += m_cTrnStatus.Head.StoreCd.ToString().Substring(iStorCdLen - 3, 1);      //점5
            sBarData += sSaleDate.Substring(6, 1);                                              //일1
            sBarData += sTradeNo.Substring(1, 1);                                               //빌2
            sBarData += sSaleDate.Substring(7, 1);                                              //일2
            sBarData += m_cTrnStatus.Head.StoreCd.ToString().Substring(iStorCdLen - 2, 1);      //점6
            sBarData += m_cTrnStatus.Head.StoreCd.ToString().Substring(iStorCdLen - 1, 1);      //점7

            return sBarData;
        }
    }
}