
using System;
using System.Data;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Cosmos.BaseFrame;
using Cosmos.UserFrame;
using Cosmos.ServiceProvider;
using Cosmos.Common;
using Cosmos.CommonManager;
using System.Threading;
using System.Collections;
using SPC.Kiosk.Common;
using SPC.Kiosk.Popup.Model;
namespace SPC.Kiosk.Payments
{
    /// <summary>
    /// POS HappyPoint Approval Process
    /// </summary>
    public class posMobileHappyCoupon : IDisposable
    {
        //CommonLog.ErrorLogWrite(this, "Ctor", "Fail", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
        #region [ Members ]
        /// <summary>
        /// HappyPointCertify ErrorCode
        /// </summary>
        public enum ErrorCode
        {
            MobileHappyCouponMobilePhoneNumberError,
            MobileHappyCouponMobileCouponNumberError,
            MobileHappyCouponMemInfoEncryptedCardNoError,
            MobileHappyCouponNotInitailzedError,
            MobileHappyCouponProcessingTimeOut,
            MobileHappyCouponTotalAmount,
            MobileHappyCouponCanUseCouponsIsZero,
            MobileHappyCouponUnknownError,
        }
        /// <summary>
        /// ErrorMessage Event
        /// </summary>
        /// <param name="LogString">반환 로그</param>
        public delegate void ErrorMessageEventHandler(string ErrorString);
        /// <summary>
        ///  로그메세지 이벤트 반환용 
        /// </summary>
        public event ErrorMessageEventHandler ErrorMessageEvent;
        /// <summary>
        /// Error 반환 Event
        /// </summary>
        /// <param name="errorCode">반환 Error Code</param>
        public delegate void LogErrorHandler(ErrorCode errorCode);
        /// <summary>
        ///  Error Code 이벤트 반환용 
        /// </summary>
        public event LogErrorHandler ErrorEvent;
        /// <summary>
        /// IcReadStart Event
        /// </summary>
        /// <param name="sender"></param>
        public delegate void IcReadStart(object sender);
        /// <summary>
        /// IcReadStart Event 반환용 
        /// </summary>
        public event IcReadStart ReadStart;
        /// <summary>
        /// IcReadStart Event
        /// </summary>
        /// <param name="sender"></param>
        public delegate void IcReadEnd(object sender);
        /// <summary>
        /// IcReadStart Event 반환용 
        /// </summary>
        public event IcReadEnd ReadEnd;

        private SManager sManager = null;                                // 이 객체를 통해 업무 Service 호출
        private StateServer StateObject = null;                          // StateObject : StateServer Object (객체)
        private PosStatus m_cPosStatus = null;                           // 기본정보 참조
        private TranStatus m_cTrnStatus = null;                          // 거래정보 참조        
        private DeviceStatus m_cDevStatus = null;                        // 디바이스 관리
        private IDataProcessUs m_cDataService = null;
        private IDataCommonUs m_cDataCommon = null;
        private IPaymentUs m_cMobileCoupon = null;

