using System;
using System.Windows.Forms;
using System.Threading;

using Cosmos.BaseFrame;
using Cosmos.UserFrame;
using Cosmos.ServiceProvider;
using Cosmos.Common;
using Cosmos.CommonManager;

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : IC리더기 및 싸인패드 무결성 체크
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Win
{
    public partial class frmIntegrityThead : Form
    {
        #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 IICReaderUs m_cICReader = null;                                     // IC리더기 
        private ISignPadUs m_cDeviceSignPad = null;                                 // RF리더기
        private IDatabaseSQL m_cSqlDbService = null;                                // 데이터베이스 관리

        private bool m_bSecondDisp = false;              // 초 표시여부
        private int  m_nSecondCount = 0;                 // 초(경과)

        private string m_sStatus = "";
        private byte[] m_RF_rep_array = new byte[2049];

        string m_sMessageStr;
        /// <summary>
        /// 화면표시 메시지
        /// </summary>
        public string PosMessageStr
        {
            get { return this.m_sMessageStr; }
            set
            {
                this.m_sMessageStr = value;
                try
                {
                    lblMessage.Text = m_sMessageStr;
                }
                catch { }
            }
        }

        string m_sCheckType;
        /// <summary>
        /// 체크 타입
        /// </summary>
        public string CheckType
        {
            get { return this.m_sCheckType; }
            set { this.m_sCheckType = value; }
        }

        string m_sDevice;
        /// <summary>
        /// 디바이스
        /// </summary>
        public string Device
        {
            get { return this.m_sDevice; }
            set { this.m_sDevice = value; }
        } 

        int m_nRecvRet;
        /// <summary>
        /// 수신리턴값
        /// </summary>
        public int RecvRet
        {
            get { return this.m_nRecvRet; }
            set { this.m_nRecvRet = value; }
        }


        string m_sAutoMode;
        /// <summary>
        /// 수신리턴값
        /// </summary>
        public string AutoMode
        {
            get { return this.m_sAutoMode; }
            set { this.m_sAutoMode = value; }
        }
        #endregion 

        #region 생성자
        public frmIntegrityThead()
        {
            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_cICReader = (IICReaderUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_ICREADER);
            m_cSqlDbService = (IDatabaseSQL)sManager.InitServiceInstance(ServiceLists.AGENT_DATABASE.DLL, ServiceLists.AGENT_DATABASE.DATABASE_MSSQL);
        }

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

                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);
                FormManager.MovePopUpForm(this, false, m_cPosStatus.Sale.ScreenSizeUser);

                picSearchMessage.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.SCH_MESSAGE_BOX);

                if (m_sMessageStr != "") lblMessage.Text = m_sMessageStr;
                
                this.m_nRecvRet = 0;
                this.TopMost = true;

                m_sStatus = "N";
                
                tmrStart.Enabled = true;
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                    "Process Exception !!! " + ex.Message);
            }
        }

        private void frmIntegrityThead_FormClosing(object sender, FormClosingEventArgs e)
        {
            UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "");
        }
        #endregion 
        
        #region OnSecondDisplay
        private void OnSecondDisplay()
        {
            try
            {
                while (m_bSecondDisp == true)
                {
                    m_nSecondCount++;
                    if (m_nSecondCount % 10 == 0)
                    {
                        lblMessage.Text = m_sMessageStr + " (" + (int)(m_nSecondCount / 10) + ")";
                        lblMessage.Update();
                    }
                    Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                    "Process Exception !!! " + ex.Message);
            }
        }
        #endregion 

        #region tmrStart_Tick
        private void tmrStart_Tick(object sender, EventArgs e)
        {
            try
            {
                tmrStart.Enabled = false;

                m_bSecondDisp = true;
                m_nSecondCount = 0;

                Thread thrSecondDisp = new Thread(new ThreadStart(OnICReaderCheck));
                thrSecondDisp.Start();

                OnSecondDisplay();

                //실패시 메세지
                if (m_sStatus == "N")
                {
                    switch (m_sCheckType)
                    {
                        case PosConst.SCFBA_BIZ_TYPE.INTEGRITY:
                            // 무결성 체크                      
                            if (m_sDevice == PosConst.POS_CARD_READER_DEVICE_TYPE.IC_READER)
                                WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0345);
                            else
                                WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0380);
                            break;
                        case PosConst.SCFBA_BIZ_TYPE.CERTIFICATION:
                            // 상호인증                     
                            if (m_sDevice == PosConst.POS_CARD_READER_DEVICE_TYPE.IC_READER)
                                WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0344);
                            else
                                WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0382);
                            break;
                        case PosConst.SCFBA_BIZ_TYPE.BIZDOWNLOAD:
                            string sResMsg = System.Text.Encoding.Default.GetString(m_RF_rep_array);
                            string sViewMsg = "";

                            if (m_sDevice == PosConst.POS_CARD_READER_DEVICE_TYPE.TMONEY)
                            {
                                // 티머니 운영정보 다운로드
                                sViewMsg = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0393);
                                //WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0393);
                            }
                            else if (m_sDevice == PosConst.POS_CARD_READER_DEVICE_TYPE.CASHBEE)
                            {
                                // 캐쉬비 운영정보 다운로드
                                sViewMsg = MessageManager.GetErrorMessage (POS_MESSAGE.ERROR.MSG_0394);
                                //WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0394);
                            }
                            WinManager.ErrorMessage(sViewMsg + "\n" + CmUtil.MidH(sResMsg, 1, CmUtil.LenH(sResMsg))  );
                            break;
                        case PosConst.SCFBA_BIZ_TYPE.OPENSTART:
                            if (m_sDevice == PosConst.POS_CARD_READER_DEVICE_TYPE.TMONEY)
                            {
                                // 티머니 개시
                                WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0322);
                            }
                            else if (m_sDevice == PosConst.POS_CARD_READER_DEVICE_TYPE.CASHBEE)
                            {
                                // 캐쉬비 개시  
                                WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0323);
                            }
                            else if (m_sDevice == PosConst.POS_CARD_READER_DEVICE_TYPE.PAYON)
                            {
                                // PAYON SAM 등록
                                WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0343);
                            }
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                    "Process Exception !!! " + ex.Message);
            }
            finally
            {
                if (m_sStatus == "N") 
                    this.DialogResult = DialogResult.Cancel;
                else 
                    this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }
        #endregion 

        #region OnICReaderCheck
        private void OnICReaderCheck()
        {
            string sRsltTime = "";
            string sRet = UserCom.RST_ERR;
            string sPayDcCd = "";
            string sApprID = "";
            string sBizNm = "";

            try
            {
                m_bSecondDisp = true;
                if (m_cICReader == null) m_cICReader = (IICReaderUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_ICREADER);
                if (m_cDeviceSignPad == null) m_cDeviceSignPad = (ISignPadUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_SIGNPAD);

                m_sStatus = "N";

                switch (m_sCheckType)
                {
                    case PosConst.SCFBA_BIZ_TYPE.INTEGRITY:
                        // 무결성 체크
                        sRet = m_cICReader.IntegrityCheck_ICReader(m_sDevice, ref sRsltTime);
                        break;
                    case PosConst.SCFBA_BIZ_TYPE.CERTIFICATION:

                        // 상호인증
                        string sTerminerID = PosMstManager.GetMstVan(ItemConst.TR_ITEM_ID.CREDITCARD_ITEM, ItemConst.TR_ITEM_ID.CREDITCARD.CREDIT_CARD, PosMst.MST_VAN.DATA.APPR_ID);

                        sRet = m_cICReader.KeyDownload_ICReader(m_sDevice, sTerminerID);

                        if (sRet == UserCom.RST_OK)
                        {
                            if (m_sDevice == PosConst.POS_CARD_READER_DEVICE_TYPE.IC_READER)
                            {
                                // IC KSN Download 상태값 초기화
                                m_cPosStatus.Base.KSN_IC_Download = "";

                                CmMessage m_PosSal = CmMessage.MakeMessageFromFile(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosSaleInfo);
                                m_PosSal.GetMessage("POSOPEN").MakeMessageOverWrite("KSN_IC_Download", m_cPosStatus.Base.KSN_IC_Download);
                                m_PosSal.MakeFileFromMessage(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosSaleInfo);
                            }
                            else
                            {
                                // RF KSN Download 상태값 초기화
                                m_cPosStatus.Base.KSN_SignPad_Download = "";

                                CmMessage m_PosSal = CmMessage.MakeMessageFromFile(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosSaleInfo);
                                m_PosSal.GetMessage("POSOPEN").MakeMessageOverWrite("KSN_SignPad_Download", m_cPosStatus.Base.KSN_SignPad_Download);
                                m_PosSal.MakeFileFromMessage(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosSaleInfo);
                            }
                        }
                        break;
                    case PosConst.SCFBA_BIZ_TYPE.BIZDOWNLOAD:
                        if (m_sDevice == PosConst.POS_CARD_READER_DEVICE_TYPE.TMONEY)
                        {
                            // 티머니 
                            sPayDcCd = ItemConst.TR_ITEM_ID.MOBILECASH.T_MONEY;
                        }
                        else if (m_sDevice == PosConst.POS_CARD_READER_DEVICE_TYPE.CASHBEE)
                        {
                            // 캐쉬비
                            sPayDcCd = ItemConst.TR_ITEM_ID.MOBILECASH.CASHBEE;
                        }

                        sApprID = PosMstManager.GetMstVan(ItemConst.TR_ITEM_ID.MOBILECASH_ITEM, sPayDcCd, PosMst.MST_VAN.DATA.APPR_ID);
                        sBizNm = PosMstManager.GetMstVan(ItemConst.TR_ITEM_ID.MOBILECASH_ITEM, sPayDcCd, PosMst.MST_VAN.DATA.CMP_APPR_ID);
                        sRet = m_cDeviceSignPad.TMoneyDownload(sApprID, sBizNm, m_cPosStatus.Base.MsgSeqNo, m_sDevice, "00", ref m_RF_rep_array);

                        break;
                    case PosConst.SCFBA_BIZ_TYPE.OPENSTART:
                        if (m_sDevice == PosConst.POS_CARD_READER_DEVICE_TYPE.TMONEY)
                            sPayDcCd = ItemConst.TR_ITEM_ID.MOBILECASH.T_MONEY;
                        else if (m_sDevice == PosConst.POS_CARD_READER_DEVICE_TYPE.CASHBEE)
                            sPayDcCd = ItemConst.TR_ITEM_ID.MOBILECASH.CASHBEE;
                        else if (m_sDevice == PosConst.POS_CARD_READER_DEVICE_TYPE.PAYON)
                            sPayDcCd = ItemConst.TR_ITEM_ID.MOBILECASH.T_MONEY;

                        sApprID = PosMstManager.GetMstVan(ItemConst.TR_ITEM_ID.MOBILECASH_ITEM, sPayDcCd, PosMst.MST_VAN.DATA.APPR_ID);
                        sBizNm = PosMstManager.GetMstVan(ItemConst.TR_ITEM_ID.MOBILECASH_ITEM, sPayDcCd, PosMst.MST_VAN.DATA.CMP_APPR_ID);
                        sRet = m_cDeviceSignPad.TMoneyOpen(sApprID, sBizNm, m_cPosStatus.Base.MsgSeqNo, m_sDevice);
                        break;
                }

                if (sRet == UserCom.RST_OK) m_sStatus = "Y";                

                if (m_sCheckType == PosConst.SCFBA_BIZ_TYPE.INTEGRITY || m_sCheckType == PosConst.SCFBA_BIZ_TYPE.CERTIFICATION)
                    LS_StatusSave(m_sCheckType, m_sDevice, m_sAutoMode, sRsltTime, m_sStatus);                  // 상태저장
                
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                    "Process Exception !!! " + ex.Message);
            }
            finally
            {
                m_bSecondDisp = false;
            }
        }
        #endregion 

        #region 처리 내역 저장
        /// <summary>
        /// 처리 내역 저장
        /// </summary>
        /// <param name="sType"></param>
        /// <param name="sCheckDate"></param>
        /// <param name="sStatus"></param>
        /// <returns></returns>
        private string LS_StatusSave(string sType, string sDeviceType, string sProcType, string sCheckDate, string sStatus)
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                // 무결성 로그 생성
                m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource, m_cPosStatus.Base.LocalDbCatalog, m_cPosStatus.Base.LocalDbUserID, m_cPosStatus.Base.LocalDbPassword);
                m_cSqlDbService.Begin();

                string sSql = "";
                sSql = "";
                sSql += "INSERT INTO POSLOG..ETC_INTEGRITY_LOG \n";
                sSql += "  ( CMP_CD, SALE_DT, STOR_CD, POS_NO, DEVICE_TYPE, CHECK_TYPE, SEQ, PROC_TYPE, CHECK_DT, CHECK_FLAG) \n";
                sSql += "SELECT '" + m_cPosStatus.Base.CmpCd + "'								CMP_CD \n";
                sSql += "	,	'" + DateTime.Now.ToString("yyyyMMdd") + "'					    SALE_DT \n";
                sSql += "	,	'" + m_cPosStatus.Base.StoreNo + "'							    STOR_CD \n";
                sSql += "	,	'" + m_cPosStatus.Base.PosNo + "'								POS_NO \n";
                sSql += "	,	'" + sDeviceType + "'								            DEVICE_TYPE \n";
                sSql += "	,	'" + sType + "'								                    CHECK_TYPE \n";
                sSql += "	,	(SELECT ISNULL(MAX(SEQ), 0) + 1 \n";
                sSql += "			FROM POSLOG..ETC_INTEGRITY_LOG \n";
                sSql += "			WHERE CMP_CD	= '" + m_cPosStatus.Base.CmpCd + "' \n";
                sSql += "			AND SALE_DT		= '" + DateTime.Now.ToString("yyyyMMdd") + "' \n";
                sSql += "			AND STOR_CD		= '" + m_cPosStatus.Base.StoreNo + "' \n";
                sSql += "			AND POS_NO		= '" + m_cPosStatus.Base.PosNo + "'  \n";
                sSql += "			AND DEVICE_TYPE	= '" + sDeviceType + "'  \n";
                sSql += "			AND CHECK_TYPE	= '" + sType + "')		SEQ \n";
                sSql += "   , '" + sProcType + "'                                               PROC_TYPE \n";
                if (sCheckDate.Trim() == "")
                {
                    sSql += "	,	'" + DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.ToString("HHmmss") + "' CHECK_DT \n";
                }
                else
                {
                    sSql += "	,	'" + sCheckDate.Trim() + "'					                    CHECK_DT \n";
                }
                sSql += "	,	'" + sStatus + "'									            CHECK_FLAG \n";

                sSql = sSql.Replace("\t", " ");

                if (m_cSqlDbService.DBExecuteNonQuery(sSql) != UserCom.OK)
                {
                    m_cSqlDbService.Rollback();

                    return sRet;
                }
                m_cSqlDbService.Commit();

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

            }
            return sRet;
        }
        #endregion 

    }
}
