using System;
using System.Drawing;
using System.Windows.Forms;

using Cosmos.BaseFrame;
using Cosmos.UserFrame;
using Cosmos.ServiceProvider;
using Cosmos.Common;
using Cosmos.CommonManager;
using System.Collections;
using System.Text;

namespace Cosmos.Win
{
    public partial class frmSFCCard : frm_PayMainBack
    {
        #region 변수 선언

        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 IDataProcessUs m_cDataSrv = null;
        private IPaymentUs m_cCreditCard = null;
        private ICampaignUs m_cCampaingMain = null;                                 // 캠페인 관리
        private IICReaderUs m_cICReader = null;                                     // IC리더기
        private ISignPadUs m_cSignPad = null;                                       // 사인패드
        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스
        private IPaymentUs m_cSamsungFamily = null;                                 // SFC 할인


        private DeviceStatus m_cDevStatus = new DeviceStatus();                     // 디바이스 관리
        private PosOLEDevice.DelegateOlePos delegatePos;
        private PosOLEDevice.DelegateIcReader delegateReader;                       // IC리더 콜백
        //#20170918 IC 콜백 함수 변경 start
        //포인트창에서 해피제휴 신용카드 리딩시 IC 우선 거래로 인해 '카드를 읽혀 주세요' 팝업 나오는 현상 수정.
        /*
        private PosOLEDevice.CallbackIc delegateReaderCardInfo;                     // IC리더 콜백(CardInfo)
        private string m_sFallDiv;                                                  //FallBack구분
        */
        //#20170918 IC 콜백 함수 변경 end

        private bool m_bApproval;                                                   //중복 승인 방지 체크
        private bool m_bCardInPut;                                                  //카드 입력 중복 방지
        private string m_InputType = "";                                            //입력구분
        private string m_sCardNo;                                                   //입력 카드 번호
        private string m_sIcChip = "";                                                //IC CHIP DATA(EMV)
        private string m_sFallback = "";
        private string m_sServiceCode;                                              //서비스코드

        private double m_dCreditCardDcAtm = 0;
        private double m_nRemainPayAmt = 0;
        private string m_sPosMenuKey;

        public string SetPosMenuKey { set { this.m_sPosMenuKey = value; } }         // POS 기능키

        #endregion 변수 선언

        #region 생성자 & 소멸자
        public frmSFCCard()
        {
            InitializeComponent();

            base.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw, true);
            //this.UpdateStyles();

            m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
            m_cTrnStatus = (TranStatus)StateObject.TRAN;    // POS 거래정보
            m_cDevStatus = (DeviceStatus)StateObject.DEVICE;

#if !DEVICE_MSR_VER                       
            m_cCreditCard = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.CREDITCARD);
#else
            m_cCreditCard = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.MSRCARD);
