
using System;
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 SPC.Kiosk.Popup.Model;
using SPC.Kiosk.Common;
namespace SPC.Kiosk.Payments
{
    /// <summary>
    /// 통신사 할인 승인
    /// </summary>
    public class posMobileCompanyDiscount : IDisposable
    {
        //CommonLog.ErrorLogWrite("SPC.Kiosk.Payments.posMobileCompanyDiscount ?() Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
        #region [ Members ]
        public enum ErrorCode
        {
            MobileCompanyDiscountCardNumberError,
            MobileCompanyDiscountEncrtipError,
            MobileCompanyDiscountNotInitailzedError,
            MobileCompanyDiscountProcessingTimeOut,
            MobileCompanyDiscountUnknownError,
            MobileCompanyDiscountCardNumError
        }
        /// <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 PosOLEDevice.DelegateIcReader delegateReader;            // IC리더 콜백
        private IICReaderUs m_cDeviceICReader = null;
        private IPaymentUs m_cMobilePoint = null;

        private string m_sPosMenuKey = string.Empty;
        /// <summary>
        /// 입력구분
        /// </summary>
        private string m_sInPutType = string.Empty;
        /// <summary>
        /// 입력데이터
        /// </summary>
        private string m_sInPutData = string.Empty;
        /// <summary>
        /// 마스킹데이터
        /// </summary>
        private string m_sInMaskData = string.Empty;
        /// <summary>
        /// 카드데이터(암호화)
        /// </summary>
        private string m_sInEncData = string.Empty;
        /// <summary>
        /// 서비스코드
        /// </summary>
        private string m_sServiceCode = string.Empty;
        /// <summary>
        /// 조회 성공 여부
        /// </summary>
        private bool m_bSearchSuccess = false;
        /// <summary>
        /// POS 초기화 필요 유무
        /// </summary>
        public bool NeedInitModule { get; set; } 
        /// <summary>
        /// 승인 수단 
        /// </summary>
        public string CertifyKey { get; set; } = string.Empty;
        public MobileCompanyType MobileCompany { get; set; }

        public double Payment { get; set; } = 0d;

        private bool icCallBack = false;
        /// <summary>
        /// Ic Reader CallBack  Switch
        /// </summary>
        public bool IcCallBack
        {
            get { return icCallBack; }
            set
            {
                if (value)
                {
                    m_cDeviceICReader.RegIcCallback(delegateReader);
                }
                icCallBack = value;
            }
        }
        /// <summary>
        /// 마스크된 회원성명
        /// </summary>
        public string MemberName { get; protected set; } = string.Empty;
        /// <summary>
        /// 할인 금액
        /// </summary>
        public double DiscountValue { get; protected set; } = 0d;
        public long PaySEQ { get; protected set; }
        public bool KT_Double { get; set; }
        /// <summary>
        /// 인증 처리 성공 유무
        /// </summary>
        public bool ProcessOK
        {
            get { return m_bSearchSuccess; }
        }
        public bool IsTimeout
        {
            set
            {
                if (value)
                {
                    ErrorEvent(ErrorCode.MobileCompanyDiscountProcessingTimeOut);
                }
            }
        }
        #endregion

