using System;
using System.Data;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

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

namespace Cosmos.Service
{
    class HoldDeal :SaleTranCallBase, IHoldDeal
    {           
        private ISaleCompleteUs m_cSaleComplete = null;                                 // 거래 완료처리

        public HoldDeal()
        {
            m_cSaleComplete = (ISaleCompleteUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.SALE_COMPLETE);
        }

        /// <summary>
        /// 보류 거래 조회
        /// </summary>
        /// <param name="sSaleDate"></param>
        /// <returns></returns>
        public DataTable SearchHoldDealList(string sSaleDate)
        {
            string sQuery = "";

            int iMaxCnt = 100;
            string sTimeCheck = "";

            try
            {


                iMaxCnt = CmUtil.IntParse(PosMstManager.GetPosOption(POS_OPTION.OPT017));


                if (iMaxCnt == 0)
                {
                    sQuery = " SELECT ROW_NUMBER() OVER( ORDER BY HDR.REG_NO ASC) AS NO ";
                }
                else
                {
                    sQuery = " SELECT TOP " + iMaxCnt + " ROW_NUMBER() OVER( ORDER BY HDR.REG_NO ASC) AS NO ";
                }

                sQuery += "       ,(HDR.SYS_DT + HDR.PAY_TIME)SYS_DT ";
                //sQuery += "       ,(CASE WHEN CNT > 1 THEN ITEM_NM +' " + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0171) + " '+ CONVERT(VARCHAR(100),CNT - 1) + '" + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0938) + "'  ELSE ITM.ITEM_NM END)ITEM_NM ";
                sQuery += "       ,(CASE WHEN CNT > 1 THEN ITEM_NM +' " + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0171) + " '";
                sQuery += "       +CONVERT(VARCHAR(100),CNT - 1) + '" + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0938) + "'  ELSE ITM.ITEM_NM END)ITEM_NM ";
                sQuery += "       ,CONVERT(VARCHAR,HDR.NET_SALE_AMT)NET_SALE_AMT ";
                sQuery += "       ,CONVERT(VARCHAR,ITM.SALE_QTY)SALE_QTY ";
                sQuery += "       ,HDR.SALE_DT, HDR.POS_NO, HDR.REG_NO ";
                sQuery += "   FROM POSLOG.dbo.ETC_SALE_HEADER HDR ";
                sQuery += "    INNER JOIN  (";
                sQuery += "     SELECT DTL.CMP_CD , DTL.SALE_DT , DTL.STOR_CD , DTL.POS_NO , DTL.REG_NO ";
                sQuery += "          , MAX(MST.SHTCUT_ITEMNM)ITEM_NM , COUNT(DTL.CMP_CD)CNT , SUM(DTL.SALE_QTY)SALE_QTY";
                sQuery += "       FROM POSLOG..ETC_SALE_DETAIL DTL ";
                sQuery += "      INNER JOIN POSMST..MST_ITEM MST ";
                sQuery += "            ON DTL.CMP_CD = MST.CMP_CD ";
                sQuery += "           AND DTL.STOR_CD = MST.STOR_CD ";
                sQuery += "           AND DTL.SUB_SHOP_CD = MST.SUB_STOR_CD ";
                sQuery += "           AND DTL.ITEM_PLU_CD = MST.ITEM_CD ";
                sQuery += "       GROUP BY DTL.CMP_CD, DTL.SALE_DT, DTL.STOR_CD, DTL.POS_NO, DTL.REG_NO ";
                sQuery += "      ) ITM ";
                sQuery += "   ON HDR.CMP_CD  = ITM.CMP_CD ";
                sQuery += "  AND HDR.SALE_DT = ITM.SALE_DT ";
                sQuery += "  AND HDR.STOR_CD = ITM.STOR_CD ";
                sQuery += "  AND HDR.POS_NO  = ITM.POS_NO ";
                sQuery += "  AND HDR.REG_NO  = ITM.REG_NO ";
                sQuery += "  WHERE HDR.CMP_CD  = '" + m_cPosStatus.Base.CmpCd + "'";
                sQuery += "    AND HDR.SALE_DT = '" + sSaleDate + "'";
                sQuery += "    AND HDR.STOR_CD = '" + m_cPosStatus.Base.StoreNo + "'";
                sQuery += "    AND HDR.TRADE_DIV = '" + ItemConst.TRAN_DIV.NORMAL + "'";
                sQuery += "    AND HDR.TRADE_KINDPER = '" + ItemConst.TRAN_KIND.LOG.HOLD_DEAL + "'";
                sQuery += "    AND HDR.TRADE_STAT = '0'";
                sQuery += "    AND HDR.TRAIN_MODE_YN = '" + m_cPosStatus.Base.TrainingFlag + "'  ";


