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 OnLineCouponBase : PaymentBase
    {
        /// <summary>
        /// 온라인쿠폰 승인 및 발행 전송 전문 생성
        /// </summary>
        public string MakeOnLineCouponSendData(string sTradeDiv, string sTranKind, string sInPutType, string sInPutData, double nTotSaleAmt, int nPluCount, double nNetSaleAmt, string sPluInfo, string sApprDate, string sApprNo)
        {
            string sSendData = "";
            try
            {
                string[] aIrtReq = new string[Column.POS_REQ_ONLINE_COUPON.LEN.Length];
                aIrtReq[Column.POS_REQ_ONLINE_COUPON.SEQ.STX] = PosConst.VAN_HEXA.STX;
                aIrtReq[Column.POS_REQ_ONLINE_COUPON.SEQ.MsgLen] = (ItemColumn.LenMessage(Column.POS_REQ_ONLINE_COUPON.LEN) + CmUtil.LenH(sPluInfo) - 1).ToString();
                aIrtReq[Column.POS_REQ_ONLINE_COUPON.SEQ.BusiDiv] = "001";         // 업무구분	임직원 인증처리	3	N	001

                if (sTradeDiv == PosConst.CANCEL_DIV.NORMAL)
                    aIrtReq[Column.POS_REQ_ONLINE_COUPON.SEQ.TranType] = "0200";   // 전문구분	승인/반품구분	4	N	0100: 조회, 0200: 정상, 0420: 반품
                else if (sTradeDiv == PosConst.CANCEL_DIV.CANCEL)
                    aIrtReq[Column.POS_REQ_ONLINE_COUPON.SEQ.TranType] = "0420";   // 전문구분	승인/반품구분	4	N	0100: 조회, 0200: 정상, 0420: 반품
                else
                    aIrtReq[Column.POS_REQ_ONLINE_COUPON.SEQ.TranType] = "0100";   // 전문구분	승인/반품구분	4	N	0100: 조회, 0200: 정상, 0420: 반품

                aIrtReq[Column.POS_REQ_ONLINE_COUPON.SEQ.TranKind] = sTranKind;    // 거래구분	요청구분	2	N	10 : 발행, 20 : 승인

                aIrtReq[Column.POS_REQ_ONLINE_COUPON.SEQ.SysDT] = DateTime.Now.ToString("yyyyMMddHHmmss");
                aIrtReq[Column.POS_REQ_ONLINE_COUPON.SEQ.BrandCode] = m_cPosStatus.Base.BrandCd;        // "5000"
                aIrtReq[Column.POS_REQ_ONLINE_COUPON.SEQ.StoreCode] = m_cPosStatus.Base.StoreNo;        // "09996"
                aIrtReq[Column.POS_REQ_ONLINE_COUPON.SEQ.SaleDate] = m_cPosStatus.Base.SaleDate;
                aIrtReq[Column.POS_REQ_ONLINE_COUPON.SEQ.PosNo] = m_cPosStatus.Base.PosNo;
                aIrtReq[Column.POS_REQ_ONLINE_COUPON.SEQ.TradeNo] = m_cPosStatus.Base.TradeNo;

                aIrtReq[Column.POS_REQ_ONLINE_COUPON.SEQ.WCC] = sInPutType;        // WCC	WCC(리딩구분자)	1	N	A: Barcode, K: Keyin 
                aIrtReq[Column.POS_REQ_ONLINE_COUPON.SEQ.COUPON_NO] = sInPutData;
                aIrtReq[Column.POS_REQ_ONLINE_COUPON.SEQ.OrgApprDT] = sApprDate;
                aIrtReq[Column.POS_REQ_ONLINE_COUPON.SEQ.OrgApprNo] = sApprNo;

                aIrtReq[Column.POS_REQ_ONLINE_COUPON.SEQ.TotSaleAmt] = CmUtil.LPadH(nTotSaleAmt.ToString(), 9);
                aIrtReq[Column.POS_REQ_ONLINE_COUPON.SEQ.PluCount] = CmUtil.LPadH(nPluCount.ToString(), 3);
                aIrtReq[Column.POS_REQ_ONLINE_COUPON.SEQ.NetSaleAmt] = CmUtil.LPadH(nNetSaleAmt.ToString(), 9);

                // 전송 데이터 생성
                sSendData = ItemColumn.MakeMessage(aIrtReq, Column.POS_REQ_ONLINE_COUPON.LEN, Column.POS_REQ_ONLINE_COUPON.TYPE);
                sSendData += sPluInfo;                  // 구매상품	상품코드	10	AN	 + 구매수량	구매수량	3	N + 구매단가	구매단가	6	N ==> 반복
                sSendData += PosConst.VAN_HEXA.ETX;
            }
            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 sSendData;
        }

        /// <summary>
        /// 온라인 쿠폰 대상상품 정보 획득
        /// </summary>
        /// <param name="nPluTotCnt"></param>
        /// <param name="nPluTotAmt"></param>
        /// <returns></returns>
        public string GetSalePluInfo(ref int nPluTotCnt, ref double nPluTotAmt)
        {
            string sPluSaleInfo = "";      // 대상 상품정보[상품코드(10) + 수량(3) + 단가(6)]
            try
            {
                nPluTotCnt = 0;     // 대상 상품 건수
                nPluTotAmt = 0;     // 대상 상품 금액
                
                ArrayList alSalePluInfo = new ArrayList();  // 대상 상품정보

                ArrayList alTrPluItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);                   // 상품 아이템
                foreach (Column.TR_PLU.DATA cPluItem in alTrPluItem)
                {
                    // 대상상품 할인 가능여부 체크
                    if (m_cDataService.CheckPluDiscountAble(PosKey.MENU_KEY.ONLINE_COUPONS, cPluItem) == false) continue;

                    nPluTotCnt++;
                    nPluTotAmt = CmUtil.DoubleAdd(nPluTotAmt, cPluItem.BILL_AMT);

                    bool bExist = false;
                    for (int i = 0; i < alSalePluInfo.Count; i++)
                    {
                        string sInfo = (string)alSalePluInfo[i];
                        if (sInfo.StartsWith(cPluItem.ITEM_PLU_CD.Trim()) == true)
                        {
                            long nQty = CmUtil.LongParse(sInfo.Substring(10, 3)) + cPluItem.SALE_QTY;
                            if (nQty > 999) nQty = 999;
                            alSalePluInfo[i] = CmUtil.RPadH(cPluItem.ITEM_PLU_CD, 10) + CmUtil.LPadH(nQty.ToString(), 3) + CmUtil.LPadH(((long)cPluItem.SALE_PRC).ToString(), 6); //string.Format("{0:D3}{1:D6}", nQty, (long)cPluItem.SALE_PRC);
                            bExist = true;
                            break;
                        }
                    }

                    if (bExist == false)
                    {
                        long nQty = (cPluItem.SALE_QTY > 999) ? 999 : cPluItem.SALE_QTY;
                        // 상품정보 = 제품코드(10)+수량(3)+단가(6)
                        string sNewInfo = CmUtil.RPadH(cPluItem.ITEM_PLU_CD, 10) + CmUtil.LPadH(nQty.ToString(), 3) + CmUtil.LPadH(((long)cPluItem.SALE_PRC).ToString(), 6); //string.Format("{0:D3}{1:D6}", nQty, (long)cPluItem.SALE_PRC);

                        alSalePluInfo.Add(sNewInfo);
                    }
                }

                // 상품정보 생성
                foreach (string sPluInfo in alSalePluInfo)
                {
                    sPluSaleInfo += sPluInfo;
                }
            }
            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 sPluSaleInfo;
        }

        /// <summary>
        /// 쿠폰 종류 명칭 획득
        /// </summary>
        /// <param name="sCouponCode"></param>
        /// <returns></returns>
        public string GetCouponKindName(string sCouponCode)
        {
            string sCouponName = "";
            try
            {
                //1	쿠폰구분코드 5	년(2자리)+순번(3자리)
                //2	체크썸	2	시퀀스 끝자리가 홀수이면 체크썸을 제외한 쿠폰번호 홀수자리 합,시퀀스 끝자리가 짝수이면 체크썸을 제외한 쿠폰번호 짝수자리 합
                //3	쿠폰형태	1	1:쿠폰, 2:영수증
                //4	쿠폰종류	1	1:교환권, 2:증정권, 3:금액권, 4:할인권, 5:상품지정할인권
                //5	시퀀스	7	9,999,999
                string sCouponKind = CmUtil.MidH(sCouponCode, 8, 1);     // 쿠폰종류	1	1:교환권, 2:증정권, 3:금액권, 4:할인권, 5:상품지정할인권

                if (sCouponKind == PosConst.ONLINE_CPN_KIND.CHANGE)
                {
                    sCouponName = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0960);
                }
                else if (sCouponKind == PosConst.ONLINE_CPN_KIND.PRESENT)
                {
                    sCouponName = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0961);
                }
                else if (sCouponKind == PosConst.ONLINE_CPN_KIND.AMTPAY)
                {
                    sCouponName = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0962);
                }
                else if (sCouponKind == PosConst.ONLINE_CPN_KIND.DISCOUNT)
                {
                    sCouponName = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0963);
                }
                else if (sCouponKind == PosConst.ONLINE_CPN_KIND.PLUDIS)
                {
                    sCouponName = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0964);
                }
            }
            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 sCouponName;
        }

        /// <summary>
        /// 점포 명칭 획득
        /// </summary>
        /// <param name="sStoreCode"></param>
        /// <returns></returns>
        public string GetStoreName(string sStoreCode)
        {
            string sQuery = "", sStroeName = "";
            try
            {
                sQuery = "SELECT * FROM POSMST..MST_STOR WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' AND STOR_CD = '" + sStoreCode + "'";
                sQuery += "AND USE_YN  = '" + PosConst.MST_USE_YN.YES + "'";

                IMasterUs cMstService = (IMasterUs)sManager.InitServiceInstance(ServiceLists.ASV_MASTER.DLL, ServiceLists.ASV_MASTER.POS_MASTER);
                DataTable dtDataInfo = cMstService.Select(new string[] { sQuery });

                if (dtDataInfo != null && dtDataInfo.Rows.Count > 0)
                {
                    DataRow dr = dtDataInfo.Rows[0];

                    sStroeName = CmUtil.GetDataRowStr(dr, PosMst.MST_STORE.DATA.STOR_OWN_NM);
                }
            }
            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 sStroeName;
        }
    }
}