        #region [ Ctor  && Dispose ]
        /// <summary>
        /// Ctor
        /// </summary>
        public posMobileCompanyDiscount()
        {
            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_cDeviceICReader = (IICReaderUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_ICREADER);
                    m_cMobilePoint = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.POINTMOBILECOM);
                    delegateReader = new PosOLEDevice.DelegateIcReader(OnIcReaderCallBack);     // IC리더 콜백
                }

            }
            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_cDeviceICReader = null;
                m_cMobilePoint = null;
                delegateReader = null;     // IC리더 콜백
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "Dispose", "Fail", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }
        #endregion

        #region [ Methods ]

        /// <summary>
        /// 통신사 할인 처리
        /// </summary>
        /// <param name="_inputString"></param>
        public void StartCertifyProcessing(string _inputString, MobileCompanyType _mobileCompanyType,double _payments)
        {
            try
            {
                CommonLog.InfoLogWrite(this, "StartCertifyProcessing()", "Start");
                SendReadStart();
                if (NeedInitModule)
                {
                    Thread.Sleep(1000); //진행창 보이기 위한 딜레이
                    ErrorEvent(ErrorCode.MobileCompanyDiscountNotInitailzedError);
                }
                else
                {
                    var startPorcess = false;
                    if (_inputString.Replace("=", "").Replace("@", "").Length.Equals(16))
                    {
                        MobileCompany = _mobileCompanyType;
                        Payment = _payments;
                        m_cTrnStatus.Head.TradeDiv = ItemConst.TRAN_DIV.NORMAL;
                        switch (MobileCompany)
                        {
                            case MobileCompanyType.KT_Mobile:
                                if (KT_Double)
                                {
                                    m_sPosMenuKey = PosKey.MENU_KEY.KT_DOUBLE;
                                }
                                else
                                {
                                    m_sPosMenuKey = PosKey.MENU_KEY.KT;
                                }
                                break;
                            case MobileCompanyType.SK_Telecom:
                                m_sPosMenuKey = PosKey.MENU_KEY.SKT;
                                break;
                            case MobileCompanyType.LG_Uplus:
                                m_sPosMenuKey = PosKey.MENU_KEY.LGT;
                                break;
                        }
                        m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_SWIP;
                        m_sInMaskData = _inputString;
                        m_sInPutData = _inputString + "=";
                        startPorcess = true;
                    }
                    else
                    {
                        SendErrLogEvent(ErrorCode.MobileCompanyDiscountCardNumError);
                    }
                    //승인 전문 처리
                    if (startPorcess)
                    {
                        if (EncryptedCardNo(m_sInPutData, ref m_sInMaskData, ref m_sInEncData))
                        {
                            CompleteTxtInPut();
                        }
                        else
                        {
                            SendErrLogEvent(ErrorCode.MobileCompanyDiscountEncrtipError);
                        }
                    }
                    else
                    {
                        SendErrLogEvent(ErrorCode.MobileCompanyDiscountUnknownError);
                    }
                }
                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));
            }
        }
        /// <summary>
        /// 휴대폰 번호 형식 확인
        /// </summary>
        /// <param name="sInputData"></param>
        /// <returns></returns>
        private bool IsCellularPhoneNumber(string sInputData)
        {
            bool bRet = false;
            try
            {
                if (sInputData.Length == 10 || sInputData.Length == 11)
                {
                    if (sInputData.StartsWith("010") == true || sInputData.StartsWith("011") == true || sInputData.StartsWith("017") == true ||
                       sInputData.StartsWith("016") == true || sInputData.StartsWith("018") == true || sInputData.StartsWith("019") == true)
                    {
                        bRet = true;
                    }
                }
            }
            catch 
            {
                bRet = false;
            }
            return bRet;
        }
        /// <summary>
        /// Happoint 조회 전문 처리
        /// </summary>
        private void CompleteTxtInPut()
        {
            CommonLog.DebugLogWrite(this, "CompleteTxtInPut()", "Start");
            string sRet = UserCom.RST_ERR;
            try
            {

                m_bSearchSuccess = false;
                
                // 승인
                sRet = m_cMobilePoint.SetPayment(new string[] { m_sPosMenuKey, m_sInPutType, m_sInMaskData, m_sInEncData, Payment.ToString(), "", "", "", "", "", "", "", "", "", "", "" });
                if (sRet != UserCom.RST_OK)
                {
                    CertifyKey = string.Empty;
                    InDataToZeroFill();
                    if (sRet == null || sRet.Equals(UserCom.RST_ERR))
                    {
                        SendErrLogEvent(ErrorCode.MobileCompanyDiscountUnknownError);
                    }
                    else
                    {
                        SendErrorMessageEvent(sRet);
                    }
                }
                else
                {

                    CertifyKey = m_sInPutData;
                    var cPayItem = (Column.TR_PAYMENT.DATA)m_cMobilePoint.GetPayment(new string[] { });
                    PaySEQ = cPayItem.SEQ;
                    DiscountValue = cPayItem.AMT_ENTRY_01;
                    m_bSearchSuccess = true;

                }            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "CompleteTxtInPut()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
            CommonLog.DebugLogWrite(this, "CompleteTxtInPut()", "End");
        }
        /// <summary>
        /// 카드 번호 암호화
        /// </summary>
        /// <param name="sInData"></param>
        /// <param name="sInMaskData"></param>
        /// <param name="sInEncData"></param>
        /// <returns></returns>
        private bool EncryptedCardNo(string sInData, ref string sInMaskData, ref string sInEncData)
        {
            string sEncData = sInData;
            bool bRet = false;
            try
            {

                //#20170913 현금영수증, 포인트카드 마스킹 미적용 start
                // "0"인 경우 마스킹 미처리
                //기존
                //sEncData = m_cDeviceICReader.GetEncryptedCardNo(sInData).Trim();
                //변경
                sEncData = m_cDeviceICReader.GetEncryptedCardNo(sInData, "0").Trim();
                //#20170913 현금영수증, 포인트카드 마스킹 미적용 end

                if (CmUtil.MidH(sEncData, 0, 2) == "00")
                {
                    sInEncData = CmUtil.MidH(sEncData, 2, 512).Trim();                          // 암호화 데이터
                    sInMaskData = CmUtil.MidH(sEncData, 514, sEncData.Length - 514).Trim();     // 마스킹 데이터

                    //#20170913 현금영수증, 포인트카드 마스킹 미적용 start
                    sInMaskData = CmUtil.MidH(sInMaskData, 0, 6) + "********";
                    //#20170913 현금영수증, 포인트카드 마스킹 미적용 end

                    bRet = true;
                }
                else
                {
                    CommonLog.ErrorLogWrite(this, "EncryptedCardNo()", "Fail !!");
                }

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

        #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 여전법 대응

        #region IC리더 콜백
        //delegate void DelegateIcReaderCallBack(int rc, StringBuilder str);
        /// <summary>
        /// IC리더 콜백 함수
        /// </summary>
        /// <param name="num"></param>
        /// <param name="str"></param>
        public void OnIcReaderCallBack(int num, StringBuilder str)
        {
            try
            {
                SendReadStart();
                if (num == 1)
                {
                    GetIcCardData();
                }
                else
                {
                    if (str.ToString().StartsWith("EN"))
                    {
                        ClearCardInfo();        // 카드 입력 정보 클리어

                        m_sInEncData = CmUtil.MidH(str.ToString(), 0, 512).Trim();
                        m_sInMaskData = CmUtil.MidH(str.ToString(), 512, 40).Trim();
                        m_sInPutData = m_sInMaskData;
                        m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_SWIP;
                    }
                }
                if (!string.IsNullOrEmpty(m_sInPutData)) CompleteTxtInPut();
                SendReadEnd();
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "OnIcReaderCallBack()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }
        private bool GetIcCardData()
        {
            string sRsvStr = "";
            try
            {
                //IcCallBack = false;     // IC리더 콜백 해지

                ClearCardInfo();        // 카드 입력 정보 클리어

                if (m_cDeviceICReader.GetCardInfo_ICReader(PosConst.IC_READER_TRAN_TYPE.POINT, 0, ref sRsvStr) == true)
                {
                    if (CmUtil.MidH(sRsvStr, 0, 2) == "00")
                    {
                        m_sInEncData = CmUtil.MidH(sRsvStr, 6, 512).Trim();
                        m_sInMaskData = CmUtil.MidH(sRsvStr, 1030, 37).Trim();
                        m_sServiceCode = CmUtil.MidH(sRsvStr, 1067, 5).Trim();

                        m_sInPutData = m_sInMaskData;
                        m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_SWIP;



                        return true;
                    }
                }

            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "GetIcCardData()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
            finally
            {
                // 여전법 대응////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref sRsvStr);
                //////////////////////////////////////////////////////////////////////////////////
            }
            return false;
        }
        #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_bSearchSuccess = false;
            }
            catch 
            {
            }
        }
        #endregion




    }
}