
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 System.Collections;
using SPC.Kiosk.Common;
namespace SPC.Kiosk.Payments
{
    /// <summary>
    /// POS HappyPoint Approval Process
    /// </summary>
    public class posPaymentsCancel : IDisposable
    {
        #region [ Members ]
        /// <summary>
        /// HappyPointCertify ErrorCode
        /// </summary>
        public enum ErrorCode
        {
            posPaymentsCancelNotInitailzedError,
            posPaymentsCancelProcessingTimeOut,
            posPaymentsCancelPaymentSEQError,
            posPaymentsCancelCanceledItemError,
            posPaymentsCancelNotFoundError,
            posPaymentsCancelUnknownError,
        }
        /// <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 IPaymentUs m_cPayCancel = null;


        /// <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 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.posPaymentsCancelProcessingTimeOut);
                }
            }
        }
        #endregion

        #region [ Ctor  && Dispose ]
        /// <summary>
        /// Ctor
        /// </summary>
        public posPaymentsCancel()
        {
            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;
                }
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "Ctor", "Fail", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            try
            {

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

                m_cPayCancel = 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 StartProcessing(long _paySeq)
        {
            try
            {
                CommonLog.InfoLogWrite(this, "StartProcessing()", string.Format("Start [{0}]", _paySeq));
                SendReadStart();
                if (NeedInitModule)
                {
                    Thread.Sleep(1000); //진행창 보이기 위한 딜레이
                    ErrorEvent(ErrorCode.posPaymentsCancelNotInitailzedError);
                }
                else
                {
                    var startPorcess = false;
                    var payRowNo = -1;
                    if (_paySeq > 0)
                    {
                        m_cTrnStatus.Head.TradeDiv = ItemConst.TRAN_DIV.NORMAL;
                        ArrayList alPayItem = (ArrayList)StateObject.GetItemObject(Column.TR_PAYMENT.ITEM);
                        foreach (var aPayItme in alPayItem)
                        {
                            if (aPayItme is Column.TR_PAYMENT.DATA findPayItem
                                && findPayItem.SEQ.Equals(_paySeq))
                            {
                                payRowNo = alPayItem.IndexOf(aPayItme);
                                if (!findPayItem.CANCEL_DIV.Equals(ItemConst.PAY_CANCEL_DIV.CANCEL))
                                {
                                    startPorcess = true;
                                }
                                else
                                {
                                    SendErrLogEvent(ErrorCode.posPaymentsCancelCanceledItemError);
                                }
                                break;
                            }
                        }
                        if (!startPorcess && payRowNo < 0)
                        {
                            SendErrLogEvent(ErrorCode.posPaymentsCancelNotFoundError);
                        }
                        else
                        {
                            //승인 취소 처리
                            CompleteTxtInPut(payRowNo);
                            if (m_bSearchSuccess)
                            {
                                alPayItem.RemoveAt(payRowNo);
                            }
                        }
                    }
                    else
                    {
                        SendErrLogEvent(ErrorCode.posPaymentsCancelPaymentSEQError);  
                    }

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

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

        /// <summary>
        /// 승인 취소 처리
        /// </summary>
        /// <returns></returns>
        private void CompleteTxtInPut(int _rowNo)
        {
            CommonLog.DebugLogWrite(this, "CompleteTxtInPut()", "Start");
            string sRet = UserCom.RST_ERR;
            try
            {
                m_bSearchSuccess = false;
                m_cPayCancel = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.PAYMENTCANCEL);
                var alPayItem = (ArrayList)StateObject.GetItemObject(Column.TR_PAYMENT.ITEM);
                var cPayItem = (Column.TR_PAYMENT.DATA)alPayItem[_rowNo];

                // 포인트 사용 승인 처리
                sRet = m_cPayCancel.CancelPayment(new string[] { cPayItem.PAY_WAY_CD, cPayItem.PAY_DTL_CD_01, _rowNo.ToString() });
                if (sRet != UserCom.RST_OK)
                {
                    if (sRet == null || sRet.Equals(UserCom.RST_ERR))
                    {
                        SendErrLogEvent(ErrorCode.posPaymentsCancelUnknownError);
                    }
                    else
                    {
                        SendErrorMessageEvent(sRet);
                    }
                }
                else
                {
                    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");
        }

        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
            {

            }
        }
        #endregion




    }
}