using System;
using System.Text;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Collections;

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

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 마감/중간마감 취소
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Win
{
    public partial class frmAccADMTCan : 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 DeviceStatus m_cDevStatus = new DeviceStatus();                     // 디바이스 관리

        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스
        private IDataProcessUs m_cDataService = null;
        private IAccADMT m_cAccADMT = null;
        private ISaleCompleteUs m_cSaleComplete = null;
        private ISaleRefundUs m_cSaleRefund = null;                                 // 반품처리

        private string m_sPosMenuKeyIn;
        public string PosMenuKeyIn { set { m_sPosMenuKeyIn = value; } get { return m_sPosMenuKeyIn; } }
        private string m_sPosMenuKeyOut;
        public string PosMenuKeyOut { set { m_sPosMenuKeyOut = value; } get { return m_sPosMenuKeyOut; } }

        private bool bNotDoubleClik = false;                                        // 더블 클릭 방지용
        /// <summary>
        /// 영수증 리스트
        /// </summary>
        private DataTable m_dtSearchList;

        private string m_sPosMenuKey;                                               // 입력코드
        /// <summary>
        /// 할인 구분
        /// </summary>
        public string SetPosMenuKey { set { this.m_sPosMenuKey = value; } }

        private string m_sTranKind;                                                 // 거래종별
        /// <summary>
        /// 거래종별
        /// </summary>
        public string SetTranKind { set { this.m_sTranKind = value; } }

        private string m_sTradeDiv;                                                 // 판매구분
        /// <summary>
        /// 판매구분
        /// </summary>
        public string SetTradeDiv { set { this.m_sTradeDiv = value; } }

        /// <summary>
        /// 입력구분
        /// </summary>
        private string m_sInPutType = "";
        /// <summary>
        /// 입력데이터
        /// </summary>
        private string m_sInPutData = "";
        /// <summary>
        /// 카드데이터
        /// </summary>
        private string m_sInEncData = ""; 


        #endregion 변수 선언

        #region 생성자 & 소멸자 & 폼초기화
        public frmAccADMTCan()
        {
            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_cDataService = (IDataProcessUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_SERVICE);
            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
            m_cAccADMT = (IAccADMT)sManager.InitServiceInstance(ServiceLists.BSV_OPEN_CLOSE.DLL, ServiceLists.BSV_OPEN_CLOSE.ACC_ADMT);
            m_cSaleComplete = (ISaleCompleteUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.SALE_COMPLETE);
            m_cSaleRefund = (ISaleRefundUs)sManager.InitServiceInstance(ServiceLists.BSV_SALE.DLL, ServiceLists.BSV_SALE.SALE_REFUND); 
        }

        private void frmAccADMTCan_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();
        }

        private void frmAccADMTCan_Activated(object sender, EventArgs e)
        { 
        }

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

        private void frmAccADMTCan_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 + "()", lblTitle.Text);
        }

        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            string sMaxTradeNo = "";
            string sRet = UserCom.RST_ERR;
            DataTable dtData = null;

            try
            {
                // 이미지 로딩 처리
                picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_FULL_SIZE);
                this.Size = new Size(1024, 696);
                this.Location = new Point(0, 50);

                this.Hide();

                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);

                txtPrtData.Font = new Font(m_cPosStatus.Base.FONT_FIX, txtPrtData.Font.Size, txtPrtData.Font.Style);

                //버튼이미지 적용
                btnUp.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_14X9_UP1_BASIC);
                btnUp.ImageAlign = ContentAlignment.MiddleCenter;
                btnUp.BorderStyle = BorderStyle.None;
                btnDw.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_14X9_DOWN1_BASIC);
                btnDw.ImageAlign = ContentAlignment.MiddleCenter;
                btnDw.BorderStyle = BorderStyle.None;

                if (btnUp.Image != null) btnUp.Text = "";
                if (btnDw.Image != null) btnDw.Text = "";

                btnUp2.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_14X9_UP2_BASIC);
                btnUp2.ImageAlign = ContentAlignment.MiddleCenter;
                btnUp2.BorderStyle = BorderStyle.None;
                btnDw2.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_14X9_DOWN2_BASIC);
                btnDw2.ImageAlign = ContentAlignment.MiddleCenter;
                btnDw2.BorderStyle = BorderStyle.None;

                if (btnUp2.Image != null) btnUp2.Text = "";
                if (btnDw2.Image != null) btnDw2.Text = "";

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

                bNotDoubleClik = false;

                if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0342) == false)
                {
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                    return;
                }

                // 영업마감 체크
                if (m_cPosStatus.Base.OpenClose != "0")
                {
                    // 마감되지 않은경우 종료
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                    return;
                }
                else
                {
                    // 영업마감 취소    
                    sMaxTradeNo = "";
                    dtData = m_cAccADMT.GetMax_ADMT_TradeNo(new string[] { ItemConst.TRAN_KIND.STATEMENT.ADJUSTMENT });
                    if (dtData != null && dtData.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dtData.Rows)
                        {
                            sMaxTradeNo = CmUtil.GetDataRowStr(dr, "TRADE_NO");
                        }
                    }

                    // 영업마감 취소 저장
                    sRet = m_cAccADMT.RefundADMTData(new string[] { m_sTranKind, m_sTradeDiv, sMaxTradeNo });
                    //WinManager.ShowSearchMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0361), this);
                    //sRet = m_cAccADMT.SetData(new string[] { m_sTranKind, m_sTradeDiv }, null);
                    //WinManager.HideSearchMessage(this);

                    if (sRet == UserCom.RST_OK)
                    {
                        sMaxTradeNo = "";
                        dtData = m_cAccADMT.GetMax_ADMT_TradeNo(new string[] { ItemConst.TRAN_KIND.LOG.POS_CLOSE });
                        if (dtData != null && dtData.Rows.Count > 0)
                        {
                            foreach (DataRow dr in dtData.Rows)
                            {
                                sMaxTradeNo = CmUtil.GetDataRowStr(dr, "TRADE_NO");
                            }
                        }

                        // 폐점정보 생성
                        sRet = m_cAccADMT.RefundADMTData(new string[] { ItemConst.TRAN_KIND.LOG.POS_CLOSE, m_sTradeDiv, sMaxTradeNo });
                        if (sRet == UserCom.RST_OK)
                        {
                            m_cPosStatus.Base.OpenClose = "1";

                            CmMessage m_PosConf = CmMessage.MakeMessageFromFile(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosSaleInfo);
                            m_PosConf.GetMessage("POSOPEN").MakeMessageOverWrite("OpenClose", m_cPosStatus.Base.OpenClose);
                            m_PosConf.MakeFileFromMessage(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosSaleInfo);

                            // 최종 중간마감 차수 증가 로딩
                            string sQuery = "";
                            sQuery = " SELECT ISNULL(MAX(MID_CLOSE_SEQ),'0') MID_CLOSE_SEQ FROM POSLOG..TR_SALE_HEADER ";
                            sQuery += " WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "'  ";
                            sQuery += "  AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "' ";
                            sQuery += "  AND SALE_DT = '" + m_cPosStatus.Base.SaleDate + "' ";
                            sQuery += "  AND POS_NO = '" + m_cPosStatus.Base.PosNo + "' ";
                            sQuery += "  AND TRADE_KINDPER = '" + ItemConst.TRAN_KIND.STATEMENT.MIDDLE_ADJUSTMENT + "' ";
                            sQuery += "  AND ISNULL(MID_CLOSE_SEQ, '0') <> '99' ";

                            IMasterUs m_cMstService = (IMasterUs)sManager.InitServiceInstance(ServiceLists.ASV_MASTER.DLL, ServiceLists.ASV_MASTER.POS_MASTER);
                            DataTable dtMidCloseSeqInfo = m_cMstService.Select(new string[] { sQuery });

                            if (dtMidCloseSeqInfo != null && dtMidCloseSeqInfo.Rows.Count > 0)
                            {
                                DataRow dr = dtMidCloseSeqInfo.Rows[0];

                                int nMidCloseSeq = (int)CmUtil.LongParse(CmUtil.GetDataRowStr(dr, "MID_CLOSE_SEQ"));
                                m_cPosStatus.Base.MidCloseSeq = string.Format("{0:00}", nMidCloseSeq + 1);
                            }

                            CmMessage m_PosSaleInfo = CmMessage.MakeMessageFromFile(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosSaleInfo);
                            m_PosSaleInfo.GetMessage("MSGNO").MakeMessageOverWrite("MidCloseSeq", m_cPosStatus.Base.MidCloseSeq);
                            m_PosSaleInfo.MakeFileFromMessage(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosSaleInfo);

                            WinManager.ConfirmMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0315));
                        }
                        else
                        {
                            WinManager.ErrorMessage(sRet);
                        } 
                    }
                    else
                    {
                        WinManager.ErrorMessage(sRet);
                    }

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

                //if (m_cPosStatus.Base.OpenClose == "1")
                //{
                //    m_sTranKind = ItemConst.TRAN_KIND.STATEMENT.ADJUSTMENT;
                //    lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0512);
                //}
                //else
                //{
                //    m_sTranKind = ItemConst.TRAN_KIND.STATEMENT.MIDDLE_ADJUSTMENT;
                //    lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0511);
                //}

                btnComplete.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0515);                          // 입금취소
                txtPrtData.Text = "";

                InitializeGrid();                                                                                       // 그리드 초기화      
                DataGridSetting(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);
            }
        }
        #endregion

        #region 버튼 입력 처리
        /// <summary>
        /// 버튼 입력 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnProc_Click(object sender, EventArgs e)
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                if (bNotDoubleClik) return;
                bNotDoubleClik = true;

                if ((UI.CsmButton)sender == btnUp2)
                {
                    grdSearchList.CsmGridScroll("PAGE UP");
                }
                else if ((UI.CsmButton)sender == btnUp)
                {
                    grdSearchList.CsmGridScroll("UP");
                }
                else if ((UI.CsmButton)sender == btnDw)
                {
                    grdSearchList.CsmGridScroll("DOWN");
                }
                else if ((UI.CsmButton)sender == btnDw2)
                {
                    grdSearchList.CsmGridScroll("PAGE DOWN");
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnComplete)          // 입금취소
                {
                    // 입금취소
                    sRet = CompleteTxtInPut();

                    bNotDoubleClik = false;
                    if (sRet != UserCom.RST_OK) return;

                    this.DialogResult = DialogResult.OK;
                    this.Close();
                    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);
                bNotDoubleClik = false;
            }
            bNotDoubleClik = false;
        }

        /// <summary>
        /// 닫기
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        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
           
        #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)
                {


                }
                else if (sFuncValue == PosKey.MENU_KEY.CLEAR)
                {

                }
                else if (sFuncValue == PosKey.MENU_KEY.ESC_PREVIOUS)
                {
                    this.DialogResult = DialogResult.Cancel;
                    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);
            }
        }

        /// <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>
        /// <returns></returns>
        private bool CheckTxtInPut(object sender)
        {
            try
            {
                // 상품권 체크
                //if (sender == null || ((Cosmos.UI.CsmPosEditBox)sender) == txtCardNo)
                //{
                //    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0189);
                //    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>
        /// <returns></returns>
        private string CompleteTxtInPut()
        {
            string sRet = UserCom.RST_ERR;

            try
            {
                if (grdSearchList.CsmGridRowsCount == 0) return sRet;

                int nRow = grdSearchList.CsmGridSelectedRowIndex;
                if (nRow < 0) return sRet;

                // 거래번호
                string sTradeNo = grdSearchList.CsmGridGetCell(nRow, 0);

                if (sTradeNo.Length <= 0) return sRet;

                // 거래구분
                string sTradeDiv = grdSearchList.CsmGridGetCell(nRow, 1);
                string sTradeMsg = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0076);                         

                if (sTradeDiv != sTradeMsg)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0314);
                    return sRet;
                }

                // 원거래 취소 조회
                DataTable dtData = m_cDataCommon.SelectDPSTRefund(sTradeNo);
                if (dtData != null && dtData.Rows.Count != 0)
                {
                    foreach (DataRow dr in dtData.Rows)
                    {
                        if (CmUtil.IntParse(dr["QTY"].ToString()) > 0 )
                        {
                            WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0314);
                            return sRet;
                        }
                    }
                }

                // 입금 조회
                //dtData = m_cDataCommon.SelectDPSTList(sTradeNo);

                // 저장 버튼 눌렀을 경우
                // 입출금 유형, 입출금 코드, 입출금 금액, 입출금 명, 고객번호, 여유필드01,  여유필드02, 여유필드03, 여유필드04, 여유필드05
                sRet = m_cAccADMT.SetRefund(new string[] { m_sTranKind, m_sTradeDiv, sTradeNo }, dtData);

                if (sRet == UserCom.RST_OK)
                {
                    if (m_sTranKind == ItemConst.TRAN_KIND.STATEMENT.ADJUSTMENT && m_cPosStatus.Base.OpenClose == "0")
                    {
                        // 영업마감 취소
                        m_cPosStatus.Base.OpenClose = "1";

                        CmMessage m_PosConf = CmMessage.MakeMessageFromFile(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosSaleInfo);
                        m_PosConf.GetMessage("POSOPEN").MakeMessageOverWrite("OpenClose", m_cPosStatus.Base.OpenClose);
                        m_PosConf.MakeFileFromMessage(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosSaleInfo);
                    }
                    WinManager.ConfirmMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0315));
                    DataGridSetting(0);
                }
                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;
        }
        #endregion

        #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;
                    case PosConst.OPOS_DEVICE.SCANNER:
                        this.Invoke(new EventHandler(OnScannerEvent));
                        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);
            }
        }

        /// <summary>
        /// MSR Event
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnMSREvent(object source, EventArgs e)
        {

        }
        /// <summary>
        /// 스캐너 이벤트 처리
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnScannerEvent(object source, EventArgs e)
        {
            string sScanData = m_cDevStatus.Scanner.DataLabel;
            if (sScanData.Length > 0 && m_sInPutData == "")
            {
                m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_BARCODE;
                m_sInPutData = sScanData;

                //txtCardNo.Text = m_sInPutData;

///                if (m_cTrnStatus.Head.TradeDiv == ItemConst.TRAN_DIV.NORMAL) SearchTxtInPut();
            }

        }

        /// <summary>
        /// 카드 번호 암호화
        /// </summary>
        /// <param name="sInData"></param>
        /// <param name="sCardData"></param>
        /// <param name="sCardNo"></param>
        /// <returns></returns>
        private string EncryptedCardNo(string sInData, ref string sCardData, ref string sCardNo)
        {
            string sEncData = sInData;

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

        /// <summary>
        /// IC 카드 정보 입력 처리
        /// </summary>
        /// <returns></returns>
        private bool GetIcCardData()
        {
            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;
        }
        #endregion

        #region 그리드 초기화
        /// <summary>
        /// 그리드 초기화
        /// </summary>
        private void InitializeGrid()
        {
            try
            {
                grdSearchList.CsmGridColumnHeadersVisible = true;           //DataGridView 자체의 컬럼 헤더 Visible 여부

                grdSearchList.CsmGridColumnHeadersFont = new Font(m_cPosStatus.Base.FONT, 12);

                grdSearchList.CsmGridColumnHeadersHeight = 38;              //DataGridView 자체의 컬럼 헤더 높이
                grdSearchList.CsmGridRowsHeight = 37;
                grdSearchList.CsmGridColumnCount = 3;                       //그리드의 컬럼수
                grdSearchList.CsmGridShowPageRowsCount = 14;                //그리드의 한 화면에 보이는 로우수
                grdSearchList.CsmGridSetHeaderBackColor(236, 238, 239);                             //그리드 헤더 배경색
                grdSearchList.CsmGridDefaultRowBackColor = Color.FromArgb(255, 255, 255);           //그리드 홀수(Default)행의 배경색 지정
                grdSearchList.CsmGridAlternateRowBackColor = Color.FromArgb(251, 253, 255);         //그리드 짝수(Alternate)행의 배경색 지정
                grdSearchList.CsmGridBackGroundColor = Color.FromArgb(251, 253, 255);               //기본 백그라운드 컬러
                grdSearchList.CsmGridHighlightColor = Color.FromArgb(255, 251, 211);                //그리드 선택 백 컬러
                grdSearchList.CsmGridHighlightTextColor = Color.Black;                              //그리드 선택 글자 컬러
                grdSearchList.CsmGridSetColumnWidth(new int[] { 160, 135, 180 });   //컬럼넓이 지정
                grdSearchList.CsmGridAlignment(new int[] { 1, 1, 1 });               //컬럼 정렬 0:왼쪽, 1:가운데, 2:오른쪽

                //각 컬럼별 이름 지정(영업일자,POS번호,판매금액,거래번호,거래시간,거래구분,)
                grdSearchList.CsmGridColumnName(0, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0378));
                grdSearchList.CsmGridColumnName(1, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0067));
                grdSearchList.CsmGridColumnName(2, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0347));

                //그리드 초기화 테이블
                m_dtSearchList = new DataTable("INIT");
                m_dtSearchList.Columns.Add(new DataColumn("TRADE_NO", typeof(string)));
                m_dtSearchList.Columns.Add(new DataColumn("TRADE_DIV", typeof(string)));
                m_dtSearchList.Columns.Add(new DataColumn("PAY_TIME", typeof(string)));
                m_dtSearchList.Clear();

            }
            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 그리드 설정 및 사용
        private double DataGridSetting(int iWorkMode)
        {
            try
            {
                m_dtSearchList.Clear();
                 
                // 거래데이터 조회
                DataTable dtData = m_cDataCommon.SelectADMTList(m_sTranKind);
                if (dtData != null && dtData.Rows.Count > 0)
                {
                    foreach (DataRow dr in dtData.Rows)
                    {
                        DataRow drNewRow = m_dtSearchList.NewRow();
                        drNewRow["TRADE_NO"] = CmUtil.GetDataRowStr(dr, "TRADE_NO");

                        if (CmUtil.GetDataRowStr(dr, "TRADE_DIV") == ItemConst.TRAN_DIV.REFUND)
                            drNewRow["TRADE_DIV"] = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0515);
                        else
                            drNewRow["TRADE_DIV"] = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0076);
                        drNewRow["PAY_TIME"] = CmUtil.StrToTime(CmUtil.GetDataRowStr(dr, "PAY_TIME"));

                        m_dtSearchList.Rows.Add(drNewRow);
                    }
                }

                //그리드 적용
                grdSearchList.CsmGridDataSource = m_dtSearchList;

                grdSearchList.CsmGridIndicateForeColor = Color.Red;
                if (dtData != null && dtData.Rows.Count > 0)
                {
                    int nRow = 0;
                    foreach (DataRow dr in dtData.Rows)
                    {
                        if (CmUtil.GetDataRowStr(dr, "TRADE_DIV") == "1")
                        {
                            grdSearchList.CsmGridIndicateRow(nRow, true);
                        }
                        nRow++;
                    }
                }

                grdSearchList.CsmGridSelectRow(0);

                return 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 0;
        }

        #endregion

        #region 그리드 클릭 이벤트
        /// <summary>
        /// 그리드 클릭 이벤트
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="rowIndex"></param>
        private void grdSearchItem_GridClickEvent(object sender, string rowIndex)
        {
            try
            {
                txtPrtData.Text = "";
                txtPrtData.Tag = "";

                if (grdSearchList.CsmGridRowsCount == 0) return;

                int nRow = grdSearchList.CsmGridSelectedRowIndex;
                if (nRow < 0) return;

                // 거래번호
                string sTradeNo = grdSearchList.CsmGridGetCell(nRow, 0);

                // 저널 데이터 조회
                string sJnlData = m_cSaleRefund.SearchPrintSaleReceiptDetail(m_cPosStatus.Base.SaleDate, m_cPosStatus.Base.PosNo, sTradeNo);

                string sJnlText = "";

                // 저널 텍스트 편집
                int iDataLen = 0;
                while (iDataLen <= sJnlData.Length)
                {
                    sJnlText += CmUtil.MidH(sJnlData, iDataLen + 5, 42) + PosConst.CRLF;
                    iDataLen += 47;
                }
                txtPrtData.Text = sJnlText;
                txtPrtData.Tag = sJnlData;
            }
            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 
    }

}