                sTimeCheck = PosMstManager.GetPosOption(POS_OPTION.OPT018).ToString().Trim();


                //경과 시간 구하기
                if (sTimeCheck != "" && sTimeCheck != "0")
                {
                    sQuery += "    AND HDR.REG_DATE < '" + DateTime.Now.AddHours(CmUtil.IntParse(PosMstManager.GetPosOption(POS_OPTION.OPT018))).ToString("yyyyMMddHHmmss") + "'";

                }

                sQuery += " ORDER BY HDR.CMP_CD, HDR.SALE_DT, HDR.STOR_CD, HDR.POS_NO, HDR.REG_NO DESC";

                return m_cMstService.Select(new string[] { sQuery });
            }
            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 null;
        }

        /// <summary>
        /// 보류 거래 영수증 조회
        /// </summary>
        /// <param name="sSaleDate"></param>
        /// <param name="sPosNo"></param>
        /// <param name="sRegNo"></param>
        /// <returns></returns>
        public DataTable SearchHoldDealPrint(string sSaleDate, string sPosNo, string sRegNo)
        {
            string sQuery = "";
            try
            {
                sQuery = " SELECT JOURNAL_DATA ";
                sQuery += "   FROM POSLOG.dbo.ETC_SALE_JOURNAL ";
                sQuery += "  WHERE CMP_CD  = '" + m_cPosStatus.Base.CmpCd + "'";
                sQuery += "    AND SALE_DT = '" + sSaleDate + "'";
                sQuery += "    AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "'";
                sQuery += "    AND POS_NO = '" + sPosNo + "'";
                sQuery += "    AND REG_NO = '" + sRegNo + "'";


                return m_cMstService.Select(new string[] { sQuery });
            }
            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 null;
        }



        /// <summary>
        /// 보류 거래 상태 변경(삭제, 불러오기)
        /// </summary>
        /// <param name="sSaleDate"></param>
        /// <param name="sPosNo"></param>
        /// <param name="sRegNo"></param>
        /// <param name="sStats"></param>
        /// <returns></returns>
        public int UpdateHoldDeal(string sSaleDate, string sPosNo, string sRegNo, string sStats, double dQty, double dSaleAmt)
        {
            string sQuery = "";
            try
            {

                if (sStats == "2" && dSaleAmt > 0)
                {
                    //로그 저장!
                    m_cSaleComplete.EtcHoldLogSvae(ItemConst.HOLD_STAT_CD.DELETE, sRegNo, dQty, dSaleAmt);
                }

                sQuery = "  UPDATE ";
                sQuery += "   POSLOG..ETC_SALE_HEADER ";
                sQuery += "    SET TRADE_STAT ='" + sStats + "'";
                sQuery += "  WHERE CMP_CD  = '" + m_cPosStatus.Base.CmpCd + "'";
                sQuery += "    AND SALE_DT = '" + sSaleDate + "'";
                sQuery += "    AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "'";
                sQuery += "    AND POS_NO  ='" + sPosNo + "'";
                sQuery += "    AND REG_NO  ='" + sRegNo + "'";
                sQuery += "    AND TRAIN_MODE_YN = '" + m_cPosStatus.Base.TrainingFlag + "'  ";


                return m_cMstService.Update(new string[] { sQuery });
            }
            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 -1;
        }

        /// <summary>
        /// 보류 영수증 출력
        /// </summary>
        /// <param name="sPrtData"></param>
        /// <returns></returns>
        public bool PrintHoldDeal(string sPrtData)
        {
            //// 영수증 출력
            return m_cSaleComplete.PosSaleRePrint(sPrtData);
        }

        /// <summary>
        /// 상품불러오기를 위한 거래 데이터 상품 정보 만 로딩
        /// </summary>
        /// <param name="sSaleDate"></param>
        /// <param name="sPosNo"></param>
        /// <param name="sTradeNo"></param>
        /// <returns></returns>
        public bool LoadLocalTranPlu(string sSaleDate, string sPosNo, string sTradeNo)
        {
            bool bRet = false;

            try
            {
                ArrayList alTrPluItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);

                if (alTrPluItem.Count > 0) // 거래호출시 데이터 있음(다시로딩 안함)
                {
                    // 상품정보를 제외한 모든 정보 클리어
                    m_cDataService.InitTranHeader();

                    ArrayList alPayItem = (ArrayList)StateObject.GetItemObject(Column.TR_PAYMENT.ITEM);
                    alPayItem.Clear();
                    ArrayList alEtcItem = (ArrayList)StateObject.GetItemObject(Column.TR_ETC.ITEM);
                    alPayItem.Clear();
                    ArrayList alTrCpiItem = (ArrayList)StateObject.GetItemObject(Column.TR_SALE_CPI_RSLT.ITEM);
                    alTrCpiItem.Clear();
                    ArrayList alTrGuest = (ArrayList)StateObject.GetItemObject(Column.TR_GUEST.ITEM);
                    alTrGuest.Clear();

                    return true;
                }

                m_cDataService.TranComplete();
                

                // 상품정보 로딩
                if (LoadLocalTrDetail(sSaleDate, sPosNo, sTradeNo, true) == false)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0248);
                    m_cDataService.TranComplete();
                    return bRet;
                }

                m_cTrnStatus.Head.FloorCd = m_cPosStatus.Sale.SelectFloorCd;
                m_cTrnStatus.Head.FloorNm = m_cPosStatus.Sale.SelectFloorNm;
                m_cTrnStatus.Head.TableNo = m_cPosStatus.Sale.SelectTableNo;
                m_cTrnStatus.Head.TableNm = m_cPosStatus.Sale.SelectTableNm;

                bRet = 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);
                m_cDataService.TranComplete();
            }
            return bRet;
        }

        
        //17.05.18 dkshin 쇼킹박스 추가
        /// <summary>
        /// 쇼킹박스 거래 조회
        /// </summary>
        /// <param name="sSaleDate"></param>
        /// <returns></returns>
        //#15746 해피오더 '쇼킹박스' 관련 POS 시스템 개발 요청 start
        //기존
        //public DataTable SearchShockingBoxDealList(string sInputData)
        //변경
        public DataTable SearchShockingBoxDealList(string sInputData, string sTradeKind, string sTradeStat)
        //#15746 해피오더 '쇼킹박스' 관련 POS 시스템 개발 요청 end
        {
            string sQuery = "";

            try
            {
                //#15746 해피오더 '쇼킹박스' 관련 POS 시스템 개발 요청 start
                //기존
                //sQuery += "SELECT SALE_DT, POS_NO, REG_NO FROM POSLOG.dbo.ETC_SALE_HEADER ";
                //변경
                sQuery += "SELECT SALE_DT, POS_NO, REG_NO,TRADE_STAT, ORG_BILL_POSNO,ORG_BILLDT,ORG_BILL_NO FROM POSLOG.dbo.ETC_SALE_HEADER ";
                //#15746 해피오더 '쇼킹박스' 관련 POS 시스템 개발 요청 end
                sQuery += "  WHERE CMP_CD  = '" + m_cPosStatus.Base.CmpCd + "'";
                sQuery += "    AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "'";
                sQuery += "    AND SALE_DT + REG_NO = '" + sInputData + "'";
                sQuery += "    AND TRADE_DIV = '" + ItemConst.TRAN_DIV.NORMAL + "'"; 
                //#15746 해피오더 '쇼킹박스' 관련 POS 시스템 개발 요청 start
                //기존
                //sQuery += "    AND TRADE_KINDPER = '" + ItemConst.TRAN_KIND.LOG.SHOCKING_BOX + "'";
                //sQuery += "    AND TRADE_STAT = '0'";

                //변경
                sQuery += "    AND TRADE_KINDPER = '" + sTradeKind + "'";

                if (sTradeStat != "1")
                {
                    sQuery += "    AND TRADE_STAT = '0'";
                }
                //#15746 해피오더 '쇼킹박스' 관련 POS 시스템 개발 요청 end
                sQuery += "    AND TRAIN_MODE_YN = '" + m_cPosStatus.Base.TrainingFlag + "'  ";

                return m_cMstService.Select(new string[] { sQuery });
            }
            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 null;
        }

        //17.05.18 dkshin 쇼킹박스 추가
        /// <summary>
        /// 쇼킹박스 거래 상태 변경
        /// </summary>
        /// <returns></returns>
        public int UpdateShockingBOX()
        {
            var sSQL = string.Empty;
            string sQuery = "";

            try
            {
                sQuery = "UPDATE POSLOG..ETC_SALE_HEADER ";
                sQuery += "SET TRADE_STAT = '0' ";
                sQuery += "WHERE CMP_CD = '{0}' AND STOR_CD = '{1}' AND POS_NO = '{2}' AND SALE_DT + REG_NO = '{3}'";

                sSQL = string.Format(sQuery, m_cTrnStatus.Head.CmpCd, m_cTrnStatus.Head.StoreCd, m_cTrnStatus.Head.PosNo, m_cTrnStatus.Head.ShockingBoxBarcodeData);

                return m_cMstService.Update(new string[] { sSQL });
            }
            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 -1;
        }

        //17.05.18 dkshin 쇼킹박스 추가
        /// <summary>
        /// 쇼킹박스 거래 조회
        /// </summary>
        /// <param name="sSaleDate"></param>
        /// <returns></returns>
        public DataTable SearchShockingBoxPayCompleteList(string sSaleDate, string sTradeNo)
        {
            string sQuery = "";

            try
            {
                sQuery += "SELECT SALE_DT, POS_NO, REG_NO FROM POSLOG.dbo.ETC_SALE_HEADER ";
                sQuery += "  WHERE CMP_CD  = '" + m_cPosStatus.Base.CmpCd + "'";
                sQuery += "    AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "'";
                sQuery += "    AND SALE_DT = '" + sSaleDate + "'";
                sQuery += "    AND ORG_BILL_NO = '" + sTradeNo + "'";
                sQuery += "    AND TRADE_KINDPER = '" + ItemConst.TRAN_KIND.LOG.SHOCKING_BOX + "'";
                sQuery += "    AND TRADE_STAT = '1' ";
                
                return m_cMstService.Select(new string[] { sQuery });
            }
            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 null;
        }

        //17.05.18 dkshin 쇼킹박스 추가
        /// <summary>
        /// 쇼킹박스 거래 상태 변경
        /// </summary>
        /// <returns></returns>
        public int UpdateShockingBOXPayComplete(string sSaleDate, string sPosNo, string sTradeNo)
        {
            var sSQL = string.Empty;
            string sQuery = "";

            try
            {
                sQuery = "UPDATE POSLOG..ETC_SALE_HEADER ";
                sQuery += " SET TRADE_STAT = '0', ORG_BILL_POSNO = '', ORG_BILLDT = '', ORG_BILL_NO = '' ";
                sQuery += "  WHERE CMP_CD = '{0}' AND STOR_CD = '{1}' AND POS_NO = '{2}' AND SALE_DT + REG_NO = '{3}' ";
                sQuery += "    AND TRADE_KINDPER = '" + ItemConst.TRAN_KIND.LOG.SHOCKING_BOX + "'";
                sQuery += "    AND TRADE_STAT = '1'";

                sSQL = string.Format(sQuery, m_cPosStatus.Base.CmpCd, m_cPosStatus.Base.StoreNo, sPosNo, sSaleDate+sTradeNo);

                return m_cMstService.Update(new string[] { sSQL });
            }
            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 -1;
        }
    }
}