#endif
            m_cDataSrv = (IDataProcessUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_SERVICE);
            m_cICReader = (IICReaderUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_ICREADER);
            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);

            m_cSamsungFamily = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.SAMSUNG_FAMILY_CARD);

            delegatePos = new PosOLEDevice.DelegateOlePos(OnDeviceEvent);
            delegateReader = new PosOLEDevice.DelegateIcReader(OnIcReaderCallBack);     // IC리더 콜백
            //#20170918 IC 콜백 함수 변경 start
            //포인트창에서 해피제휴 신용카드 리딩시 IC 우선 거래로 인해 '카드를 읽혀 주세요' 팝업 나오는 현상 수정.
            //delegateReaderCardInfo = new PosOLEDevice.CallbackIc(OnIcReaderCallBackCardInfo);     // IC리더 콜백(CardInfo)
            //#20170918 IC 콜백 함수 변경 end

        }

        private void frmSFCCard_Load(object sender, EventArgs e)
        {
            UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "");
            InitControl();

            tmrIcCard.Tag = "";
            tmrIcCard.Enabled = true;   // IC리더 콜백 설정
        }

        private void frmSFCCard_FormClosing(object sender, FormClosingEventArgs e)
        {
            tmrIcCard.Tag = "CLOSE";

            UnRegIcCallback();          // IC리더 콜백 해지
            InDataToZeroFill();
            UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", lblTitle.Text);
        }

        private void frmSFCCard_Activated(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(delegatePos);
        }
        private void frmSFCCard_Deactivate(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(null);
        }

        #endregion 생성자 & 소멸자

        #region 폼 컨트롤 초기화
        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            try
            {

                this.Location = new Point(0, 50);
                this.Size = new Size(1024, 525);

                //this.BackColor = Color.FromArgb(114, 114, 114);
                //picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_S);
                FormManager.SetFormAllControlFont(this, m_cPosStatus.Base.FONT);
                FormManager.SetTextBoxGlobalInfo(this, m_cPosStatus.Global.m_stCultureMaster.nGroupingDigits, m_cPosStatus.Global.m_stCultureMaster.strGroupingSymbol
                    , m_cPosStatus.Global.m_stCultureMaster.nDecimalDigits, m_cPosStatus.Global.m_stCultureMaster.strDecimalSymbol);

                btnExit.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BTN_CLOSE);
                if (btnExit.Image != null) btnExit.Text = "";

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0170);
                lblCardNo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0051);

                btnSearch.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0004);
                btnEnter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0057);
                btnCatApp.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0854);

                lblMsg.Text = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0242).Replace("\n", "").Replace("$$", "\n");

                InitPayMainBack(m_cPosStatus, m_cDataCommon, m_sPosMenuKey, PosConst.MOT_MSG_TYPE.PAY_STEP_3, "");

                // 기능 버튼 설정 체크
                FormManager.SetbtnMenu(null, m_cDevStatus.ICReader.UseYn, btnMenu1, btnMenu2, btnMenu3, btnMenu4);

                txtCardNo.Text = "";
                m_sCardNo = "";
                m_sIcChip = "";
                m_sFallback = "";
                m_InputType = "";

                GetCreditDcAmt();

                m_bCardInPut = false;

                txtCardNo.ReadOnly = false;
                btnCatApp.Visible = false;

                btnSearch.Visible = true;

                if (m_cDevStatus.CatTerminal.UseYn == true)
                {
                    btnCatApp.Visible = true;
                    btnSearch.Visible = false;

                    if (m_cPosStatus.Base.OlePosCATModel == PosConst.CAT_MODEL_DIV._KOR_SPCN)
                    {
                        txtCardNo.ReadOnly = true;
                    }
                }
                
                if (m_cDevStatus.ICReader.UseYn == true)     // 여신전문금융업법 적용여부 체크
                {
                    txtCardNo.MaxLength = 24;
                }
                else
                {
                    // MSR
                    txtCardNo.MaxLength = 40;
                }

                btnEnter.Visible = false;
                txtCardNo.Select();

            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        #endregion

        #region Control Event


        #region 버튼 입력 처리
        /// <summary>
        /// 버튼 입력 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnProc_Click(object sender, EventArgs e)
        {
            try
            {
                if (((Cosmos.UI.CsmButton)sender) == btnSearch) // 조회
                {
                    txtEditBox_EditBoxKeyDownEvent(null, PosKey.MENU_KEY.SEARCH);
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnEnter) // 승인
                {
                    txtEditBox_EditBoxKeyDownEvent(null, PosKey.MENU_KEY.APPROVAL);
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnCatApp) // cat단말기 승인
                {
                    txtEditBox_EditBoxKeyDownEvent(null, PosKey.MENU_KEY.CAT_TERMINAL);
                }
                padInPut.SetActiveFocus();
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion

        #region 텍스트박스 활성화 처리
        /// <summary>
        /// 텍스트박스 활성화 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtEditBox_EnterEvent(object sender, EventArgs e)
        {
            try
            {
                padInPut.SetActiveControl = (Control)sender;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion

        #region 텍스트박스 키 입력 이벤트 처리
        /// <summary>
        /// 텍스트박스 키 입력 이벤트 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="sFuncValue"></param>
        private void txtEditBox_EditBoxKeyDownEvent(object sender, string sFuncValue)
        {
            try
            {
                if (sFuncValue == PosKey.MENU_KEY.ENTER)
                {

                    if (((Cosmos.UI.CsmPosEditBox)sender) == txtCardNo)
                    {
                        if (txtCardNo.Text != "")
                        {
                            if (CheckTxtInPut(txtCardNo) == false) return;

                            if (m_cDevStatus.ICReader.UseYn != true)             // 여전법 인증여부(0:MSR, 1:IC)
                            {
                                m_sCardNo = m_cDataCommon.MSR_CardNoCheck(txtCardNo.Value, "", ref m_InputType);
                            }
                            else
                            {
                                if (m_sCardNo != "")
                                {
                                    m_InputType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_KEYIN;
                                    m_sCardNo = EncryptedCardNo(txtCardNo.Value);
                                }
                            }

                        }
                        else
                        {
                            if (m_cDevStatus.ICReader.UseYn != true)             // 여전법 인증여부(0:MSR, 1:IC)
                            {
                                if (CheckTxtInPut(txtCardNo) == false) return;
                            }
                            else
                            {
                                if (m_bCardInPut == true) return;
                                m_bCardInPut = true;

                                if (GetCardInfo(true) == true)
                                {

                                    //CardDataDisplay();

                                }
                                else
                                {
                                    //카드 입력 에러 다시 입력 하세요.
                                    txtCardNo.Select();
                                    m_bCardInPut = false;
                                    return;

                                }
                                m_bCardInPut = false;
                            }
                        }
                        btnSearch.Focus();
                        txtEditBox_EditBoxKeyDownEvent(null, PosKey.MENU_KEY.SEARCH);
                        txtCardNo.Focus();
                    }

                }
                else if (sFuncValue == PosKey.MENU_KEY.CLEAR)
                {
                    if (((Cosmos.UI.CsmPosEditBox)sender).ReadOnly == false)
                    {
                        if (((Cosmos.UI.CsmPosEditBox)sender) == txtCardNo)
                        {
                            txtCardNo.Text = "";
                            m_sCardNo = "";
                            m_sIcChip = "";
                            m_sFallback = "";
                            m_InputType = "";

                            m_bCardInPut = false;

                            btnEnter.Visible = false;
                            tmrIcCard.Enabled = true;
                        }
                    }
                }
                else if (sFuncValue == PosKey.MENU_KEY.ESC_PREVIOUS)
                {
                    this.DialogResult = DialogResult.Cancel;
                    this.Close();
                }
                else if (sFuncValue == PosKey.MENU_KEY.APPROVAL)
                {
                    if (CheckTxtInPut(null) == false) return;
                    CompleteTxtInPut(1);
                }
                else if (sFuncValue == PosKey.MENU_KEY.CAT_TERMINAL)
                {
                    if (CheckPayMentItem() == true) return;
                    CompleteTxtInPut(3);
                }
                else if (sFuncValue == PosKey.MENU_KEY.SEARCH)
                {
                    if (CheckTxtInPut(null) == false) return;
                    if (CheckPayMentItem() == true) return;
                    CompleteTxtInPut(2);
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion

        #region 텍스트박스 입력 유효성 체크
        /// <summary>
        /// 텍스트박스 입력 유효성 체크
        /// </summary>
        /// <param name="sender"></param>
        /// <returns></returns>
        private bool CheckTxtInPut(object sender)
        {
            try
            {
                // 특정 문자값 제거
                try
                {
                    if (m_cDevStatus.Msr.STX != "" && txtCardNo.Value.StartsWith(m_cDevStatus.Msr.STX)) txtCardNo.Value = txtCardNo.Value.Substring(1);

                    int iLastEtx = txtCardNo.Value.LastIndexOf(m_cDevStatus.Msr.ETX);
                    if (m_cDevStatus.Msr.ETX != "" && iLastEtx > 0) txtCardNo.Value = CmUtil.MidH(txtCardNo.Value, 0, iLastEtx);
                }
                catch { }

                // 카드번호 길이 체크
                if (sender == null || ((Cosmos.UI.CsmPosEditBox)sender) == txtCardNo)
                {
                    if (txtCardNo.Value.Length < 6)
                    {
                        if (m_cDevStatus.CatTerminal.UseYn == true && m_cPosStatus.Base.OlePosCATModel == PosConst.CAT_MODEL_DIV._KOR_SPCN)
                        {
                            WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0682);
                        }
                        else
                        {
                            WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0037);
                        }

                        txtCardNo.Text = "";
                        return false;
                    }
                }

            }
            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 false;
            }
            return true;
        }
        #endregion

        #region 텍스트박스 입력 완료 처리
        /// <summary>
        /// 텍스트박스 입력 완료 처리
        /// </summary>
        /// <param name="nFlowMode"></param>
        /// <returns></returns>
        private bool CompleteTxtInPut(int nFlowMode)
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                if (nFlowMode == 1) // 신용카드 승인 처리
                {

                    //승인 정상 유무 체크


                    //결제수단생성(할인)


                    this.DialogResult = DialogResult.OK;
                    this.Close();

                }
                else if (nFlowMode == 2)
                {
                    //조회
                    // 중복 승인 방지 체크
                    if (m_bApproval == true) return false;
                    m_bApproval = true;

                    sRet = CreditCardApproval();
                    m_bApproval = false;

                    if (sRet != UserCom.RST_OK)
                    {
                        padInPut.SetActiveFocus();
                        return false;
                    }

                }
                else if (nFlowMode == 3)    //cat단말기
                {
                    //조회
                    // 중복 승인 방지 체크
                    if (m_bApproval == true) return false;
                    m_bApproval = true;

                    sRet = CatTerminalApproval();
                    m_bApproval = false;

                    if (sRet != UserCom.RST_OK)
                    {
                        padInPut.SetActiveFocus();
                        return false;
                    }

                    this.DialogResult = DialogResult.Ignore;
                    this.Close();
                }

            }
            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 false;
            }
            return true;
        }
        #endregion


        #endregion Control Event

        #region User Method


        #region 카드데이터 화면 표시
        /// <summary>
        /// 카드데이터 화면 표시
        /// </summary>
        /// <returns></returns>
        private void CardDataDisplay()
        {
            try
            {

            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion

        #region 카드번호 조회
        /// <summary>
        /// 카드번호 조회
        /// <param name="sCardData"></param>
        /// <param name="bMenual"></param>
        /// <param name="sUniEtcData"></param>
        /// </summary>
        /// <returns></returns>
        private bool CardSearch(string sCardData, bool bMenual, string sUniEtcData, bool bNFCCard)
        {
            try
            {
                //조회 필요시 처리
            }
            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 false;
            }
            return true;
        }
        #endregion

        #region 신용카드 승인 처리
        /// <summary>
        /// 신용카드 승인 처리
        /// <param name=""></param>
        /// </summary>
        /// <returns></returns>
        private string CreditCardApproval()
        {

            string sRet = UserCom.RST_ERR;
            try
            {
                //0:마스킹 카드번호 1:입력구분 2:카드번호 3:할부개월 4:총금액 5:봉사료
                //6:세금 7:비밀번호 8:신용카드종류 9:칩데이터 10:사인
                //11:Fallback구분 12:제휴할인금액 13:원승인번호 14:원승인일자 15:아이템코드
                //16:매입사코드 17:매입사명 18:할인카드구분 19:할인금액 20:승인구분, 21:매체구분, 22:서비스코드

                string[] aParam = new string[] { 
                        PosConst.CREDITCARD_SEARCH_TYPE.SFC, m_InputType, m_sCardNo, "00", "1", "0","0", "","", m_sIcChip, "",m_sFallback, "0","","","", "","","","","","","" };

                string[] aRet = new string[1];


                //승인처리
                sRet = m_cCreditCard.SearchPayment(aParam, ref aRet);

                //if(1 == 1)
                //{

                //    btnEnter.Visible = true;
                //    WinManager.ConfirmMessage("테스트 무조건 정상! 승인 버튼 누른후 결제 진행");
                //    return "" ;
                //}


                if (sRet == UserCom.RST_OK)
                {
                    if (aRet[0] == "Y")
                    {


                        string sMsg = string.Format(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0594), m_cPosStatus.Global.NumericTOCurrency(m_dCreditCardDcAtm), m_cPosStatus.Global.NumericTOCurrency(m_nRemainPayAmt));

                        if (WinManager.QuestionMessage(sMsg) == true)
                        {
                            m_cSamsungFamily.SetPayment(new string[] { txtCardNo.Value, m_dCreditCardDcAtm.ToString() });
                            PayMentDisplay();

                            //// 정상
                            //btnEnter.Visible = true;
                            //WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0126);

                            txtEditBox_EditBoxKeyDownEvent(null, PosKey.MENU_KEY.APPROVAL);

                        }

                    }
                    else
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0125);
                    }
                }
                else
                {
                    WinManager.ErrorMessage(sRet);
                }
            }
            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 sRet;
        }

        /// <summary>
        /// cat단말기
        /// </summary>
        /// <returns></returns>
        private string CatTerminalApproval()
        {

            string sRet = UserCom.RST_ERR;
            try
            {

                string[] aRet = new string[1];

                //InParam
                // 0.전문구분,1.거래유형, 2.할부개월, 3.승인금액 , 4.봉사료, 5.세금, 6.원승인번호, 7.원거래일자, 8.포인트거래구분, 9.상품코드,
                //10.전표인쇄여부, 11.추가항목, 12.제휴할인코드, 13.제휴할인금액, 14.예비1, 15.예비2

                //승인처리                                                   0,                                           1,                            2,    3,  4,  5,  6,  7,  8,  9, 10, 11,                     12,              13,  14, 15 
                sRet = m_cCreditCard.SearchPayment(new string[] { PosConst.POS_CAT_MASTER.TRAN_TYPE, PosConst.POS_CAT_MASTER.TRADE_ID.CAT_CARD_AGREE, "00", "1", "", "", "", "", "", "", "", "", PosConst.CREDITCARD_SEARCH_TYPE.SFC, "0", "", "" }, ref aRet);

                if (sRet != UserCom.RST_OK)
                {
                    if (sRet == UserCom.RST_IGNORE) WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0125);
                    return sRet;
                }

                if (aRet[0] == PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_IC)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0633);
                }

                string sMsg = string.Format(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0594), m_cPosStatus.Global.NumericTOCurrency(m_dCreditCardDcAtm), m_cPosStatus.Global.NumericTOCurrency(m_nRemainPayAmt));

                if (WinManager.QuestionMessage(sMsg) == true)
                {

                    // 할인 저장!
                    m_cSamsungFamily.SetPayment(new string[] { txtCardNo.Value, m_dCreditCardDcAtm.ToString() });
                    PayMentDisplay();


                    //승인처리                                                   0,                                           1,                        2,            3,                 4,  5,  6,  7,  8,  9, 10, 11,                     12,                              13,               14, 15 
                    sRet = m_cCreditCard.SetPayment(new string[] { PosConst.POS_CAT_MASTER.TRAN_TYPE, PosConst.POS_CAT_MASTER.TRADE_ID.CAT_CARD_AGREE, "00", m_nRemainPayAmt.ToString(), "", "", "", "", "", "", "", "", ItemConst.CREDITCARD_DC_TY.CREDIT_SFC, m_dCreditCardDcAtm.ToString(), "", "", "", "" });

                    if (sRet != UserCom.RST_OK)
                    {
                        if (sRet != UserCom.RST_ERR)   //에러 코드만일때는 메세지 표기 안함!
                            WinManager.ErrorMessage(sRet);

                        sRet = 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);
            }
            return sRet;
        }


        #endregion 신용카드 승인 처리

        #region 카드 조회

        /// <summary>
        /// 조회
        /// </summary>
        /// <returns></returns>
        private string SearchApproval()
        {

            string sRet = UserCom.RST_ERR;


            //0:마스킹 카드번호 1:입력구분 2:카드번호 3:할부개월 4:총금액 5:봉사료
            //6:세금 7:비밀번호 8:신용카드종류 9:칩데이터 10:사인
            //11:Fallback구분 12:제휴할인금액 13:원승인번호 14:원승인일자 15:아이템코드
            //16:매입사코드 17:매입사명 18:할인카드구분 19:할인금액 20:승인구분, 21:매체구분, 22:서비스코드

            try
            {
                //승인처리
                sRet = m_cCreditCard.SetPayment(new string[] { 
                    txtCardNo.Value, m_InputType, m_sCardNo, "00", "1", "0", "0", "", "", m_sIcChip, "", m_sFallback, "0","","","", "","","","","","" });

            }
            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 sRet;
            }
            return sRet;
        }
        #endregion

        /// <summary>
        /// 카드 번호 암호화
        /// </summary>
        /// <param name="sIndata"></param>
        /// <returns></returns>
        private string EncryptedCardNo(string sIndata)
        {
            string tmpEnc = sIndata;

            try
            {

                tmpEnc = m_cICReader.GetEncryptedCardNo(sIndata).Trim();

                if (CmUtil.MidH(tmpEnc, 0, 2) == "00")
                {
                    tmpEnc = CmUtil.MidH(tmpEnc, 2, 512).Trim();
                }
                else
                {
                    //암호화 처리 실패!
                }

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

        }

        ///// <summary>
        ///// 카드 정보 입력 처리
        ///// </summary>
        ///// <returns></returns>
        //private bool GetCardInfo()
        //{
        //    bool bRet = false;

        //    try
        //    {
        //        txtCardNo.Value = "";
        //        string sRsvStr = "";

        //        m_sCardNo = "";
        //        m_InputType = "";
        //        m_sIcChip = "";
        //        m_sFallback = "";

        //        if (m_cICReader.GetCardInfo_ICReader(PosConst.IC_READER_TRAN_TYPE.CREDIT, 1, ref sRsvStr) == true)
        //        {

        //            if (CmUtil.MidH(sRsvStr, 0, 2) == "00")
        //            {

        //                m_sCardNo = CmUtil.MidH(sRsvStr, 6, 512).Trim();

        //                txtCardNo.Value = CmUtil.MidH(sRsvStr, 1030, 37).Trim();

        //                m_sIcChip = CmUtil.MidH(sRsvStr, 518, 512).Trim();

        //                if (CmUtil.MidH(sRsvStr, 4, 2).Trim() == "02")
        //                {
        //                    m_InputType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_SWIP;
        //                }
        //                else
        //                {
        //                    m_InputType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_IC;
        //                }
        //                m_sFallback = CmUtil.MidH(sRsvStr, 3, 1); // == "3" ? "0" : "1";
        //                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;

        //}


        /// <summary>
        /// 카드 할인 대상 금액 조회
        /// </summary>
        private void GetCreditDcAmt()
        {
            try
            {
                m_dCreditCardDcAtm = 0;

                double dItem = 0;
                double dTarget = 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;                              // 할인가능 여부 

                    dItem = CmUtil.DoubleAdd(dItem, cSaleItem.SALE_AMT);
                }

                if (dItem > m_cTrnStatus.Sale.RemainPayAmt)
                    dTarget = m_cTrnStatus.Sale.RemainPayAmt;
                else
                    dTarget = dItem;

                dTarget = CmUtil.DoubleDivision(CmUtil.DoubleMultiplication(dTarget, 10), 100);

                //할인 대상 금액 계산
                m_dCreditCardDcAtm = CmUtil.MathRounds(dTarget, m_cPosStatus.Mst.DcRudDwLocMethd, CmUtil.IntParse(m_cPosStatus.Mst.DcRudDwLoc));
                m_nRemainPayAmt = CmUtil.DoubleSubtraction(m_cTrnStatus.Sale.RemainPayAmt, m_dCreditCardDcAtm);

            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }

        }

        /// <summary>
        /// 할인 등록 여부 체크
        /// </summary>
        /// <returns></returns>
        private bool CheckPayMentItem()
        {

            bool bRet = false;

            try
            {
                ArrayList aPayItem = (ArrayList)StateObject.GetItemObject(Column.TR_PAYMENT.ITEM);

                foreach (Column.TR_PAYMENT.DATA cPayItem in aPayItem)
                {
                    if (cPayItem.PAY_WAY_CD == ItemConst.TR_ITEM_ID.EMP_DC_ITEM && cPayItem.PAY_DTL_CD_01 == ItemConst.TR_ITEM_ID.EMP_DC.SAMSUNGCARD && cPayItem.CANCEL_DIV == PosConst.CANCEL_DIV.NORMAL)
                    {

                        MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0669);
                        bRet = true;
                        break;
                    }
                }

            }
            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;
        }
        /// <summary>
        /// 할인 수단 화면 표시
        /// </summary>
        private void PayMentDisplay()
        {
            try
            {
                // 판매화면
                IFormSaleMainUs cFormSaleMain = (IFormSaleMainUs)FormManager.GetForm(FormManager.FORM_SAL_MAIN);
                cFormSaleMain.DisplayPayment();           // 결제등록정보 화면표시
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }


        #endregion User Method

        #region DeviceEvent 관련
        /// <summary>
        /// DeviceEvent 관련
        /// </summary>
        /// <param name="sDevice"></param>
        /// <param name="sData1"></param>
        /// <param name="sData2"></param>
        /// <param name="sData3"></param>
        public void OnDeviceEvent(string sDevice, string sData1, string sData2, string sData3)
        {
            try
            {
                switch (sDevice)
                {
                    case PosConst.OPOS_DEVICE.MSR:
                        this.Invoke(new EventHandler(OnMSREvent));
                        break;
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        #region MSR Event
        /// <summary>
        /// MSR Event
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnMSREvent(object source, EventArgs e)
        {
            try
            {
                //if (m_cMultiCard == null)
                //{
                //    bool bRet = CardSearch(m_cDevStatus.Msr.Track2Data, false, "", false);
                //    if (bRet == false)
                //    {
                //        txtCardNo.Text = "";
                //        txtCardNo.Select();
                //    }
                //}
                //else
                //{
                //   //WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_1410);
                //    return;
                //}
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion MSR Event


        private void btnExit_Click(object sender, EventArgs e)
        {
            try
            {
                txtEditBox_EditBoxKeyDownEvent(null, PosKey.MENU_KEY.ESC_PREVIOUS);
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);

            }


        }

        #endregion DeviceEvent 관련


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

                //여전법 대응!
                //////////////////////////////////////////////////////////////////////////////////
                CmUtil.ZeroFillClear(ref m_sCardNo);
                CmUtil.ZeroFillClear(ref m_sIcChip);
                //////////////////////////////////////////////////////////////////////////////////

                txtCardNo.Value = string.Empty;
            }
            catch (Exception) { }

        }
        #endregion 여전법 대응

        #region 카드 정보 입력 처리
        /// <summary>
        /// 카드 정보 입력 처리
        /// </summary>
        /// <returns></returns>
        private bool GetCardInfo(bool bCancelCallBack)
        {
            return GetCardInfo(bCancelCallBack, true);
        }
        private bool GetCardInfo(bool bCancelCallBack, bool bEnableCallBack)
        {
            bool bRet = false;
            string sRsvStr = "";

            try
            {
                if (bCancelCallBack == true) UnRegIcCallback(); // IC리더 콜백 해지

                txtCardNo.Value = "";

                m_sCardNo = "";
                m_InputType = "";
                m_sIcChip = "";
                m_sFallback = "";
                m_sServiceCode = "";

                if (m_cICReader.GetCardInfo_ICReader(PosConst.IC_READER_TRAN_TYPE.CREDIT, (int)1, ref sRsvStr) == true)
                {
                    if (CmUtil.MidH(sRsvStr, 0, 2) == "00")
                    {
                        m_sCardNo = CmUtil.MidH(sRsvStr, 6, 512).Trim();
                        txtCardNo.Value = CmUtil.MidH(sRsvStr, 1030, 37).Trim();
                        m_sIcChip = CmUtil.MidH(sRsvStr, 518, 512).Trim();
                        if (CmUtil.MidH(sRsvStr, 4, 2).Trim() == "02")
                        {
                            m_InputType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_SWIP;
                        }
                        else
                        {
                            m_InputType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_IC;
                        }

                        m_sServiceCode = CmUtil.MidH(sRsvStr, 1067, 5).Trim();

                        m_sFallback = CmUtil.MidH(sRsvStr, 3, 1); // == "3" ? "0" : "1";
                        bRet = true;
                    }
                }

                if (bEnableCallBack == true)
                {
                    if (txtCardNo.Value == "") tmrIcCard.Enabled = true;       // IC리더 콜백 설정
                }
            }
            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 sRsvStr);
            }

            return bRet;

        }
        #endregion

        #region IC리더 콜백 관련
        /// <summary>
        /// IC리더 콜백 설정
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tmrIcCard_Tick(object sender, EventArgs e)
        {
            try
            {
                if (m_cDevStatus.ICReader.UseYn != true)             // 여전법 인증여부(0:MSR, 1:IC)
                {
                    tmrIcCard.Enabled = false;
                    return;
                }

                if (tmrIcCard.Tag == null || tmrIcCard.Tag.ToString() == "")
                {
                    // IC리더 콜백 설정
                    if (m_bCardInPut) return;

                    tmrIcCard.Enabled = false;

                    //#20170918 IC 콜백 함수 변경 start
                    //포인트창에서 해피제휴 신용카드 리딩시 IC 우선 거래로 인해 '카드를 읽혀 주세요' 팝업 나오는 현상 수정.
                    //기존
                    m_cICReader.RegIcCallback(delegateReader);
                    //변경
                    //string sApprID = PosMstManager.GetMstVan(ItemConst.TR_ITEM_ID.CREDITCARD_ITEM, ItemConst.TR_ITEM_ID.CREDITCARD.CREDIT_CARD, PosMst.MST_VAN.DATA.APPR_ID);
                    //m_cICReader.RegIcCallbackCardInfo(sApprID, m_cDataSrv.IntParse("0"), delegateReaderCardInfo);
                    //#20170918 IC 콜백 함수 변경 end
                }
                else if (tmrIcCard.Tag.ToString() == "MSR")
                {
                    // MSR 카드 읽기
                    tmrIcCard.Enabled = false;
                    tmrIcCard.Tag = "";
                    tmrIcCard.Interval = 500;

                    CardDataDisplay();

                    tmrIcCard.Enabled = true;
                }
                else if (tmrIcCard.Tag.ToString() == "IC")
                {
                    // IC리더 카드 읽기
                    tmrIcCard.Enabled = false;
                    tmrIcCard.Tag = "";

                    if (GetCardInfo(false) == true)
                    {
                        CardDataDisplay();
                    }
                }
                else
                    tmrIcCard.Enabled = false;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        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
            {
                if (txtCardNo.InvokeRequired)
                {
                    DelegateIcReaderCallBack d = new DelegateIcReaderCallBack(OnIcReaderCallBack);
                    this.Invoke(d, new object[] { num, str });
                }
                else
                {
                    if (m_bCardInPut) return;
                    m_bCardInPut = true;

                    if (num == 1)
                    {
                        // IC 카드
                        tmrIcCard.Tag = "IC";
                        tmrIcCard.Interval = 100;
                    }
                    else
                    {
                        // MSR 카드
                        if (str.ToString().StartsWith("EN") == true)
                        {
                            m_InputType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_SWIP;
                            m_sCardNo = CmUtil.MidH(str.ToString(), 0, 512).Trim();
                            txtCardNo.Value = CmUtil.MidH(str.ToString(), 512, 40).Trim();
                            m_sServiceCode = CmUtil.MidH(str.ToString(), 552, 5).Trim();
                            m_sFallback = "0";

                            tmrIcCard.Tag = "MSR";
                            tmrIcCard.Interval = 100;
                        }
                        else
                        {
                            tmrIcCard.Interval = 500;
                        }
                    }
                    tmrIcCard.Enabled = true;

                    m_bCardInPut = false;
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
                m_bCardInPut = false;
            }
        }

        /// <summary>
        /// IC리더 콜백 해지
        /// </summary>
        private void UnRegIcCallback()
        {
            try
            {
                if (m_cDevStatus.ICReader.UseYn == true)     // 여신전문금융업법 적용여부 체크
                {
                    tmrIcCard.Enabled = false;

                    //#20170918 IC 콜백 함수 변경 start
                    //포인트창에서 해피제휴 신용카드 리딩시 IC 우선 거래로 인해 '카드를 읽혀 주세요' 팝업 나오는 현상 수정.
                    //기존
                    m_cICReader.UnRegIcCallback();
                    //변경
                    //m_cICReader.UnRegIcCallbackCardInfo();
                    //#20170918 IC 콜백 함수 변경 end
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        //#20170918 IC 콜백 함수 변경 start
        //포인트창에서 해피제휴 신용카드 리딩시 IC 우선 거래로 인해 '카드를 읽혀 주세요' 팝업 나오는 현상 수정.
        /*
        delegate void DelegateWriteLog(int returnValue, StringBuilder returnData);
        /// <summary>
        /// IC리더 콜백 함수(CardInfo)
        /// </summary>
        /// <param name="returnValue"></param>
        /// <param name="returnData"></param>
        public void OnIcReaderCallBackCardInfo(int returnValue, StringBuilder returnData)
        {
            if (txtCardNo.InvokeRequired)
            {
                DelegateWriteLog d = new DelegateWriteLog(OnIcReaderCallBackCardInfo);
                this.Invoke(d, new object[] { returnValue, returnData });
            }
            else
            {
                if (m_bCardInPut) return;
                m_bCardInPut = true;

                if (returnValue > 0)
                {
                    string sRsvStr = returnData.ToString();
                    if (CmUtil.MidH(sRsvStr, 0, 2) == "00")
                    {
                        m_sCardNo = CmUtil.MidH(sRsvStr, 6, 512).Trim();
                        txtCardNo.Value = CmUtil.MidH(sRsvStr, 1030, 37).Trim();
                        m_sIcChip = CmUtil.MidH(sRsvStr, 518, 512).Trim();
                        if (CmUtil.MidH(sRsvStr, 4, 2).Trim() == "02")
                        {
                            m_InputType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_SWIP;
                        }
                        else
                        {
                            m_InputType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_IC;
                        }
                        m_sServiceCode = CmUtil.MidH(sRsvStr, 1067, 5).Trim();
                        m_sFallDiv = CmUtil.MidH(sRsvStr, 3, 1); // == "3" ? "0" : "1";

                        // IC 카드(CardInfo)
                        tmrIcCard.Tag = "ICREADER";
                        tmrIcCard.Interval = 100;
                        tmrIcCard.Enabled = true;

                        m_bCardInPut = false;
                    }
                }
            }

        }
        */
        //#20170918 IC 콜백 함수 변경 end

        #endregion

    }
}