        private string mPay_DC_Type = "";                                           // 결제 그룹 코드
        private string mPay_DC_CD = "";                                             // 결제 상세 코드
        private string m_sPosMenuKey = PosKey.MENU_KEY.MOBILE_COUPON_HAPPYCON;      // 입력값 할인
        private string[] m_aRecvdData = null;
        /// <summary>
        /// 상품정보 작업용
        /// </summary> 
        private ArrayList m_aSaleItem = null;
        private struct ITEM_PLU_CHECK
        {
            public string sCouponNo;        // 쿠폰코드  
            public string sVCouponNo;       // 가상 쿠폰코드
            public string sProductID;       // 프로덕트 코드
            public string iTemCD;           // 상품코드
            public double T_Qty;            // 구매해야될 건수
            public double S_Qty;            // 구매한 건수 
            public double SALE_PRC;         // 상품단가
            public double SaleAmt;          // 상품판매금액
            public double PayAmt;           // 상품결제금액
            public double DCAmt;            // 할인
        }
        /// <summary>
        /// 입력구분
        /// </summary>
        private string m_sInPutType = "";
        /// <summary>
        /// 입력데이터
        /// </summary>
        private string m_sInPutData = "";
        /// <summary>
        /// 마스킹데이터
        /// </summary>
        private string m_sInMaskData = "";
        /// <summary>
        /// 카드데이터(암호화)
        /// </summary>
        private string m_sInEncData = "";
        /// <summary>
        /// 서비스코드
        /// </summary>
        private string m_sServiceCode = "";
        /// <summary>
        /// 승인카드번호
        /// </summary>
        private string m_sAppCardNo = "";
        /// <summary>
        /// 조회 성공 여부
        /// </summary>
        private bool m_bSearchSuccess = false;
        /// <summary>
        /// POS 초기화 필요 유무
        /// </summary>
        public bool NeedInitModule { get; set; } 
        /// <summary>
        /// 승인 수단 
        /// </summary>
        public string CertifyKey { get; set; } = string.Empty;
        /// <summary>
        /// 마스크된 회원성명
        /// </summary>
        public string MemberName { get; protected set; } = string.Empty;
        public string MemberNumber { get; protected set; } = string.Empty;
        /// <summary>
        /// SPC 임직원 유무
        /// </summary>
        public bool IsCompanyMember { get; protected set; }
        /// <summary>
        /// 적립 가능 유무
        /// </summary>
        public bool CanReservePoint { get; protected set; }
        /// <summary>
        /// 회원 등급
        /// </summary>
        public string MemberLevel { get; protected set; } = string.Empty;
        /// <summary>
        /// 회원 비밀번호
        /// </summary>
        public string MemberPassword { get; protected set; } = string.Empty;
        /// <summary>
        /// HappyApp 가입 고객
        /// </summary>
        public bool IsAppMamber { get; protected set; } = false;
        /// <summary>
        /// 단골 매장 유무
        /// </summary>
        public bool IsFavoriteStore { get; protected set; } = false;
        /// <summary>
        /// 회원 적립 Point
        /// </summary>
        public double MemberPoint { get; protected set; } = 0d;
        /// <summary>
        /// 회원 가용 Point
        /// </summary>
        public double UseablePoint { get; protected set; } = 0d;
        /// <summary>
        /// 승인 요청 포인트
        /// </summary>
        public double UseingPoint { get;  set; } = 0d;
        /// <summary>
        /// 승인 포인트
        /// </summary>
        public double ApprovalPoint { get; protected set; } = 0d;
        /// <summary>
        /// Point 사용시 비번 필요 유무
        /// </summary>
        public bool NeedPassword { get;  protected set; }
        public double Payments { get; protected set; }
        public long PaySEQ { get; protected set; }
        /// <summary>
        /// 인증 처리 성공 유무
        /// </summary>
        public bool ProcessOK
        {
            get { return m_bSearchSuccess; }
        }
        /// <summary>
        /// Processing TimeOut
        /// </summary>
        public bool IsTimeout
        {
            set
            {
                if (value)
                {
                    ErrorEvent(ErrorCode.MobileHappyCouponProcessingTimeOut);
                }
            }
        }
        public M_MobileCouponReturn CouponData { get; protected set; }
        #endregion

