using System;
using System.Collections;
//using System.Windows.Forms;

using Cosmos.UserFrame;
using Cosmos.ServiceProvider;
using Cosmos.Common;
using Cosmos.CommonManager;
using System.Text;
using System.Data;
using Cosmos.BaseFrame;
/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 삼성패밀리카드 할인(SFC)
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Service
{
    class SamsungFamilyCard : PaymentBase, IPaymentUs
    {
        #region Variable

        //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 IICReaderUs m_cICReader = null;                                     // IC리더기
        //private ISignPadUs m_cSignPad = null;                                       // 싸인패드
        //private IDataProcessUs m_cDataService = null;                               // 거래데이터 합계금액 계산 및 관리
        //private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스

        //private IMasterUs m_cMater = null;                                          // 마스터 Database

        private ISalePluItemUs m_cPluService = null;
        //private DeviceStatus m_cDevStatus = new DeviceStatus();                     // 디바이스 관리

        //private readonly string GIFT_REMAIN_TAG = "잔액 :";                          //선불카드 잔액 태그
        //private readonly string GIFT_WON_TAG = "원";                                 //선불카드 잔액 태그


        #endregion

        #region 생성자
        public SamsungFamilyCard()
        {
            //m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
            //m_cTrnStatus = (TranStatus)StateObject.TRAN;    // POS 거래정보
            //m_cDataService = (IDataProcessUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_SERVICE);
            //m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
            //m_cICReader = (IICReaderUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_ICREADER);
            //m_cMater = (IMasterUs)sManager.InitServiceInstance(ServiceLists.ASV_MASTER.DLL, ServiceLists.ASV_MASTER.PAY_DC_MASTER);
            m_cPluService = (ISalePluItemUs)sManager.InitServiceInstance(ServiceLists.BSV_SALE.DLL, ServiceLists.BSV_SALE.SALE_PLU_ITEM);
            //m_cSignPad = (ISignPadUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_SIGNPAD);

            //m_cDevStatus = (DeviceStatus)StateObject.DEVICE;

        }
        #endregion

        #region 조회 관련 업무
        public string SearchPayment(string[] aParam, ref string[] aRet)
        {

            string sRet = UserCom.RST_ERR;

            try
            {
                return sRet;

            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.ERROR, UserCom.ERROR_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
                return UserCom.RST_ERR + ex.Message;

            }
            finally
            {
                //여전법 대응!
                //////////////////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref aParam);
                //////////////////////////////////////////////////////////////////////////////////
            }
        }
        #endregion 조회 관련 업무

        #region 결제 정보 획득
        /// <summary>
        /// 결제 정보 획득
        /// </summary>
        /// <param name="aParam"></param>
        /// <returns></returns>
        public object GetPayment(string[] aParam)
        {
            try
            {
                return null;
            }
            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;
        }
        #endregion

        #region 결제 등록 처리
        /// <summary>
        /// 카드 결제 등록 처리
        /// </summary>
        /// <param name="aParam"></param>
        /// <returns></returns>
        public string SetPayment(string[] aParam)
        {
            string sRet = UserCom.RST_ERR;
            bool bRet = false;

            try
            {
                // aParam : 0:카드번호, 1:할인금액

                //할인 결과 저장
                ArrayList aPayItem = (ArrayList)StateObject.GetItemObject(Column.TR_PAYMENT.ITEM);
                Column.TR_PAYMENT.DATA m_cPayItem = new Column.TR_PAYMENT.DATA();

                m_cPayItem.PAY_WAY_CD = ItemConst.TR_ITEM_ID.EMP_DC_ITEM;
                m_cPayItem.PAY_AMT = CmUtil.DoubleParse(aParam[1]);

                m_cPayItem.BILLSPR_NO = m_cTrnStatus.Sale.BillSplitNo;                                                  // 빌분리 번호

                m_cPayItem.PAY_DTL_CD_01 = ItemConst.TR_ITEM_ID.EMP_DC.SAMSUNGCARD;
                m_cPayItem.PAY_DTL_CD_02 = ItemConst.CREDITCARD_DC_TY.CREDIT_SFC;


                m_cPayItem.PAY_DTL_CD_03 = "0";                                 // 할인금액아이템적용여부 (0:미적용, 1:적용)
                m_cPayItem.PAY_DTL_CD_05 = PosConst.PAY_DC_TYPE.PAY;            // 할인결제구분 (1:결제, 2:할인)
                if (PosMstManager.GetMstPayDc(m_cPayItem.PAY_WAY_CD, m_cPayItem.PAY_DTL_CD_01, PosMst.MST_PAY_DC.DATA.PAY_DC_TYPE) == PosConst.PAY_DC_TYPE.DC)
                {
                    m_cPayItem.PAY_DTL_CD_03 = "1";                             // 할인금액아이템적용여부 (0:미적용, 1:적용)
                    m_cPayItem.PAY_DTL_CD_05 = PosConst.PAY_DC_TYPE.DC;         // 할인결제구분 (1:결제, 2:할인)
                }

                m_cPayItem.PAY_DTL_CD_04 = "";

                m_cPayItem.QTY_ENTRY_01 = 0;
                m_cPayItem.QTY_ENTRY_02 = 0;
                m_cPayItem.QTY_ENTRY_03 = 0;
                m_cPayItem.QTY_ENTRY_04 = 0;
                m_cPayItem.QTY_ENTRY_05 = 0;

                m_cPayItem.AMT_ENTRY_01 = m_cPayItem.PAY_AMT;
                m_cPayItem.AMT_ENTRY_02 = 0;
                m_cPayItem.AMT_ENTRY_03 = 0;
                m_cPayItem.AMT_ENTRY_04 = 0;
                m_cPayItem.AMT_ENTRY_05 = 0;
                m_cPayItem.AMT_ENTRY_06 = 0;
                m_cPayItem.AMT_ENTRY_07 = 0;
                m_cPayItem.AMT_ENTRY_08 = 0;
                m_cPayItem.AMT_ENTRY_09 = 0;
                m_cPayItem.AMT_ENTRY_10 = 0;

                m_cPayItem.OCCUR_ENTRY_01 = aParam[0];   //카드번호
                m_cPayItem.OCCUR_ENTRY_02 = "";
                m_cPayItem.OCCUR_ENTRY_03 = DateTime.Now.ToString("yyMMdd");
                m_cPayItem.OCCUR_ENTRY_04 = DateTime.Now.ToString("HHmm");
                m_cPayItem.OCCUR_ENTRY_05 = "";
                m_cPayItem.OCCUR_ENTRY_06 = "";
                m_cPayItem.OCCUR_ENTRY_07 = "";
                m_cPayItem.OCCUR_ENTRY_08 = "";
                m_cPayItem.OCCUR_ENTRY_09 = "";
                m_cPayItem.OCCUR_ENTRY_10 = "";
                m_cPayItem.OCCUR_ENTRY_11 = "";
                m_cPayItem.OCCUR_ENTRY_12 = "";
                m_cPayItem.OCCUR_ENTRY_13 = "";
                m_cPayItem.OCCUR_ENTRY_14 = "";
                m_cPayItem.OCCUR_ENTRY_15 = "";
                m_cPayItem.OCCUR_ENTRY_16 = "";
                m_cPayItem.OCCUR_ENTRY_17 = "";
                m_cPayItem.OCCUR_ENTRY_18 = "";
                m_cPayItem.OCCUR_ENTRY_19 = "1";
                m_cPayItem.OCCUR_ENTRY_20 = GetPayDtlCdToPayDtlName(m_cPayItem.PAY_WAY_CD, m_cPayItem.PAY_DTL_CD_01);   // 결제수단명
                m_cPayItem.OCCUR_ENTRY_21 = GetPayDtlCdToCashBillYn(m_cPayItem.PAY_WAY_CD, m_cPayItem.PAY_DTL_CD_01);   // 현금영수증 발행여부
                m_cPayItem.OCCUR_ENTRY_22 = "";
                m_cPayItem.OCCUR_ENTRY_23 = "";
                m_cPayItem.OCCUR_ENTRY_24 = "";
                m_cPayItem.OCCUR_ENTRY_25 = "";

                m_cPayItem.CANCEL_DIV = ItemConst.PAY_CANCEL_DIV.NORMAL;

                //아이템 분배
                if (m_cPayItem.PAY_DTL_CD_03 == "1")
                    bRet = SetItemDcSeparate(m_cPayItem.PAY_AMT);
                else
                    bRet = true;

                if (bRet == true)
                {
                    aPayItem.Add(m_cPayItem);
                    m_cDataService.UpdatePayAmount();   // 결제 금액 재 계산 처리
                }
                    
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.ERROR, UserCom.ERROR_LEVEL, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
                return UserCom.RST_ERR + ex.Message;
            }
            finally
            {
                //여전법 대응!
                //////////////////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref aParam);
                //////////////////////////////////////////////////////////////////////////////////
            }

            return sRet;

        }
        #endregion

        #region 결제 취소 처리
        /// <summary>
        /// 카드 결제 취소 처리
        /// </summary>
        /// <param name="aParam"></param>
        /// <returns></returns>
        public string CancelPayment(string[] aParam)
        {
            string sRet = UserCom.RST_ERR;

            try
            {
                //결과 저장
                ArrayList aPayItem = (ArrayList)StateObject.GetItemObject(Column.TR_PAYMENT.ITEM);
                m_cPayItem = (Column.TR_PAYMENT.DATA)aPayItem[CmUtil.IntParse(aParam[0])];

                //SFC 할인 이면 할인 내역 취소!
                if (m_cPayItem.PAY_DTL_CD_03 == "1")
                {

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

                    for (int iCnt = 0; iCnt < aSaleItem.Count; iCnt++)
                    {
                        Column.TR_PLU.DATA cSaleItem = (Column.TR_PLU.DATA)aSaleItem[iCnt];

                        if (cSaleItem.CANCEL_DIV != PosConst.CANCEL_DIV.NORMAL) continue;       // 지정취소
                        if (cSaleItem.DC_DIV != ItemConst.PLU_DC_DIV.NORMAL) continue;          // 서비스(무료)
                        if (cSaleItem.ITEM_DIV != ItemConst.PLU_ITEM_DIV.NORMAL) continue;      // 서비스(무료)
                        if (cSaleItem.NONSALES_RSN_CD != "0") continue;                         // 비매출구분
                        if (cSaleItem.BILLSPR_NO != m_cTrnStatus.Sale.BillSplitNo) continue;    // 빌분리번호
                        if (cSaleItem.BILL_AMT <= 0) continue;                                  // 영수금액
                        if (cSaleItem.DC_PRMT_YN != "0") continue;                              // 할인가능 여부 


                        if (cSaleItem.EMP_DC_DIV == ItemConst.TR_ITEM_ID.EMP_DC_ITEM + ItemConst.TR_ITEM_ID.EMP_DC.SAMSUNGCARD)
                        {
                            cSaleItem.EMP_DC_AMT = 0;
                            cSaleItem.EMP_DC_DIV = "0000";
                        }

                        // 상품행별 영수 금액 재계산 처리
                        m_cDataService.UpdatePluItemAmount(cSaleItem);
                    }

                    m_cPluService.ItemAmountExeccute(true, true);
                }

                m_cPayItem.CANCEL_DIV = PosConst.CANCEL_DIV.CANCEL;

                m_cDataService.UpdatePluAmount();       // 상품 합계금액 계산(거래해더)
                // 결제 금액 재 계산 처리
                m_cDataService.UpdatePayAmount();

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

                sRet = UserCom.RST_ERR + ex.Message;
            }
            finally
            {
                //여전법 대응!
                //////////////////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref aParam);
                //////////////////////////////////////////////////////////////////////////////////
            }
            return sRet;
        }
        #endregion

        #region 오타/반품시 처리
        /// <summary>
        /// 오타/반품시 처리
        /// </summary>
        /// <param name="aParam"></param>
        /// <returns></returns>
        public string RefundPayment(string[] aParam)
        {
            string sRet = UserCom.RST_ERR;

            try
            {
                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);

                sRet = UserCom.RST_ERR + ex.Message;
            }
            finally
            {
                //여전법 대응!
                //////////////////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref aParam);
                //////////////////////////////////////////////////////////////////////////////////
            }
            return sRet;
        }
        #endregion 오타/반품시 처리

        #region 결제 수기 등록(임의등록)
        /// <summary>
        /// 결제 수기 등록(임의등록)
        /// </summary>
        /// <param name="aParam"></param>
        /// <returns></returns>
        public string SetMenualPayment(string[] aParam)
        {
            try
            {
                return UserCom.RST_ERR;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                   System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            finally
            {
                //여전법 대응!
                //////////////////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref aParam);
                //////////////////////////////////////////////////////////////////////////////////
            }
            return UserCom.RST_ERR;
        }
        #endregion 결제 수기 등록(임의등록)
        
        #region SetItemDcSeparate(SFC 할인 분배 처리)
        /// <summary>
        /// SFC 할인 분배 처리
        /// </summary>
        /// <param name="nAmt"></param>
        /// <returns></returns>
        private bool SetItemDcSeparate(double nAmt)
        {
            bool bRet = false;

            double nPrice = 0, nDCSum = 0, nRate = 0, nDCAmount = 0, nMaxPrice = 0;
            int iIndex = 0;

            try
            {
                nDCSum = 0;
                nRate = 0;
                nDCAmount = 0;
                nMaxPrice = 0;

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

                for (int iRow = 0; iRow < aSaleItem.Count; iRow++)
                {
                    Column.TR_PLU.DATA cSaleItem = (Column.TR_PLU.DATA)aSaleItem[iRow];

                    if (cSaleItem.CANCEL_DIV == PosConst.CANCEL_DIV.CANCEL || cSaleItem.CANCEL_DIV_MAIN == PosConst.CANCEL_DIV.CANCEL) continue; // 지정취소
                    if (cSaleItem.DC_DIV != ItemConst.PLU_DC_DIV.NORMAL) continue;          // 서비스(무료)
                    if (cSaleItem.ITEM_DIV != ItemConst.PLU_ITEM_DIV.NORMAL) continue;      // 서비스(무료)
                    if (cSaleItem.NONSALES_RSN_CD != "0") continue;                         // 비매출구분
                    if (cSaleItem.BILLSPR_NO != m_cTrnStatus.Sale.BillSplitNo) continue;    // 빌분리번호
                    if (cSaleItem.BILL_AMT <= 0) continue;                                  // 영수금액
                    if (cSaleItem.DC_PRMT_YN != "0") continue;                              // 할인가능 여부 

                    // 할인 절삭
                    nDCAmount = CmUtil.MathRounds(nAmt, m_cPosStatus.Mst.DcRudDwLocMethd, CmUtil.IntParse(m_cPosStatus.Mst.DcRudDwLoc));

                    // 비율 = 상품금액 / 총판매가 * 100 
                    nRate = CmUtil.DoubleMultiplication(CmUtil.DoubleDivision(cSaleItem.SALE_AMT, m_cTrnStatus.Head.TotSaleAmt), 100);

                    // 분배금액 = 상품금액 * 비율 / 100
                    nPrice = CmUtil.DoubleDivision(CmUtil.DoubleMultiplication(nDCAmount, nRate), 100);

                    // 금액 배분 절삭
                    nPrice = CmUtil.MathRounds(nPrice, m_cPosStatus.Mst.DcRudDwLocMethd, CmUtil.IntParse(m_cPosStatus.Mst.DcRudDwLoc));

                    if (nPrice > cSaleItem.SALE_AMT) continue;

                    // 할인 적용
                    cSaleItem.EMP_DC_AMT = nPrice;
                    cSaleItem.EMP_DC_DIV = ItemConst.TR_ITEM_ID.EMP_DC_ITEM + ItemConst.TR_ITEM_ID.EMP_DC.SAMSUNGCARD;

                    // 분배후 짜투리 금액 체크용
                    nDCSum = CmUtil.DoubleAdd(nDCSum, nPrice);

                    // 최종 적용 상품 index
                    if (nMaxPrice == 0 || nMaxPrice >= cSaleItem.SALE_AMT)
                    {
                        nMaxPrice = cSaleItem.SALE_AMT;
                        iIndex = iRow;
                    }

                    // 상품행별 영수 금액 재계산 처리
                    m_cDataService.UpdatePluItemAmount(cSaleItem);


                    if (nDCSum >= nAmt) break;

                }

                // 짜투리 금액 최종 적용 상품에 추가
                if (nDCSum != nAmt)
                {
                    Column.TR_PLU.DATA cSaleItem = (Column.TR_PLU.DATA)aSaleItem[iIndex];

                    nPrice = 0;
                    nPrice = CmUtil.DoubleSubtraction(nAmt, nDCSum);

                    cSaleItem.EMP_DC_AMT = CmUtil.DoubleAdd(cSaleItem.EMP_DC_AMT, nPrice);              // 단품 할인 금액

                    // 상품행별 영수 금액 재계산 처리
                    m_cDataService.UpdatePluItemAmount(cSaleItem);
                }

                m_cPluService.ItemAmountExeccute(true, true);

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


            return bRet;

        }
        #endregion

    }
}
