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 HappyBuzz : IHappyBuzz
    {
        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 static ArrayList m_sPrintData = new ArrayList();

        private string m_HAPPYBUZZ_URL = "";

        /// <summary>
        /// 생성자
        /// </summary>
        public HappyBuzz()
        {
            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);
            //GetHappyBuzzUrl();

        }

        /// <summary>
        /// URL 가져오기
        /// </summary>
        /// <returns></returns>
        private bool GetHappyBuzzUrl()
        {
            bool bRet = false;

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


                if (string.IsNullOrEmpty(stmp) == false)
                {
                    m_HAPPYBUZZ_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>
        /// <param name="aParam"></param>
        /// <param name="aOutParam"></param>
        /// <returns></returns>
        public int SetHappyBuzz(string[] aParam, ref string[] aOutParam)
        {

            int iRet = BaseCom.NG;
            string sCardNo = "";
            try
            {
                if (m_HAPPYBUZZ_URL == "")
                {
                    if (GetHappyBuzzUrl() == false)
                    {
                        return BaseCom.NG1;
                    }
                }
                
                //[0] : 카드번호
                sCardNo = aParam[0].ToString();
                
                // 상품정보
                ArrayList aSaleItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);

                //아이템 리스트 담기
                Hashtable[] htDatail = new Hashtable[aSaleItem.Count > 5 ? 5 : 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("name", cSaleItem.ITEM_NAME);
                    htDatail[iRow].Add("price", (int)cSaleItem.SALE_AMT);
                    htDatail[iRow].Add("count", (int)cSaleItem.SALE_QTY);

                    if (iRow >= 4) break;
                }
                
                //헤더 담기                
                Hashtable htRequest = new Hashtable();
                htRequest.Add("storeCd", m_cPosStatus.Base.StoreNo);      //유니크한 점포코드
                //htRequest.Add("storeCd", "99931");                          //테스트용
                htRequest.Add("subCd", 0);
                htRequest.Add("orderCnt", aSaleItem.Count > 5 ? 5 : aSaleItem.Count);                          
                htRequest.Add("cardNo", sCardNo);                           //적립사용카드번호
                htRequest.Add("orderList", htDatail);                       //적립사용카드번호
                htRequest.Add("totalAmount", (int)m_cTrnStatus.Head.TotSaleAmt); //결제금액
                htRequest.Add("expectTime", 600);                         //초단위 예상대기시간(10분고정)
                
                Hashtable htResponse = null;
                int iReturn = SendReceiveForHttps(new object[] { m_HAPPYBUZZ_URL, PosConst.HAPPYBUZZ_SUB_URL.SET, htRequest }, ref htResponse);

                if (iReturn == BaseCom.OK)
                {
                    aOutParam[0] = htResponse["result"].ToString().Trim();
                    aOutParam[1] = htResponse["msg"] == null ? "" : htResponse["msg"].ToString();
                    aOutParam[2] = htResponse["pagerNo"].ToString();
                    iRet = BaseCom.OK;
                }
            }
            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 iRet;
        }

        /// <summary>
        /// 해피버즈 취소
        /// </summary>
        /// <param name="aParam"></param>
        /// <param name="aOutParam"></param>
        /// <returns></returns>
        public int CanHappyBuzz(string[] aParam, ref string[] aOutParam)
        {

            int iRet = BaseCom.NG;

            try
            {

                if (m_HAPPYBUZZ_URL == "")
                {
                    if (GetHappyBuzzUrl() == false)
                    {
                        return BaseCom.NG1;
                    }
                }

                //[0] : 카드번호

                //헤더 담기                
                Hashtable htRequest = new Hashtable();
                htRequest.Add("storeCd", m_cPosStatus.Base.StoreNo);      //유니크한 점포코드
                //htRequest.Add("storeCd", "99931");                          //테스트용
                htRequest.Add("subCd", 0);
                htRequest.Add("pagerNo", aParam[0].ToString());
                                
                Hashtable htResponse = null;
                int iReturn = SendReceiveForHttps(new object[] { m_HAPPYBUZZ_URL, PosConst.HAPPYBUZZ_SUB_URL.CAN, htRequest }, ref htResponse);

                if (iReturn == BaseCom.OK)
                {
                    aOutParam[0] = htResponse["result"].ToString().Trim();
                    aOutParam[1] = htResponse["msg"] == null ? "" : htResponse["msg"].ToString();

                    iRet = BaseCom.OK;
                }
            }
            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 iRet;
        }


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

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

                htResponse = null;
                string sResp = string.Empty;

                iRet = m_cNetworkHttp.HttpJsonPOST_SendReceiveForBuzz(sUrl, sWorkType, 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);
            }

            return iRet;
        }

    }
}
