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

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

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 해피포인트 거래후 적립
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Win
{
    public partial class frmHPAfterSave : Form
    {
        #region Variable

        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 PosOLEDevice.DelegateOlePos delegatePos;

        private IDataProcessUs m_cDataService = null;
        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스
        private IHpAfterSaveUs m_cHpAfterSave = null;                               // HP 사후적립

        /// <summary>
        /// 영수증 리스트
        /// </summary>
        private DataTable m_dtSearchList;
        /// <summary>
        /// 서버 거래 호출 여부
        /// </summary>
        private bool m_bServerTranCall = false;
        #endregion
        
        #region 생성자 & 소멸자
        /// <summary>
        /// 생성자
        /// </summary>
        public frmHPAfterSave()
        {
            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;
            delegatePos = new PosOLEDevice.DelegateOlePos(OnDeviceEvent);

            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_cHpAfterSave = (IHpAfterSaveUs)sManager.InitServiceInstance(ServiceLists.BSV_SALE.DLL, ServiceLists.BSV_SALE.HP_AFTER_SAVE); 
        }

        /// <summary>
        /// 폼로드
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmHPAfterSave_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();
        }

        /// <summary>
        /// 폼클로즈
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmHPAfterSave_FormClosing(object sender, FormClosingEventArgs e)
        {
            vScrollbar.Attach(null);

            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>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmHPAfterSave_Activated(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(delegatePos);
        }

        /// <summary>
        /// 폼디엑티브
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmHPAfterSave_Deactivate(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(null);
        }
        #endregion 생성자 & 소멸자
        
        #region 폼 컨트롤 초기화
        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            try
            {
                // 이미지 로딩 처리
                picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_800X600);

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

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

                btnUp2.Image = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_14X9_UP2_BASIC);
                btnUp.Image = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_14X9_UP1_BASIC);
                btnDw.Image = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_14X9_DOWN1_BASIC);
                btnDw2.Image = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_14X9_DOWN2_BASIC);

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

                //테마색상 적용!
                btnEnter.BackColor = CmUtil.GetColorToString(m_cPosStatus.ScnMst.ThemeColor);

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0327);
                lblSaleDate.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0242);
                lblPosNo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0370);
                lblTradeNo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0346);
                lblTradeType.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0404);

                btnSearch.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0004);
                btnEnter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0134);

                //#12283 PB 천안신세계_해피포인트 부정적립 경구 문구 삽입요청 start, phj
                WarningMsg.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1079);
                WarningMsg.BringToFront();
                //#12283 PB 천안신세계_해피포인트 부정적립 경구 문구 삽입요청 end, phj

                txtSaleDate.InputTypeFormat = m_cPosStatus.Global.m_stCultureMaster.strDatePattern;
                txtSaleDate.Text = m_cPosStatus.Global.DateToCulture(m_cPosStatus.Base.SaleDate);

                //dtSaleDate.Value = DateTime.ParseExact(m_cPosStatus.Base.SaleDate, "yyyyMMdd", null);
                txtPosNo.Text = m_cPosStatus.Base.PosNo;
                txtTradeNo.Text = "";
                txtPrtData.Text = "";

                InitializeGrid();
                InitComboBox();

                m_bServerTranCall = false;
                
                vScrollbar.Attach(txtPrtData);

                txtBarCode.Text = "";
                txtBarCode.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);
            }
        }

        /// <summary>
        /// 그리드 초기화
        /// </summary>
        private void InitializeGrid()
        {
            try
            {
                grdSearchList.CsmGridColumnHeadersVisible = true;           //DataGridView 자체의 컬럼 헤더 Visible 여부
                
                grdSearchList.CsmGridColumnHeadersFont = new Font(m_cPosStatus.Base.FONT, 11);
                
                grdSearchList.CsmGridColumnHeadersHeight = 36;              //DataGridView 자체의 컬럼 헤더 높이
                grdSearchList.CsmGridRowsHeight = 36;

                //#14525 PB 중화역 - 12시간지난 결제건이 해피포인트 추후적립되는 증상 start, phj
                //기존
                //grdSearchList.CsmGridColumnCount = 8;                       //그리드의 컬럼수
                //변경
                grdSearchList.CsmGridColumnCount = 9;                       //그리드의 컬럼수
                //#14525 PB 중화역 - 12시간지난 결제건이 해피포인트 추후적립되는 증상 end, phj

                grdSearchList.CsmGridShowPageRowsCount = 9;                 //그리드의 한 화면에 보이는 로우수
                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;                              //그리드 선택 글자 컬러

                //#14525 PB 중화역 - 12시간지난 결제건이 해피포인트 추후적립되는 증상 start, phj
                //기존
                //grdSearchList.CsmGridSetColumnWidth(new int[] { 96, 47, 96, 77, 76, 0, 0, 0 });   //컬럼넓이 지정 // 410->392로 변경
                //변경
                grdSearchList.CsmGridSetColumnWidth(new int[] { 96, 47, 96, 77, 76, 0, 0, 0, 0 });   //컬럼넓이 지정 // 410->392로 변경
                //#14525 PB 중화역 - 12시간지난 결제건이 해피포인트 추후적립되는 증상 end, phj

                grdSearchList.CsmGridAlignment(new int[] { 1, 1, 2, 1, 1, 1, 1, 1 });               //컬럼 정렬 0:왼쪽, 1:가운데, 2:오른쪽

                //각 컬럼별 이름 지정(영업일자,POS번호,판매금액,거래번호,거래시간,사후적립금액,추가적립정보)
                grdSearchList.CsmGridColumnName(0, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0242));
                grdSearchList.CsmGridColumnName(1, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0377));
                grdSearchList.CsmGridColumnName(2, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0348));
                grdSearchList.CsmGridColumnName(3, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0378));
                grdSearchList.CsmGridColumnName(4, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0347));
                grdSearchList.CsmGridColumnName(5, "POINT_AMT");
                grdSearchList.CsmGridColumnName(6, "POINT_INFO");
                grdSearchList.CsmGridColumnName(7, "SAVE_INFO");
                //#14525 PB 중화역 - 12시간지난 결제건이 해피포인트 추후적립되는 증상 start, phj
                grdSearchList.CsmGridColumnName(8, "SYS_DT");
                //#14525 PB 중화역 - 12시간지난 결제건이 해피포인트 추후적립되는 증상 end, phj
                
                //그리드 초기화 테이블
                m_dtSearchList = new DataTable("INIT");
                m_dtSearchList.Columns.Add(new DataColumn("SALE_DT", typeof(string)));
                m_dtSearchList.Columns.Add(new DataColumn("POS_NO", typeof(string)));
                m_dtSearchList.Columns.Add(new DataColumn("TOTSALE_AMT", typeof(string)));
                m_dtSearchList.Columns.Add(new DataColumn("TRADE_NO", typeof(string)));
                m_dtSearchList.Columns.Add(new DataColumn("SYS_TIME", typeof(string)));
                m_dtSearchList.Columns.Add(new DataColumn("POINT_AMT", typeof(string)));
                m_dtSearchList.Columns.Add(new DataColumn("POINT_INFO", typeof(string)));
                m_dtSearchList.Columns.Add(new DataColumn("SAVE_INFO", typeof(string)));
                //#14525 PB 중화역 - 12시간지난 결제건이 해피포인트 추후적립되는 증상 start, phj
                m_dtSearchList.Columns.Add(new DataColumn("SYS_DT", typeof(string)));
                //#14525 PB 중화역 - 12시간지난 결제건이 해피포인트 추후적립되는 증상 end, phj
                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);
            }
        }

        /// <summary>
        /// 콤보박스 초기화
        /// </summary>
        private void InitComboBox()
        {
            try
            {
                cbTradeType.Items.Clear();
                
                cbTradeType.Items.Add("0. " + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0226));
                cbTradeType.Items.Add("1. " + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0405));
                cbTradeType.Items.Add("2. " + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0406));
                
                cbTradeType.SelectedIndex = 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 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)         // 조회
                {
                    SearchTrade("", "", "", "", true);
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnEnter)    // 추후적립
                {
                    CompleteTrade();
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnExit)    
                {
                    m_cDataService.TranComplete();

                    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 btnSelProc_Click(object sender, EventArgs e)
        {
            try
            {
                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");
                }
            }
            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
                
        /// <summary>
        /// 그리드 클릭 이벤트
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="rowIndex"></param>
        private void grdSearchItem_GridClickEvent(object sender, string rowIndex)
        {
            try
            {
                UserLog.WriteLogFile(UserCom.LOG_IOS,
                                     UserCom.INFO_LEVEL,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "Grid Click start");

                txtPrtData.Text = "";
                txtPrtData.Tag = "";

                if (grdSearchList.CsmGridRowsCount == 0) return;

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

                //영업일자,POS번호,판매금액,거래번호,거래시간,사후적립금액,추가적립정보
                string sSaleDate = m_cPosStatus.Global.CultureToDate(grdSearchList.CsmGridGetCell(nRow, 0));
                string sPosNo = grdSearchList.CsmGridGetCell(nRow, 1);
                string sTradeNo = grdSearchList.CsmGridGetCell(nRow, 3);
                
                // 저널 데이터 조회
                string sJnlData = m_cHpAfterSave.SearchPrintSaleReceiptDetail(sSaleDate, sPosNo, sTradeNo);

                //#20171220, HP추후적립 시 현금영수증 데이터 중복으로 들어가는 현상 수정 Start 
                /*UserLog.WriteLogFile(UserCom.LOG_IOS,
                                     UserCom.INFO_LEVEL,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "LoadLocalTran start");
                                
                if (m_bServerTranCall == false)
                {
                    // 사후적립 가능 여부 체크 처리
                    bool bRet = m_cHpAfterSave.LoadLocalTran(sSaleDate, sPosNo, sTradeNo);
                    if (bRet == false) return;
                }

                UserLog.WriteLogFile(UserCom.LOG_IOS,
                                     UserCom.INFO_LEVEL,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "LoadLocalTran end");*/
                //#20171220, HP추후적립 시 현금영수증 데이터 중복으로 들어가는 현상 수정 End

                string sJnlText = "";
                // 저널 텍스트 편집
                int iDataLen = 0;
                while (iDataLen <= sJnlData.Length)
                {
                    string sJnlHdr = CmUtil.MidH(sJnlData, iDataLen, 5);
                    if (sJnlHdr == PosConst.PRT_HDR.PRT_HOR || sJnlHdr == PosConst.PRT_HDR.PRT_BIG)
                    {
                        if (m_cDataService.DoubleParse(CmUtil.MidH(sJnlData, iDataLen + 5 + 11, 11).Trim()) != 0)
                            sJnlText += CmUtil.MidH(sJnlData, iDataLen + 5, 11) + CmUtil.LPadH(CmUtil.MidH(sJnlData, iDataLen + 5 + 11, 11), 32) + PosConst.CRLF;
                        else
                            sJnlText += CmUtil.MidH(sJnlData, iDataLen + 5, 42) + PosConst.CRLF;
                    }
                    else
                    {
                        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);
            }

            UserLog.WriteLogFile(UserCom.LOG_IOS,
                                 UserCom.INFO_LEVEL,
                                 System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                 System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                 "Grid Click end");
        }

        /// <summary>
        /// 컨트롤 이벤트
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Control_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtBarcodeSetFocus();
        }
        private void txtPrtData_Enter(object sender, EventArgs e)
        {
            txtBarcodeSetFocus();
        }

        private void grdSearchList_Enter(object sender, EventArgs e)
        {
            txtBarcodeSetFocus();
        }

        private void txtBarcodeSetFocus()
        {
            try
            {
                txtBarCode.Text = "";
                txtBarCode.Focus();
            }
            catch { }
        }

        private void txtTradeNo_Click(object sender, EventArgs e)
        {
            try
            {
                // 거래번호 입력 처리
                string sStat = WinBasic.ShowForm(new string[] { FormManager.FORM_USER_INPUT_DATA, PosConst.FRM_INPUT_DATA.TRADENO });
                if (sStat != UserCom.RST_ERR && sStat.Length > 0)
                {
                    txtTradeNo.Text = string.Format("{0:D5}", CmUtil.LongParse(sStat));
                }
                else
                {
                    txtTradeNo.Text = "";
                }
            }
            catch { }
        }
        #endregion

        #region User Method
        /// <summary>
        /// 거래 데이터 조회
        /// </summary>
        private void SearchTrade(string sSaleDate, string sPosNo, string sTradeNo, string sPayTime, bool bErrMsg)
        {
            try
            {
                if (sSaleDate == "" && txtSaleDate.Text.Length != 10)
                {
                    if ( bErrMsg == true ) WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0186));
                    return;
                }

                m_bServerTranCall = false;

                txtPrtData.Text = "";
                txtPrtData.Tag = "";

                m_dtSearchList.Clear();

                string sTradeType = "0";
                if ( sSaleDate == "")
                {
                    sSaleDate = m_cPosStatus.Global.CultureToDate(txtSaleDate.Text);
                    //sSaleDate = dtSaleDate.Value.ToString("yyyyMMdd");
                    sPosNo = txtPosNo.Text;
                    sTradeNo = txtTradeNo.Text;
                    sTradeType = cbTradeType.Text.Substring(0, 1);
                }
                // 거래데이터 조회
                UserLog.WriteLogFile(UserCom.LOG_IOS,
                                     UserCom.INFO_LEVEL,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "거래데이터 조회 시작");

                DataTable dtData = m_cHpAfterSave.SearchSaleReceiptList(sSaleDate, sPosNo, sTradeNo, sPayTime, sTradeType);
                if (dtData != null && dtData.Rows.Count > 0)
                {
                    foreach (DataRow dr in dtData.Rows)
                    {
                        DataRow drNewRow = m_dtSearchList.NewRow();

                        drNewRow["SALE_DT"] = m_cPosStatus.Global.DateToCulture(CmUtil.GetDataRowStr(dr, "SALE_DT"));
                        drNewRow["POS_NO"] = CmUtil.GetDataRowStr(dr, "POS_NO");
                        drNewRow["TOTSALE_AMT"] = m_cPosStatus.Global.NumericTOCurrency(CmUtil.GetDataRowDouble(dr, "NET_SALE_AMT"));
                        drNewRow["TRADE_NO"] = CmUtil.GetDataRowStr(dr, "TRADE_NO");
                        drNewRow["SYS_TIME"] =  CmUtil.StrToTime(CmUtil.GetDataRowStr(dr,"PAY_TIME"));
                        drNewRow["POINT_AMT"] = CmUtil.GetDataRowDouble(dr, "AF_ACCUM_POINT_AMT").ToString();
                        drNewRow["POINT_INFO"] = CmUtil.GetDataRowStr(dr, "AF_ACCUM_POINT_INFO");
                        drNewRow["SAVE_INFO"] = CmUtil.GetDataRowStr(dr, "SAVE_INFO");

                        //#14525 PB 중화역 - 12시간지난 결제건이 해피포인트 추후적립되는 증상 start, phj
                        drNewRow["SYS_DT"] = CmUtil.GetDataRowStr(dr, "SYS_DT");
                        //#14525 PB 중화역 - 12시간지난 결제건이 해피포인트 추후적립되는 증상 end, phj
                        

                        m_dtSearchList.Rows.Add(drNewRow);
                    }
                }
                else
                {
                    if (bErrMsg == true) WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0302));
                }

                UserLog.WriteLogFile(UserCom.LOG_IOS,
                                     UserCom.INFO_LEVEL,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "거래데이터 건 수:" + (m_dtSearchList == null ? "0" : m_dtSearchList.Rows.Count.ToString()));

                //그리드 적용
                grdSearchList.CsmGridDataSource = m_dtSearchList;
                grdSearchList.CsmGridSelectRow(0);
                grdSearchItem_GridClickEvent(null, null);

                UserLog.WriteLogFile(UserCom.LOG_IOS,
                                         UserCom.INFO_LEVEL,
                                         System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                         System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                         "거래데이터 조회 완료");
            }
            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 CompleteTrade()
        {
            bool bRet = false;

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

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

                //영업일자,POS번호,판매금액,거래번호,거래시간,사후적립금액,추가적립정보
                string sSaleDate = m_cPosStatus.Global.CultureToDate(grdSearchList.CsmGridGetCell(nRow, 0));
                string sPosNo = grdSearchList.CsmGridGetCell(nRow, 1);
                string sNetSaleAmt = grdSearchList.CsmGridGetCell(nRow, 2);
                string sTradeNo = grdSearchList.CsmGridGetCell(nRow, 3);
                string sTradeTm = grdSearchList.CsmGridGetCell(nRow, 4);
                string sPointAmt = grdSearchList.CsmGridGetCell(nRow, 5);
                string sPointInfo = grdSearchList.CsmGridGetCell(nRow, 6);

                //#14525 PB 중화역 - 12시간지난 결제건이 해피포인트 추후적립되는 증상 start, phj
                string sSysDate = grdSearchList.CsmGridGetCell(nRow, 8);
                //#14525 PB 중화역 - 12시간지난 결제건이 해피포인트 추후적립되는 증상 end, phj

                double nAddHours = CmUtil.LongParse(PosMstManager.GetPosOption(POS_OPTION.OPT016));
                if (nAddHours > 0)
                {
                    //#15037 PB 학익풍림 - 해피포인트 추후적립 가능시간 관련 start,phj
                    //기존
                    ////#14525 PB 중화역 - 12시간지난 결제건이 해피포인트 추후적립되는 증상 start, phj
                    ////기존
                    ///*
                    //DateTime dtSaleDT = new DateTime(CmUtil.IntParse(sSaleDate.Substring(0, 4)),
                    //                                 CmUtil.IntParse(sSaleDate.Substring(4, 2)),
                    //                                 CmUtil.IntParse(sSaleDate.Substring(6, 2)),
                    //                                 CmUtil.IntParse(sTradeTm.Substring(0, 2)),
                    //                                 CmUtil.IntParse(sTradeTm.Substring(2, 2)), 0);
                    //*/
                    //
                    ////변경
                    //DateTime dtSaleDT = new DateTime(CmUtil.IntParse(sSysDate.Substring(0, 4)),
                    //                                 CmUtil.IntParse(sSysDate.Substring(4, 2)),
                    //                                 CmUtil.IntParse(sSysDate.Substring(6, 2)),
                    //                                 CmUtil.IntParse(sTradeTm.Substring(0, 2)),
                    //                                 CmUtil.IntParse(sTradeTm.Substring(2, 2)), 0);
                    ////#14525 PB 중화역 - 12시간지난 결제건이 해피포인트 추후적립되는 증상 end, phj


                    //변경
                    DateTime dtSaleDT = new DateTime(CmUtil.IntParse(sSysDate.Substring(0, 4)),
                                                     CmUtil.IntParse(sSysDate.Substring(4, 2)),
                                                     CmUtil.IntParse(sSysDate.Substring(6, 2)),
                                                     CmUtil.IntParse(sTradeTm.Substring(0, 2)),
                                                     CmUtil.IntParse(sTradeTm.Substring(3, 2)),
                                                     CmUtil.IntParse(sTradeTm.Substring(6, 2)), 0);    
                    //#15037 PB 학익풍림 - 해피포인트 추후적립 가능시간 관련 end,phj


                    if (dtSaleDT.AddHours(nAddHours) < DateTime.Now)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0395);
                        return false;
                    }
                }

                if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0270) != true) return bRet;

                // 사후적립 가능 여부 체크 처리
                bRet = m_cHpAfterSave.ChekcAfterSaveTran(sSaleDate, sPosNo, sTradeNo);
                if (bRet == false) return bRet;

                //if (m_bServerTranCall == false)
                //{
                //    // 사후적립 가능 여부 체크 처리
                //    bRet = m_cHpAfterSave.ChekcAfterSaveTran(sSaleDate, sPosNo, sTradeNo);
                //    if (bRet == false) return bRet;
                //}

                // 추후 적립 처리(중국 추후적립 2017.06.02)
                if (m_cPosStatus.Mst.CntryDiv == ItemConst.CNTRY_DIV.CN)
                {
                    frmPointHappyPointAfter_China fFormPay = (frmPointHappyPointAfter_China)FormManager.GetForm(FormManager.FORM_POINT_HAPPYPOINT_AFTER);
                    if (fFormPay == null)
                    {
                        fFormPay = new frmPointHappyPointAfter_China();
                        FormManager.AddForm(FormManager.FORM_POINT_HAPPYPOINT_AFTER, fFormPay);
                    }
                    fFormPay.SaleDateTime = m_cPosStatus.Global.DateToCulture(sSaleDate) + "  " + CmUtil.StrToTime(sTradeTm);
                    fFormPay.NetSaleAmt = m_cDataService.DoubleParse(sNetSaleAmt);
                    fFormPay.AfterSaveAmt = m_cDataService.DoubleParse(sPointAmt);
                    fFormPay.AfterSaveInfo = sPointInfo;
                    if (fFormPay.ShowDialog() != DialogResult.OK) return false;
                }
                else
                {
                    frmPointHappyPointAfter fFormPay = (frmPointHappyPointAfter)FormManager.GetForm(FormManager.FORM_POINT_HAPPYPOINT_AFTER);
                    if (fFormPay == null)
                    {
                        fFormPay = new frmPointHappyPointAfter();
                        FormManager.AddForm(FormManager.FORM_POINT_HAPPYPOINT_AFTER, fFormPay);
                    }
                    fFormPay.SaleDateTime = m_cPosStatus.Global.DateToCulture(sSaleDate) + "  " + CmUtil.StrToTime(sTradeTm);
                    fFormPay.NetSaleAmt = m_cDataService.DoubleParse(sNetSaleAmt);
                    fFormPay.AfterSaveAmt = m_cDataService.DoubleParse(sPointAmt);
                    fFormPay.AfterSaveInfo = sPointInfo;
                    if (fFormPay.ShowDialog() != DialogResult.OK) return false;
                }

                // 거래구분 설정 => 사후적립
                m_cTrnStatus.Head.TradeDiv = ItemConst.TRAN_DIV.NORMAL;
                m_cTrnStatus.Head.TradeKind = ItemConst.TRAN_KIND.AFTER.HP_SAVE;

                // 원거래 정보 설정
                m_cTrnStatus.Head.OrgSaleDate = sSaleDate;
                m_cTrnStatus.Head.OrgPosNo = sPosNo;
                m_cTrnStatus.Head.OrgTradeNo = sTradeNo;

                // 거래 완료 처리
                ISaleCompleteUs m_cSaleComplete = (ISaleCompleteUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.SALE_COMPLETE);
                string sRet = m_cSaleComplete.PosSaleExecute(new string[] { });
                if (sRet != UserCom.RST_OK) return bRet;

                //2017-06-02 dkshin 해피앱 추후적립
                //해피앱 추후적립 상태 변경
                if (m_cPosStatus.Mst.CntryDiv == ItemConst.CNTRY_DIV.KR)
                {
                    m_cHpAfterSave.HPAPP_After_Update_Tran(sSaleDate, sPosNo, sTradeNo);
                }

                if (m_bServerTranCall == false)
                    SearchTrade("", "", "", "", false);                    // 거래데이터 재조회
                else
                    SearchTrade(sSaleDate, sPosNo, sTradeNo, "", 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 bRet;
        }

        #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.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>
        /// SCANNER Event
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnScannerEvent(object source, EventArgs e)
        {
            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 DeviceEvent 관련

        /// <summary>
        /// 입력박스 (바코드 입력 처리)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="sFuncValue"></param>
        private void txtBarCode_EditBoxKeyDownEvent(object sender, string sFuncValue)
        {
            try
            {
                if (sFuncValue == PosKey.MENU_KEY.ENTER)
                {
                    //#20170623, 해피앱 추후적립_바코드 수정_lsr Start
                    // 기존
                    /*if (txtBarCode.Text.Length != 16)
                    {
                        txtBarCode.Text = "";
                        return;
                    }
                    
                    m_bServerTranCall = false;
                    
                    string sSaleDate = txtBarCode.Text.Substring(0, 8);
                    string sPosNo = txtBarCode.Text.Substring(8, 2);
                    string sSaleTime = txtBarCode.Text.Substring(10, 6);
                    */

                    if (txtBarCode.Text.Length != 16 && txtBarCode.Text.Length != 20)
                    {
                        txtBarCode.Text = "";
                        return;
                    }

                    m_bServerTranCall = false;

                    string sSaleDate = "";
                    string sPosNo = "";
                    string sSaleTime = "";
                    string sTradeNo = "";

                    if (txtBarCode.Text.Length == 16)
                    {
                        sSaleDate = txtBarCode.Text.Substring(0, 8);
                        sPosNo = txtBarCode.Text.Substring(8, 2);
                        sSaleTime = txtBarCode.Text.Substring(10, 6);
                    }
                    else
                    {
                        // 회사, 빌5(끝4자리), P1, 년1, 빌4, 년2, P2, 년3, 점1(5자리), 년4, 점2, 월1, 빌3, 월2, 점3, 일1, 빌2, 일2, 점4, 점5
                        sSaleDate = txtBarCode.Text.Substring(3, 1) + txtBarCode.Text.Substring(5, 1) + txtBarCode.Text.Substring(7, 1) + txtBarCode.Text.Substring(9, 1) +
                                    txtBarCode.Text.Substring(11, 1) + txtBarCode.Text.Substring(13, 1) + txtBarCode.Text.Substring(15, 1) + txtBarCode.Text.Substring(17, 1);
                        sPosNo = txtBarCode.Text.Substring(2, 1) + txtBarCode.Text.Substring(6, 1);
                        sTradeNo = "0" + txtBarCode.Text.Substring(16, 1) + txtBarCode.Text.Substring(12, 1) + txtBarCode.Text.Substring(4, 1) + txtBarCode.Text.Substring(1, 1);
                    }
                    //#20170623, 해피앱 추후적립_바코드 수정_lsr End

                    txtBarCode.Text = "";
                    txtPrtData.Text = "";
                    txtPrtData.Tag = "";

                    //#20170623, 해피앱 추후적립_바코드 수정_lsr Start
                    // 기존
                    //SearchTrade(sSaleDate, sPosNo, "", sSaleTime, true);

                    SearchTrade(sSaleDate, sPosNo, sTradeNo, sSaleTime, true);
                    //#20170623, 해피앱 추후적립_바코드 수정_lsr End

                    //m_dtSearchList.Clear();

                    //// 영수증 스캔시 서버 거래 호출 만 처리
                    //string sRet = m_cHpAfterSave.SearchServerTran(sSaleDate, sPosNo, "", sSaleTime);
                    //if (sRet == UserCom.RST_OK)
                    //{
                    //    DataRow drNewRow = m_dtSearchList.NewRow();

                    //    drNewRow["SALE_DT"] = m_cPosStatus.Global.DateToCulture(m_cTrnStatus.Head.SaleDate);
                    //    drNewRow["POS_NO"] = m_cTrnStatus.Head.PosNo;
                    //    drNewRow["TOTSALE_AMT"] = m_cPosStatus.Global.NumericTOCurrency(m_cTrnStatus.Head.NetSaleAmt);
                    //    drNewRow["TRADE_NO"] = m_cTrnStatus.Head.TradeNo;
                    //    drNewRow["SYS_TIME"] = CmUtil.StrToTime(m_cTrnStatus.Head.PayHms);
                    //    drNewRow["POINT_AMT"] = m_cTrnStatus.Head.AftSavePoint;
                    //    drNewRow["POINT_INFO"] = m_cTrnStatus.Head.AftSaveAddInfo;
                    //    drNewRow["SAVE_INFO"] = "";

                    //    m_dtSearchList.Rows.Add(drNewRow);

                    //    m_bServerTranCall = true;

                    //    m_cDataSrv.TranComplete();
                    //}

                    ////그리드 적용
                    //grdSearchList.CsmGridDataSource = m_dtSearchList;
                    //grdSearchList.CsmGridSelectRow(0);
                    //grdSearchItem_GridClickEvent(null, null);
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        private void btnDate_Click(object sender, EventArgs e)
        {
            try
            {
                string sDate = WinBasic.ShowForm(new string[] { FormManager.FORM_CALENDAR });
                if (sDate != "") txtSaleDate.Text = m_cPosStatus.Global.DateToCulture(sDate);

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

        private void txtPosNo_Click(object sender, EventArgs e)
        {
            try
            {
                // 포스번호 입력 처리
                string sStat = WinBasic.ShowForm(new string[] { FormManager.FORM_USER_INPUT_DATA, PosConst.FRM_INPUT_DATA.POSNO });
                if (sStat != UserCom.RST_ERR && sStat.Length > 0)
                {
                    txtPosNo.Text = string.Format("{0:D2}", CmUtil.LongParse(sStat));
                }
                else
                {
                    txtPosNo.Text = m_cPosStatus.Base.PosNo;
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

    }
}