        #region [ Ctor  && Dispose ]
        /// <summary>
        /// Ctor
        /// </summary>
        public posMobileHappyCoupon()
        {
            try
            {
                sManager = new SManager();
                StateObject = (StateServer)StateServer.GetInstance();
                NeedInitModule = StateObject.POS == null
                               || StateObject.TRAN == null
                               || StateObject.DEVICE == null;
                if (!NeedInitModule)
                {
                    m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
                    m_cTrnStatus = (TranStatus)StateObject.TRAN;    // POS 거래정보 
                    m_cDevStatus = (DeviceStatus)StateObject.DEVICE;
                    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_cMobileCoupon = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.MOBILECOUPON_HAPPYCON);

                }
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "Ctor", "Fail", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            try
            {
                InDataToZeroFill();

                sManager = null;
                StateObject = null;
                m_cPosStatus = null;      // POS 기본정보
                m_cTrnStatus = null;    // POS 거래정보 
                m_cDevStatus = null;


                m_cDataService = null;
                m_cDataCommon = null;
                m_cMobileCoupon = null;
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "Dispose", "Fail", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }
        #endregion

        #region [ Methods ]
        /// <summary>
        /// HappyPoint 회원 조회 (16 자리이면 Mobile BarCode, 그외는 전화 번호)
        /// </summary>
        /// <param name="_inputString"></param>
        public void StartCertifyProcessing(string _inputString,double _payments)
        {
            try
            {
                CommonLog.InfoLogWrite(this, "StartCertifyProcessing()", "Start");
                SendReadStart();
                if (NeedInitModule)
                {
                    Thread.Sleep(1000); //진행창 보이기 위한 딜레이
                    ErrorEvent(ErrorCode.MobileHappyCouponNotInitailzedError);
                }
                else
                {
                    var startPorcess = false;
                    if (_inputString.Length > 6)
                    {
                        startPorcess = GetPrefixToPayTypeInfo(_inputString);
                        Payments = _payments;
                    }
                    else
                    {
                        SendErrLogEvent(ErrorCode.MobileHappyCouponMobileCouponNumberError);
                    }
                    //조회 전문 처리
                    if (startPorcess)
                    {
                        //SearchTxtInPut(PosConst.POS_INQ_MODE.SEARCH, "", "");
                        SearchTxtInPut(_inputString, _payments);
                    }

                }
                SendReadEnd();
                CommonLog.InfoLogWrite(this, "StartCertifyProcessing()", string.Format("End : Result={0}", ProcessOK ? "OK" : "Fail"));

            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "StartCertifyProcessing()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }

        public void StartPaymentProcessing(M_MobileCouponReturn _mobileCouponReturn, double _payments)
        {
            try
            {
                CommonLog.InfoLogWrite(this, "StartPaymentProcessing()", "Start");
                SendReadStart();
                if (NeedInitModule)
                {
                    Thread.Sleep(3000); //진행창 보이기 위한 딜레이
                    ErrorEvent(ErrorCode.MobileHappyCouponNotInitailzedError);
                }
                else
                {
                    var startPorcess = false;
                    if (_mobileCouponReturn is M_MobileCouponReturn
                        && _mobileCouponReturn.VirtureCoupons.Where(r=>r.RequestPrice > 0 ).Count() > 0)
                    {
                        CouponData = _mobileCouponReturn;
                        Payments = _payments;
                        startPorcess = true;
                    }
                    else
                    {
                        SendErrLogEvent(ErrorCode.MobileHappyCouponTotalAmount);
                    }
                    //승인 전문 처리
                    if (startPorcess)
                    {
                        CompleteTxtInPut();
                    }

                }
                SendReadEnd();
                CommonLog.InfoLogWrite(this, "StartPaymentProcessing()", string.Format("End : Result={0}", ProcessOK ? "OK" : "Fail"));

            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "StartPaymentProcessing()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }
        #region Prefix에 의한 사용 Van 정보 조회
        /// <summary>
        /// Prefix에 의한 사용 Van 정보 조회
        /// </summary>
        /// <param name="sCardNo"></param>
        /// <returns></returns>
        private bool GetPrefixToPayTypeInfo(string sCardNo)
        {
            bool result = false;
            try
            {
                if (sCardNo.Length == 0) return false;

                // PreFix 검색              
                DataTable dtVanInfo = m_cDataCommon.SeletPrefixToPayTypeInfo(sCardNo);
                if (dtVanInfo == null || dtVanInfo.Rows.Count <= 0)
                {
                    SendErrLogEvent(ErrorCode.MobileHappyCouponMobileCouponNumberError);
                    result = false;
                }
                else
                {
                    DataRow drVanInfo = dtVanInfo.Rows[0];

                    // 결제 그룹 코드
                    mPay_DC_Type = CmUtil.GetDataRowStr(drVanInfo, "PAY_DC_GRP_TYPE");
                    // 결제 상세 코드
                    mPay_DC_CD = CmUtil.GetDataRowStr(drVanInfo, "PAY_DC_CD");

                    result = true;
                }
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "GetPrefixToPayTypeInfo()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
                result = false;
            }
            return result;
        }
        #endregion
        #region CouponData 처리용 함수
        private MobileCouponType GetMobileCouponType(string _TypeCode)
        {
            MobileCouponType result = MobileCouponType.Normal;
            try
            {
                switch (_TypeCode)
                {
                    case "0":
                        result = MobileCouponType.Normal;
                        break;
                    case "1":
                        result = MobileCouponType.NormalValue;
                        break;
                    case "2":
                        result = MobileCouponType.CountLimit;
                        break;
                    case "3":
                        result = MobileCouponType.ValueLimit;
                        break;
                    case "4":
                        result = MobileCouponType.ValueFixed;
                        break;
                    default:
                        result = MobileCouponType.Normal;
                        break;
                }
            }
            catch 
            {
                result = MobileCouponType.Normal;
            }
            return result;
        }
        private string GetStringMobileCouponType(MobileCouponType _Type)
        {
            string result = "0";
            try
            {
                switch (_Type)
                {
                    case MobileCouponType.Normal:
                        result = "0";
                        break;
                    case MobileCouponType.NormalValue:
                        result = "1";
                        break;
                    case MobileCouponType.CountLimit:
                        result = "2";
                        break;
                    case MobileCouponType.ValueLimit:
                        result = "3";
                        break;
                    case MobileCouponType.ValueFixed:
                        result = "4";
                        break;
                    default:
                        result = "0";
                        break;
                }
            }
            catch 
            {
                result = "0";
            }
            return result;
        }
        private MobileCouponStatusType GetMobileCouponStatusType(string _TypeCode)
        {
            MobileCouponStatusType result = MobileCouponStatusType.CanNotUse;
            try
            {
                switch (_TypeCode)
                {
                    case "Y":
                        result = MobileCouponStatusType.CanUse;
                        break;
                    case "N":
                        result = MobileCouponStatusType.CanNotUse;
                        break;
                    case "D":
                        result = MobileCouponStatusType.Used;
                        break;
                    case "C":
                        result = MobileCouponStatusType.Cancel;
                        break;
                    case "R":
                        result = MobileCouponStatusType.Refound;
                        break;
                    default:
                        result = MobileCouponStatusType.CanNotUse;
                        break;
                }
            }
            catch (Exception)
            {
                result = MobileCouponStatusType.CanNotUse;
            }
            return result;

        }
        
        private string GetNextData(ref int _index)
        {
            string result = string.Empty;
            try
            {
                _index++;
                if (m_aRecvdData.Length > _index)
                {
                    result = m_aRecvdData[_index].Trim();
                }

            }
            catch (Exception)
            {
                result = string.Empty;
            }
            return result;
        }
        private bool CouponDataCreate()
        {
            bool result = false;
            try
            {
                int dataIndex = -1;
                if (m_aRecvdData is string[] && m_aRecvdData.Length > 6)
                {
                    if (GetNextData(ref dataIndex).Equals("0"))
                    {
                        GetNextData(ref dataIndex); // [1] 버림
                        CouponData = new M_MobileCouponReturn
                        {
                            Number = GetNextData(ref dataIndex), //[2]
                            Name = GetNextData(ref dataIndex), //[3]
                            TotalAmount = CmUtil.LongParse(GetNextData(ref dataIndex)), //[4]
                            IsOnlyAllUse = GetNextData(ref dataIndex).Equals("1"), //[5]
                        };
                        var virtureCouponCount = CmUtil.LongParse(GetNextData(ref dataIndex)); //[6]
                        var virtureCoupons = new List<M_MobileCouponDetail>();
                        for (int iLoop = 0; iLoop < virtureCouponCount; iLoop++)
                        {
                            var aVirtureCoupon = new M_MobileCouponDetail
                            {
                                Number = GetNextData(ref dataIndex),
                                Name = GetNextData(ref dataIndex),
                                BrandCode = GetNextData(ref dataIndex),
                                BrandName = GetNextData(ref dataIndex),
                                Type = GetMobileCouponType(GetNextData(ref dataIndex)),
                                Option = GetNextData(ref dataIndex).Equals("1")
                                       ? MobileCouponOptionType.ItemFixed
                                       : MobileCouponOptionType.None,
                                ShowPrice = CmUtil.LongParse(GetNextData(ref dataIndex)),
                                ByePrice = CmUtil.LongParse(GetNextData(ref dataIndex)),
                                RemainPrice = CmUtil.LongParse(GetNextData(ref dataIndex)),
                                CanUsingPrice = CmUtil.LongParse(GetNextData(ref dataIndex)),
                                GroupNo = CmUtil.IntParse(GetNextData(ref dataIndex)),
                                GroupLimitUsingCount = CmUtil.IntParse(GetNextData(ref dataIndex)),
                                StartDate = CommonFunction.GetDate(GetNextData(ref dataIndex)),
                                EndDate = CommonFunction.GetDate(GetNextData(ref dataIndex)),
                                Status = GetMobileCouponStatusType(GetNextData(ref dataIndex)),
                                StatusDetail = GetNextData(ref dataIndex),
                                ItemCodeKey = GetNextData(ref dataIndex),
                            };
                            var itemCount = CmUtil.IntParse(GetNextData(ref dataIndex));
                            var itemCodes = new List<string>();
                            if (itemCount > 0)
                            {
                                for (int iLoop2 = 0; iLoop2 < itemCount; iLoop2++)
                                {
                                    itemCodes.Add(GetNextData(ref dataIndex));
                                }
                            }
                            aVirtureCoupon.ItemCodes = itemCodes;
                            virtureCoupons.Add(aVirtureCoupon);
                        }
                        if (virtureCoupons.Where(r => r.Status.Equals(MobileCouponStatusType.CanUse)).Count() > 0)
                        {
                            CouponData.VirtureCoupons = virtureCoupons.OrderBy(r => r.Status).ToList();
                            result = true;
                        }
                        else
                        {
                            SendErrLogEvent(ErrorCode.MobileHappyCouponCanUseCouponsIsZero);
                            CommonLog.ErrorLogWrite(this, "CouponDataCreate()", "Not found useable Coupons", string.Format("{0} : {1}", CouponData.Name, CouponData.Number));
                        }
                    }
                    else
                    {
                        CommonLog.ErrorLogWrite(this, "CouponDataCreate()", "Fail !!", string.Format("{0}={1}", m_aRecvdData[0].Trim(), m_aRecvdData[1].Trim()));
                    }
                }
                else
                {
                    CommonLog.ErrorLogWrite(this, "CouponDataCreate()", "Recive Data Length Fail !!");
                }

            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "CouponDataCreate()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
                result = false;
            }
            return result;

        }

        #endregion
        /// <summary>
        /// 조회 처리
        /// </summary>
        /// <returns></returns>
        private void SearchTxtInPut(string _inputString, double _payments)
        {
            string sCoponinfo = "";
            string sInPutType = "";
            string sInPutData = "";
            string sInEncData = "";
            try
            {
                CommonLog.DebugLogWrite(this, "SearchTxtInPut()", "Start");

                // 중복체크
                //if (DataGridSetting(4, ref aRet, ref aRet2, ref aRet3) != UserCom.RST_OK) return sRet;
                var sSearchType = PosConst.POS_INQ_MODE.SEARCH;
                sInPutType = m_sInPutType;
                sInPutData = m_sInPutData;
                sInEncData = m_sInEncData;
                if (m_sInEncData == "")
                {
                    if (m_sInPutData == "")
                    {
                        sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_KEYIN_CP;
                        sInPutData = _inputString;
                    }
                }
                m_aRecvdData = null;
                var sRet = m_cMobileCoupon.SearchPayment(new string[] { m_sPosMenuKey, sInPutType, sInPutData, sInPutData, _payments.ToString(), "", "", "", mPay_DC_Type, mPay_DC_CD, sSearchType, sCoponinfo }, ref m_aRecvdData);
                if (sRet != UserCom.RST_OK)
                {
                    InDataToZeroFill();
                    if (sRet == null || sRet.Equals(UserCom.RST_ERR))
                    {
                        SendErrLogEvent(ErrorCode.MobileHappyCouponUnknownError);
                    }
                    else
                    {
                        SendErrorMessageEvent(sRet);
                    }

                }
                else
                {
                    m_bSearchSuccess = CouponDataCreate();

                }
                CommonLog.DebugLogWrite(this, "SearchTxtInPut()", string.Format("End : Result={0}", sRet));

            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "SearchTxtInPut()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }

        /// <summary>
        /// 사용 승인 처리
        /// </summary>
        /// <returns></returns>
        private void CompleteTxtInPut()
        {
            CommonLog.DebugLogWrite(this, "CompleteTxtInPut()", "Start");
            string sProductiTem = string.Empty;
            string sRet = UserCom.RST_ERR;
            try
            {
                m_bSearchSuccess = false;
                var sSendData = new StringBuilder();
                var sCounponIfo = new StringBuilder();
                bool biTemCheck = false;
                // 상품정보
                ArrayList aSaleItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);

                m_aSaleItem = new ArrayList();
                for (int iRow = 0; iRow < aSaleItem.Count; iRow++)
                {
                    Column.TR_PLU.DATA cSaleItem = (Column.TR_PLU.DATA)aSaleItem[iRow];
                    m_aSaleItem.Add(cSaleItem.Clone());
                }
                var checkOK = true;
                sSendData.Append(CmUtil.MidH(CouponData.VirtureCoupons.Where(r => r.Status.Equals(MobileCouponStatusType.CanUse)).Sum(r2=>r2.DiscountPrice).ToString(), 0, 10));
                sSendData.Append(CmUtil.MidH(CouponData.VirtureCoupons.Where(r =>r.Status.Equals(MobileCouponStatusType.CanUse)).Count().ToString(), 0, 5));
                foreach (var aCoupon in CouponData.VirtureCoupons)
                {
                    if (aCoupon.DiscountPrice > 0)
                    {
                        if (CouponData.IsOnlyAllUse)
                        {
                            var checkGrooup = aCoupon.GroupNo;
                            var groupItemCount = CouponData.VirtureCoupons.Where(r => r.GroupNo.Equals(checkGrooup)
                                               && r.Status.Equals(MobileCouponStatusType.CanUse)).Count();
                            var usingIgtemCount = CouponData.VirtureCoupons.Where(r => r.GroupNo.Equals(checkGrooup) && r.RequestPrice > 0
                                                && r.Status.Equals(MobileCouponStatusType.CanUse)).Count();
                            if (usingIgtemCount < groupItemCount)
                            {
                                SendErrorMessageEvent(POS_MESSAGE.ERROR.MSG_0410);
                                checkOK = false;
                                break;
                            }
                        }

                        if (!string.IsNullOrEmpty(aCoupon.ItemCodeKey)
                         && (aCoupon.Type.Equals(MobileCouponType.Normal)
                            || aCoupon.Type.Equals(MobileCouponType.CountLimit)
                            || aCoupon.Type.Equals(MobileCouponType.ValueFixed)
                            ))
                        {
                            sRet = GetDCItemAmount(aCoupon.ItemCodeKey
                                                 , CouponData.Number
                                                 , aCoupon.Number
                                                 , m_cDataService.DoubleParse(aCoupon.DiscountPrice.ToString())
                                                 , aCoupon.Option.Equals(MobileCouponOptionType.ItemFixed) ? "1" : "0", ref sProductiTem);
                            if (sRet != UserCom.RST_OK && aCoupon.Option.Equals(MobileCouponOptionType.ItemFixed))
                            {
                                SendErrorMessageEvent(sRet);
                                checkOK = false;
                                break;
                            }
                        }
                        sSendData.Append(CmUtil.MidH(CouponData.Number, 0, 32));                    //쿠폰번호
                        sSendData.Append(CmUtil.MidH(aCoupon.Number, 0, 32));                       //가상쿠폰번호
                        sSendData.Append(CmUtil.MidH(aCoupon.DiscountPrice.ToString(), 0, 10));     //사용금액

                        sCounponIfo.Append(CmUtil.MidH(CouponData.Number, 0, 32));                    //쿠폰번호
                        sCounponIfo.Append("|");
                        sCounponIfo.Append(CmUtil.MidH(aCoupon.Number, 0, 32));                       //가상쿠폰번호
                        sCounponIfo.Append("|");
                        sCounponIfo.Append(GetStringMobileCouponType(aCoupon.Type));                  //쿠폰종류
                        sCounponIfo.Append("@~");
                        if (aCoupon.Option.Equals(MobileCouponOptionType.ItemFixed)) biTemCheck = true;
                    }
                }
                if (checkOK)
                {
                    if (biTemCheck == true)
                    {
                        sSendData.Append(CmUtil.MidH(m_aSaleItem.Count.ToString(), 0, 5));                                                                 // POS 상품갯수
                        for (int iRow = 0; iRow < m_aSaleItem.Count; iRow++)
                        {
                            Column.TR_PLU.DATA cSaleItem = (Column.TR_PLU.DATA)m_aSaleItem[iRow];

                            if (cSaleItem.CANCEL_DIV == PosConst.CANCEL_DIV.CANCEL || cSaleItem.CANCEL_DIV_MAIN == PosConst.CANCEL_DIV.CANCEL) continue;// 지정취소

                            sSendData.Append(CmUtil.MidH(cSaleItem.ITEM_PLU_CD, 0, 32));                                                                 // POS 상품코드
                                                                                                                                                         // 전문 설정 오류 수정(2017.05.22)
                            sSendData.Append(CmUtil.MidH(cSaleItem.SALE_AMT.ToString(), 0, 10));                                                         // POS 상품금액
                                                                                                                                                         //sSendData += m_cDataService.DoubleParse(CmUtil.MidH(cSaleItem.SALE_AMT.ToString(), 0, 10));                             // POS 상품금액
                        }
                    }
                    else
                    {
                        sSendData.Append(CmUtil.MidH("0", 0, 5));                                                                                        // POS 상품갯수
                    }
                    string sInPutType = m_sInPutType;
                    string sInPutData = m_sInPutData;
                    string sInEncData = m_sInEncData;
                    if (m_sInEncData == "")
                    {
                        if (m_sInPutData == "")
                        {
                            sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_KEYIN_CP;
                            sInPutData = CouponData.Number;

                        }
                    }
                    // 승인 처리
                    sRet = m_cMobileCoupon.SetPayment(new string[] { m_sPosMenuKey, sInPutType, sInPutData, sInPutData, "0", "", "", "", mPay_DC_Type, mPay_DC_CD, sSendData.ToString(), sCounponIfo.ToString(), sProductiTem });
                    if (sRet != UserCom.RST_OK)
                    {
                        InDataToZeroFill();
                        if (sRet == null || sRet.Equals(UserCom.RST_ERR))
                        {
                            SendErrLogEvent(ErrorCode.MobileHappyCouponUnknownError);
                        }
                        else
                        {
                            SendErrorMessageEvent(sRet);
                        }
                    }
                    else
                    {
                        CouponData.TotalUseAmount = CouponData.VirtureCoupons.Where(r => r.Status.Equals(MobileCouponStatusType.CanUse)).Sum(r2 => r2.DiscountPrice);
                        foreach (var aCoupon in CouponData.VirtureCoupons)
                        {
                            if (aCoupon.DiscountPrice > 0)  aCoupon.PaySEQ = FindPaySEQ(aCoupon.Number);
                        }
                        m_bSearchSuccess = true;
                    }
                }
                sSendData.Remove(0, sSendData.Length);
                sCounponIfo.Remove(0, sCounponIfo.Length);

            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "CompleteTxtInPut()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
            CommonLog.DebugLogWrite(this, "CompleteTxtInPut()", "End");
        }
        private long FindPaySEQ(string _virtureCouponNo)
        {
            var result = -1L;
            try
            {
                var alPayItem = (ArrayList)StateObject.GetItemObject(Column.TR_PAYMENT.ITEM);
                foreach (var aitem in alPayItem)
                {
                    if (aitem is Column.TR_PAYMENT.DATA aPayTem)
                    {
                        if (aPayTem.PAY_WAY_CD.Trim().Equals(mPay_DC_Type)
                         && aPayTem.PAY_DTL_CD_01.Trim().Equals(mPay_DC_CD)
                         && aPayTem.OCCUR_ENTRY_09.Trim().Equals(_virtureCouponNo))
                        {
                            result = aPayTem.SEQ;
                            break;
                        }
                    }
                }

            }
            catch 
            {
                result = -1L;
            }
            return result;
        }
        #region ProductID로 등록된 상품 체크
        /// <summary>
        /// ProductID로 등록된 상품 체크
        /// </summary>
        /// <param name="sProductID"></param>
        /// <param name="sCouponNo"></param>
        /// <param name="sVCouponNo"></param>
        /// <param name="nPayAmt"></param>
        /// <param name="siTemCheck"></param>
        /// <returns></returns>
        public string GetDCItemAmount(string sProductID, string sCouponNo, string sVCouponNo, double nPayAmt, string sItemChgUse, ref string siTemCheck)
        {
            string sRet = UserCom.RST_ERR;

            double niTemSum = 0;
            double nQty = 0;
            int iMaxIndex = -1;

            try
            {
                // 프로덕트 id 없으면 Skip
                if (sProductID.Trim().Length <= 0) return sRet;

                // 쿠폰 List 조회
                DataTable dtMemu = m_cDataCommon.SeletProductIDToItemCD(sProductID);
                if (dtMemu == null || dtMemu.Rows.Count <= 0)
                {
                    //WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0149);
                    return UserCom.RST_OK;
                }

                ITEM_PLU_CHECK iTemCheck = new ITEM_PLU_CHECK();

                if (m_aSaleItem.Count <= 0)
                {
                    return POS_MESSAGE.ERROR.MSG_0149;
                }

                foreach (DataRow dr in dtMemu.Rows)
                {
                    // Product ID로 결제구분을 재설정한다.
                    string sDC_Type = CmUtil.GetDataRowStr(dr, "PAY_DC_GRP_TYPE").Trim();
                    if (sDC_Type.Trim().Length > 0) mPay_DC_Type = sDC_Type.Trim();

                    // Product ID로 결제상세코드를 재설정한다.
                    string sDC_CD = CmUtil.GetDataRowStr(dr, "PAY_DC_CD").Trim();
                    if (sDC_Type.Trim().Length > 0) mPay_DC_CD = sDC_CD.Trim();

                    for (int iRow = 0; iRow < m_aSaleItem.Count; iRow++)
                    {
                        Column.TR_PLU.DATA cSaleItem = (Column.TR_PLU.DATA)m_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.FREE) 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 (CmUtil.GetDataRowStr(dr, "ITEM_CHECK_YN") == "1")
                        {
                            // 등록된 상품과 쿠폰마스터 상품 체크용 저장
                            if (CmUtil.GetDataRowStr(dr, "ITEM_CD") == cSaleItem.ITEM_PLU_CD)
                            {
                                // 할인 대상 iTemCD/수량 체크용 저장
                                nQty = CmUtil.GetDataRowDouble(dr, "QTY");

                                // 할인금액+결제요금액 보다 상품판매금액이 같거나 큰 경우만 
                                if (nQty > 0 && cSaleItem.SALE_QTY > 0 && cSaleItem.BILL_AMT >= nPayAmt + CmUtil.GetDataRowDouble(dr, "DC_AMT"))
                                {
                                    // 제일 큰 금액에 설정
                                    if (iTemCheck.SALE_PRC == 0 || iTemCheck.SALE_PRC < cSaleItem.SALE_PRC)
                                    {
                                        iMaxIndex = iRow;

                                        iTemCheck.sCouponNo = sCouponNo.Trim();
                                        iTemCheck.sVCouponNo = sVCouponNo.Trim();
                                        iTemCheck.sProductID = CmUtil.GetDataRowStr(dr, "PRODUCT_CD").Trim();
                                        iTemCheck.iTemCD = cSaleItem.ITEM_PLU_CD;
                                        iTemCheck.SALE_PRC = cSaleItem.SALE_PRC;
                                        iTemCheck.SaleAmt = cSaleItem.BILL_AMT;
                                        iTemCheck.PayAmt = nPayAmt;
                                        iTemCheck.DCAmt = CmUtil.GetDataRowDouble(dr, "DC_AMT");

                                        // 대상 금액 sum
                                        niTemSum = CmUtil.DoubleAdd(CmUtil.GetDataRowDouble(dr, "DC_AMT"), nPayAmt);
                                    }
                                }
                            }
                        }
                        else
                        {
                            nQty = CmUtil.GetDataRowDouble(dr, "QTY");

                            // 프로덕트 코드 미설정 오류로 인한 수정(2017.05.18)
                            //if (nQty > 0 && cSaleItem.SALE_QTY > 0 && cSaleItem.BILL_AMT >= nPayAmt + CmUtil.GetDataRowDouble(dr, "DC_AMT"))
                            //{
                            // 제일 큰 금액에 설정
                            if (iTemCheck.SALE_PRC == 0 || iTemCheck.SALE_PRC < cSaleItem.SALE_PRC)
                            {
                                iMaxIndex = iRow;

                                iTemCheck.sCouponNo = sCouponNo.Trim();
                                iTemCheck.sVCouponNo = sVCouponNo.Trim();
                                iTemCheck.sProductID = CmUtil.GetDataRowStr(dr, "PRODUCT_CD").Trim();
                                iTemCheck.iTemCD = cSaleItem.ITEM_PLU_CD;
                                iTemCheck.SALE_PRC = cSaleItem.SALE_PRC;
                                iTemCheck.SaleAmt = cSaleItem.BILL_AMT;
                                iTemCheck.PayAmt = nPayAmt;
                                iTemCheck.DCAmt = CmUtil.GetDataRowDouble(dr, "DC_AMT");

                                // 대상 금액 sum
                                niTemSum = CmUtil.DoubleAdd(CmUtil.GetDataRowDouble(dr, "DC_AMT"), nPayAmt);
                            }
                            //}
                        }
                    }
                }

                // 적용 상품의 상품금액 변경
                if (iMaxIndex > -1)
                {
                    Column.TR_PLU.DATA cSaleItem = (Column.TR_PLU.DATA)m_aSaleItem[iMaxIndex];

                    cSaleItem.CPN_DC_DIV = mPay_DC_Type + mPay_DC_CD;
                    cSaleItem.CPN_DC_AMT = CmUtil.DoubleAdd(cSaleItem.CPN_DC_AMT, iTemCheck.DCAmt);
                    cSaleItem.BILL_AMT = CmUtil.DoubleSubtraction(cSaleItem.BILL_AMT, iTemCheck.DCAmt);
                }

                //// 구매수량 체크
                //for (int index = 0; index < m_aSaleItem.Count; index++)
                //{
                //    if (iTemCheck.iTemCD != "")
                //    {
                //        if (iTemCheck.T_Qty >= 0 && iTemCheck.S_Qty != 0)
                //        {
                //            WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0160);
                //            return sRet;
                //        }
                //    }
                //}

                // 금액 체크
                if (niTemSum > Payments)
                {
                    return POS_MESSAGE.ERROR.MSG_0160;
                }

                // 가능한 상품 미존재시 && 타상품 교환 불가시
                if (niTemSum <= 0 && sItemChgUse == "1")
                {
                    return POS_MESSAGE.ERROR.MSG_0160;
                }

                // 프로덕트 정보 체크용
                if (!string.IsNullOrEmpty(iTemCheck.sCouponNo) && iTemCheck.sCouponNo.Trim() != "")
                {
                    siTemCheck += iTemCheck.sCouponNo;
                    siTemCheck += "!~";
                    siTemCheck += iTemCheck.sVCouponNo;
                    siTemCheck += "!~";
                    siTemCheck += iTemCheck.sProductID;
                    siTemCheck += "!~";
                    siTemCheck += iTemCheck.iTemCD;
                    siTemCheck += "!~";
                    siTemCheck += iTemCheck.PayAmt;
                    siTemCheck += "!~";
                    siTemCheck += iTemCheck.DCAmt;
                    siTemCheck += "$~";
                }

                sRet = UserCom.RST_OK;
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "GetDCItemAmount()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
            return sRet;
        }
        #endregion

        #region 여전법 대응
        /// <summary>
        /// ZeroFill 초기화
        /// </summary>
        private void InDataToZeroFill()
        {
            try
            {

                //여전법 대응!
                //////////////////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref m_sInPutData);
                CmUtil.ZeroFillClear(ref m_sInEncData);
                CmUtil.ZeroFillClear(ref m_sInMaskData);
                //////////////////////////////////////////////////////////////////////////////////
            }
            catch
            {
            }

        }
        #endregion 여전법 대응

        private void SendErrorMessageEvent(string _errorMessageString)
        {
            try
            {
                CommonLog.ErrorLogWrite(this, "SendErrorMessageEvent()", _errorMessageString);
                ErrorMessageEvent(_errorMessageString);
            }
            catch
            {
            }
        }
        private void SendErrLogEvent(ErrorCode _errorCode)
        {
            try
            {
                CommonLog.DebugLogWrite(this, "SendErrLogEvent()", _errorCode.ToString());
                ErrorEvent(_errorCode);
            }
            catch
            {

            }
        }
        private void SendReadStart()
        {
            try
            {
                CommonLog.DebugLogWrite(this, "SendReadStart()");
                ReadStart(this);
            }
            catch
            {

            }
        }
        private void SendReadEnd()
        {
            try
            {
                CommonLog.DebugLogWrite(this, "SendReadEnd()");
                ReadEnd(this);
            }
            catch
            {

            }
        }
        private void ClearCardInfo()
        {
            try
            {
                m_sInPutType = "";      // 입력구분
                m_sInPutData = "";      // 입력데이터
                m_sInMaskData = "";     // 마스킹
                m_sInEncData = "";      // 카드데이터
                m_sServiceCode = "";    // 서비스코드
                m_sAppCardNo = "";      // 승인카드번호


                m_bSearchSuccess = false;
            }
            catch 
            {
            }
        }
        #endregion




    }
}