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

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

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 영수증 반품
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Win
{
    public partial class frmRefundRec : 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 ISaleReceipt m_cTradeDeal = null;
        private ISaleRefundUs m_cSaleRefund = null;                                 // 반품처리


        //#20171227 인천공항 포스연동 start, phj
        private IAirPortTran m_cAirPortTran = null;
        //#20171227 인천공항 포스연동 end, phj

        /// <summary>
        /// 영수증 리스트
        /// </summary>
        private DataTable m_dtSearchList;
        /// <summary>
        /// 서버 거래 호출 여부
        /// </summary>
        private bool m_bServerTranCall = false;
        #endregion
        
        #region 생성자 & 소멸자
        /// <summary>
        /// 생성자
        /// </summary>
        public frmRefundRec()
        {
            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_cTradeDeal = (ISaleReceipt)sManager.InitServiceInstance(ServiceLists.BSV_BASIC.DLL, ServiceLists.BSV_BASIC.SALE_RECEIPT);
            m_cSaleRefund = (ISaleRefundUs)sManager.InitServiceInstance(ServiceLists.BSV_SALE.DLL, ServiceLists.BSV_SALE.SALE_REFUND);


            //#20171227 인천공항 포스연동 start, phj            
            m_cAirPortTran = (IAirPortTran)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.AIRPORT_TRAN);
            //#20171227 인천공항 포스연동 end, phj

            GetBtnImg();    //버튼이미지로드
        }

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

        /// <summary>
        /// 폼디엑티브
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmRefund_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 = "";

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

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0379);
                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_0371);

                btnSearch.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0004);
                btnEnter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0075);
                btnPluLoad.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0372);

                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;

                if (m_cPosStatus.Sale.EtcOperateMode == PosConst.ETC_OPERATION_MODE.MENU_EXECUTE)
                {
                    btnPluLoad.Visible = false;
                    txtBarCode.Size = new Size(420, 40);
                }
                else
                {
                    btnPluLoad.Visible = true;
                    txtBarCode.Size = new Size(315, 40);
                }

                //if (m_cPosStatus.Mst.CntryDiv == ItemConst.CNTRY_DIV.KR && m_cPosStatus.Base.BrandCd == PosConst.MST_BRAND_CODE.BR_BR)
                //{
                //    // BR 이면 당일반품만 가능
                //    txtSaleDate.ReadOnly = true;
                //    btnDate.Enabled = false;
                //}
                //else
                //{
                //    txtSaleDate.ReadOnly = false;
                //    btnDate.Enabled = true;
                //}

                //#11047_[BR] 반품일자 제한 해제 
                txtSaleDate.ReadOnly = false;
                btnDate.Enabled = true;
               
                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, 12);
                
                grdSearchList.CsmGridColumnHeadersHeight = 34;              //DataGridView 자체의 컬럼 헤더 높이
                grdSearchList.CsmGridRowsHeight = 35;
                grdSearchList.CsmGridColumnCount = 9;                       //그리드의 컬럼수
                grdSearchList.CsmGridShowPageRowsCount = 8;                //그리드의 한 화면에 보이는 로우수    
                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[] { 100, 50, 100, 80, 90, 0, 0, 0, 0 });   //컬럼넓이 지정
                grdSearchList.CsmGridAlignment(new int[] { 1, 1, 2, 1, 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, "TRADE_KIND");
                grdSearchList.CsmGridColumnName(6, "ORG_INFO");
                grdSearchList.CsmGridColumnName(7, "RTN_INFO");
                grdSearchList.CsmGridColumnName(8, "AMT_DUTCHPAY_YN");
                
                //그리드 초기화 테이블
                m_dtSearchList = new DataTable("REFUND_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("TRADE_KIND", typeof(string)));
                m_dtSearchList.Columns.Add(new DataColumn("ORG_INFO", typeof(string)));
                m_dtSearchList.Columns.Add(new DataColumn("RTN_INFO", typeof(string)));
                m_dtSearchList.Columns.Add(new DataColumn("AMT_DUTCHPAY_YN", 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);
            }
        }

        /// <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_0076));
                cbTradeType.Items.Add("2. " + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0075));
                cbTradeType.Items.Add("3. " + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0345));

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

        /// <summary>
        /// 이미지로드
        /// </summary>
        private void GetBtnImg()
        {
            try
            {
                //승인 종류 버튼 테마색상 적용!
                if (m_cPosStatus.ScnMst.ThemeColor.Length == 9)
                {
                    btnEnter.BackColor = CmUtil.GetColorToString(m_cPosStatus.ScnMst.ThemeColor);
                    btnPluLoad.BackColor = CmUtil.GetColorToString(m_cPosStatus.ScnMst.ThemeColor);
                }

                //네이게이션 버튼 이미지 적용!

                btnUp.DefaultImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_UP1_BASIC);
                btnUp.ClickImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_UP1_PRESS);
                btnUp2.DefaultImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_UP2_BASIC);
                btnUp2.ClickImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_UP2_PRESS);
                
                btnDw.DefaultImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_DOWN1_BASIC);
                btnDw.ClickImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_DOWN1_PRESS);
                btnDw2.DefaultImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_DOWN2_BASIC);
                btnDw2.ClickImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_DOWN2_PRESS);

            }
            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)         // 조회
                {
                    TradeDealSearch("", "", "", "");
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnEnter)     // 반품
                {
                    //#20171023 start , phj 
                    //반품 시도 후 승인반품 화면에서 그냥 화면을 닫고, 
                    //그리드 선택없이 반품 버튼을 눌러 반품을 시도하면
                    //trade_div가 재리딩되지 않으므로 거래구분이 거꾸로 들어간다.
                    grdSearchItem_GridClickEvent(grdSearchList, grdSearchList.CsmGridSelectedRowIndex.ToString());
                    //#20171023 end , phj
                    ReturnTrade();
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnPluLoad)    // 내역복원
                {
                    LoadPluTrade();
                }
                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)
        {
            string sJnlText = "";
            try
            {
                if (grdSearchList.CsmGridRowsCount == 0) return;

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

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

                //(영업일자,POS번호,판매금액,거래번호,거래시간,거래구분)
                string sSaleDate = m_cPosStatus.Global.CultureToDate(grdSearchList.CsmGridGetCell(nRow, 0));
                string sPosNo = grdSearchList.CsmGridGetCell(nRow, 1);
                string sNetAmt = grdSearchList.CsmGridGetCell(nRow, 2);
                string sTradeNo = grdSearchList.CsmGridGetCell(nRow, 3);
                string sTradeKind = grdSearchList.CsmGridGetCell(nRow, 5);
                string sOrgInfo = grdSearchList.CsmGridGetCell(nRow, 6);
                string sRtnInfo = grdSearchList.CsmGridGetCell(nRow, 7);

                //#17662 PC 연세세브란스 - 결제진행전 신용카드 결제내역이 이미 등록되어있던 증상 start
                //로그 추가
                UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     " TradeDiv: " + m_cTrnStatus.Head.TradeDiv +
                                     " ,SaleDate : " + sSaleDate +
                                     " ,PosNo : " + sPosNo +
                                     " ,TradeNo : " + sTradeNo +
                                     " ,TradeKind : " + sTradeKind +
                                     " ,OrgInfo : " + sOrgInfo +
                                     " ,RtnInfo : " + sRtnInfo);
                //#17662 PC 연세세브란스 - 결제진행전 신용카드 결제내역이 이미 등록되어있던 증상 end

                //if (m_bServerTranCall == false)
                //{
                //    // 거래데이터 로딩 처리
                //    bool bRet = m_cSaleRefund.LoadLocalTran(sSaleDate, sPosNo, sTradeNo);
                //    if (bRet == false) return;
                //}
                //m_cDataService.UpdateTranAmount();

                // 저널 데이터 조회
                //ISaleCompleteUs cSaleComplete = (ISaleCompleteUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.SALE_COMPLETE);
                //string sJnlData = cSaleComplete.GetDisplayPrintData(sSaleDate, sPosNo, sTradeNo);

                //if (sTradeKind.StartsWith(ItemConst.TRAN_DIV.REFUND) == true)
                //{
                //    // 반품 영수증
                //    sJnlText += MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0249) + PosConst.CRLF;
                //    if (sOrgInfo.Length >= 15)
                //        sJnlText += "     " + MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0250) + " " + sOrgInfo.Substring(0, 8) + "-" + sOrgInfo.Substring(8, 2) + "-" + sOrgInfo.Substring(10, 5)
                //                 + PosConst.CRLF + PosConst.CRLF;
                //}
                //else if (sRtnInfo != "")
                //{
                //    // 반품된 영수증
                //    sJnlText += MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0251) + PosConst.CRLF;
                //    if (sRtnInfo.Length >= 15)
                //        sJnlText += "     " + MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0252) + " " + sRtnInfo.Substring(0, 8) + "-" + sRtnInfo.Substring(8, 2) + "-" + sRtnInfo.Substring(10, 5)
                //                 + PosConst.CRLF + PosConst.CRLF;
                //}


                //// 저널 텍스트 편집
                //int iDataLen = 0;
                //while (iDataLen <= sJnlData.Length)
                //{
                //    sJnlText += CmUtil.MidH(sJnlData, iDataLen + 5, 42) + PosConst.CRLF;
                //    iDataLen += 47;
                //}

                //txtPrtData.Text = sJnlText;

                // 저널 데이터 조회
                string sJnlData = m_cSaleRefund.SearchPrintSaleReceiptDetail(sSaleDate, sPosNo, sTradeNo);

                //string sJnlText = "";
                if (sTradeKind.StartsWith(ItemConst.TRAN_DIV.REFUND) == true)
                {
                    // 반품 영수증
                    sJnlText += MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0249) + PosConst.CRLF;
                    if (sOrgInfo.Length >= 15)
                        sJnlText += "     " + MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0250) + " " + sOrgInfo.Substring(0, 8) + "-" + sOrgInfo.Substring(8, 2) + "-" + sOrgInfo.Substring(10, 5)
                                 + PosConst.CRLF + PosConst.CRLF;
                }
                else if (sRtnInfo != "")
                {
                    // 반품된 영수증
                    sJnlText += MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0251) + PosConst.CRLF;
                    if (sRtnInfo.Length >= 15)
                        sJnlText += "     " + MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0252) + " " + sRtnInfo.Substring(0, 8) + "-" + sRtnInfo.Substring(8, 2) + "-" + sRtnInfo.Substring(10, 5)
                                 + PosConst.CRLF + PosConst.CRLF;
                }

                //#해피앱 추후적립 start, sskim
                //해피앱 추후적립 데이터 서버 조회
                if (m_cPosStatus.Mst.CntryDiv == ItemConst.CNTRY_DIV.KR)
                {
                    if (sTradeKind.StartsWith(ItemConst.TRAN_DIV.REFUND) == false)
                    {
                        string sHpAppAfterSave = m_cSaleRefund.SearchServerHpAppSave(sSaleDate, sPosNo, sTradeNo, true);
                    }
                }
                //#해피앱 추후적립 end, sskim
                
                if (m_bServerTranCall == false)
                {
                    //#17662 PC 연세세브란스 - 결제진행전 신용카드 결제내역이 이미 등록되어있던 증상 start
                    //로그 추가
                    UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                         System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                         "* 거래데이터 로딩 => " +
                                         " TradeDiv: " + m_cTrnStatus.Head.TradeDiv +
                                         " ,SaleDate : " + sSaleDate +
                                         " ,PosNo : " + sPosNo +
                                         " ,TradeNo : " + sTradeNo);
                    //#17662 PC 연세세브란스 - 결제진행전 신용카드 결제내역이 이미 등록되어있던 증상 end

                    // 거래데이터 로딩 처리
                    bool bRet = m_cSaleRefund.LoadLocalTran(sSaleDate, sPosNo, sTradeNo);
                    if (bRet == false) return;
                }
                m_cDataService.UpdateTranAmount();

                #region 기존 저널 로드 로직 백업 
                //// 저널 텍스트 편집
                //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;
                //}

                //// 추후적립 내역 
                //ISaleCompleteUs cSaleComplete = (ISaleCompleteUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.SALE_COMPLETE);
                //string sAftData = cSaleComplete.AddHappyPointAfterSave(sSaleDate, sPosNo, sTradeNo);
                //if (sAftData != "")
                //{
                //    iDataLen = 0;
                //    while (iDataLen <= sAftData.Length)
                //    {
                //        sJnlText += CmUtil.MidH(sAftData, iDataLen + 5, 42) + PosConst.CRLF;
                //        iDataLen += 47;
                //    }
                //}

                //txtPrtData.Text = sJnlText;
                //txtPrtData.Tag = sJnlData; 
                #endregion 

                int iDataLen = 0;

                //1.추후적립 내역이 있는지 확인 한다!
                //2.데이터를 담아 둔다(커팅 제외)
                //3.원거래 읽어 온다
                //4.1 추후가 있으면 바코드 또는 고객용을 체크한다
                //4.2 추후영수증을 넣는다.
                //4.3 추후가 없으면 현재 영수증을 넣는다.

                string sAfterJnlData = "";
                string sAfterJnlText = "";

                // 추후적립 내역 
                ISaleCompleteUs cSaleComplete = (ISaleCompleteUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.SALE_COMPLETE);
                string sAftData = cSaleComplete.AddHappyPointAfterSave(sSaleDate, sPosNo, sTradeNo);

                if (sAftData != "")
                {
                    iDataLen = 0;
                    while (iDataLen <= CmUtil.LenH(sAftData))
                    {
                       
                        if (CmUtil.MidH(sAftData, iDataLen + 5, 42).Trim() != "")
                        {
                            sAfterJnlText += CmUtil.MidH(sAftData, iDataLen + 5, 42) + PosConst.CRLF;

                            if (CmUtil.MidH(sAftData, iDataLen, 5) != PosConst.PRT_HDR.PRT_CUT)
                            {
                                sAfterJnlData += CmUtil.MidH(sAftData, iDataLen, 47);
                            }
                        }
                        iDataLen += 47;
                    }
                }

                string sPrtJnlData = "";

                iDataLen = 0;

                //#해피앱 추후적립 start, sskim
                #region 해피앱 추후적립 내역 영수증 추가
                /*
                if (sTradeKind.StartsWith(ItemConst.TRAN_DIV.REFUND) == false)
                {

                    // 해피앱 추후적립 내역 
                    string sHpAppAftData = cSaleComplete.AddHappyPointHpAppAfterSave(sSaleDate, sPosNo, sTradeNo);

                    if (sHpAppAftData != "")
                    {
                        iDataLen = 0;
                        while (iDataLen <= CmUtil.LenH(sHpAppAftData))
                        {

                            if (CmUtil.MidH(sHpAppAftData, iDataLen + 5, 42).Trim() != "")
                            {
                                sAfterJnlText += CmUtil.MidH(sHpAppAftData, iDataLen + 5, 42) + PosConst.CRLF;

                                if (CmUtil.MidH(sHpAppAftData, iDataLen, 5) != PosConst.PRT_HDR.PRT_CUT)
                                {
                                    sAfterJnlData += CmUtil.MidH(sHpAppAftData, iDataLen, 47);
                                }
                            }
                            iDataLen += 47;
                        }
                    }

                    sPrtJnlData = "";

                    iDataLen = 0;
                }
                */ 
                #endregion
                //#해피앱 추후적립 end, sskim

                // 저널 텍스트 편집
                while (iDataLen <= CmUtil.LenH(sJnlData))
                {

                    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;
                    }
                    //#20180625 영수증반품, 영수증재발행에서 영수증 조회시 추후적립내역 미표시 증상 수정 start
                    //기존
                    //else if (sAfterJnlText != "" && (sJnlHdr == PosConst.PRT_HDR.PRT_BA1 || CmUtil.MidH(sJnlData, iDataLen + 5, 42).Trim().Replace("[", "").StartsWith(MessageManager.GetPrintMessage(POS_MESSAGE.PRINT.MSG_0136))))
                    //변경
                    else if (sAfterJnlText != "" && 
                             (sJnlHdr == PosConst.PRT_HDR.PRT_BA1 ||
                              sJnlHdr == PosConst.PRT_HDR.PRT_BAR || 
                              CmUtil.MidH(sJnlData, iDataLen + 5, 42).Trim().Replace("[", "").StartsWith(MessageManager.GetPrintMessage(POS_MESSAGE.PRINT.MSG_0136))))
                    //#20180625 영수증반품, 영수증재발행에서 영수증 조회시 추후적립내역 미표시 증상 수정 end
                    {

                        sJnlText += sAfterJnlText;
                        sPrtJnlData += sAfterJnlData;

                        sJnlText += CmUtil.MidH(sJnlData, iDataLen + 5, 42) + PosConst.CRLF;

                        sAfterJnlText = "";
                        sAfterJnlData = "";
                    }
                    else
                    {
                        sJnlText += CmUtil.MidH(sJnlData, iDataLen + 5, 42) + PosConst.CRLF;
                    }


                    sPrtJnlData += CmUtil.MidH(sJnlData, iDataLen, 47);

                    iDataLen += 47;
                }


                txtPrtData.Text = sJnlText;
                txtPrtData.Tag = sPrtJnlData; 

            }
            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 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 (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 User Method
        /// <summary>
        /// 거래 데이터 조회
        /// </summary>
        private void TradeDealSearch(string sSaleDate, string sPosNo, string sTradeNo, string sPayTime)
        {
            try
            {
                if (sSaleDate == "" && txtSaleDate.Text.Length != 10)
                {
                    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);
                    sPosNo = txtPosNo.Text;
                    sTradeNo = txtTradeNo.Text;
                    sTradeType = cbTradeType.Text.Substring(0, 1);
                }

                // 거래데이터 조회
                DataTable dtData = m_cSaleRefund.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");
                        int nSign = CmUtil.GetDataRowStr(dr, "TRADE_DIV") == "1" ? -1 : 1;
                        drNewRow["TOTSALE_AMT"] = m_cPosStatus.Global.NumericTOCurrency(CmUtil.GetDataRowDouble(dr, "NET_SALE_AMT") * nSign);
                        drNewRow["TRADE_NO"] = CmUtil.GetDataRowStr(dr, "TRADE_NO");
                        drNewRow["SYS_TIME"] =  CmUtil.StrToTime(CmUtil.GetDataRowStr(dr,"PAY_TIME"));
                        drNewRow["TRADE_KIND"] = CmUtil.GetDataRowStr(dr,"TRADE_DIV") + CmUtil.GetDataRowStr(dr,"TRADE_KINDPER");
                        drNewRow["ORG_INFO"] = CmUtil.GetDataRowStr(dr,"ORG_INFO");
                        drNewRow["RTN_INFO"] = CmUtil.GetDataRowStr(dr,"RTN_INFO");
                        drNewRow["AMT_DUTCHPAY_YN"] = CmUtil.GetDataRowStr(dr, "AMT_DUTCHPAY_YN");

                        m_dtSearchList.Rows.Add(drNewRow);
                    }
                }
                else if ( sSaleDate != "" && sPosNo != "" && (sTradeNo != "" || sPayTime != ""))
                {
                    // 서버 거래 호출 처리
                    string sRet = m_cSaleRefund.SearchServerTran(sSaleDate, sPosNo, sTradeNo, sPayTime);
                    if (sRet == UserCom.RST_OK)
                    {
                        // 판매 거래만 반품 가능
                        if (m_cTrnStatus.Head.TradeKind != ItemConst.TRAN_KIND.NORMAL.SALE)
                        {
                            WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0262);
                            m_cDataService.TranComplete();
                        }
                        else
                        {
                            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["TRADE_KIND"] = m_cTrnStatus.Head.TradeDiv + m_cTrnStatus.Head.TradeKind;
                            drNewRow["ORG_INFO"] = m_cTrnStatus.Head.OrgSaleDate;
                            drNewRow["RTN_INFO"] = m_cTrnStatus.Head.RefundInfo;
                            drNewRow["AMT_DUTCHPAY_YN"] = m_cTrnStatus.Head.AmtDutchPayYn;

                            m_dtSearchList.Rows.Add(drNewRow);

                            m_bServerTranCall = true;
                        }
                    }
                }
                else 
                {
                    WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0302));
                }
                
                // 그리드 적용
                grdSearchList.CsmGridDataSource = m_dtSearchList;

                grdSearchList.CsmGridIndicateForeColor = Color.Red;
                if (m_dtSearchList != null && m_dtSearchList.Rows.Count > 0)
                {
                    int nRow = 0;
                    foreach (DataRow dr in m_dtSearchList.Rows)
                    {
                        //#20170928 낱개 반품 한 영수증 반품 기능 start
                        //기존
                        //if (CmUtil.GetDataRowStr(dr, "TRADE_KIND").StartsWith("1") || CmUtil.GetDataRowStr(dr, "RTN_INFO") != "")
                        //변경
                        if (CmUtil.GetDataRowStr(dr, "RTN_INFO") != "" || CmUtil.GetDataRowStr(dr, "ORG_INFO") != "")
                        //#20170928 낱개 반품 한 영수증 반품 기능 end
                        grdSearchList.CsmGridIndicateRow(nRow, true);
                        nRow++;
                    }
                }

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

        /// <summary>
        /// 반품처리
        /// </summary>
        /// <returns></returns>
        private bool ReturnTrade()
        {
            bool bRet = false;

            try
            {
                string sNewTradeNo = m_cPosStatus.Base.TradeNo;

                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 sTradeNo = grdSearchList.CsmGridGetCell(nRow, 3);
                string sTradeKind = grdSearchList.CsmGridGetCell(nRow, 5);
                string sOrgInfo = grdSearchList.CsmGridGetCell(nRow, 6);
                string sRtnInfo = grdSearchList.CsmGridGetCell(nRow, 7);
                string sDutchPayYn = grdSearchList.CsmGridGetCell(nRow, 8);

                //#20180416 반품시 영수증 데이터 서버로 조회한 경우 반품승인창 종료 후 재시도시 정상 영수증으로 처리 되는 증상 수정 start
                //영수증 서버 조회 -> 반품 버튼 -> 반품승인창 -> 창 종료 -> 반품 버튼 -> 반품승인창 -> 승인취소 -> 반품 완료 -> 정상 영수증 생성
                m_cTrnStatus.Head.TradeDiv = sTradeKind.Substring(0, 1);
                //#20180416 반품시 영수증 데이터 서버로 조회한 경우 반품승인창 종료 후 재시도시 정상 영수증으로 처리 되는 증상 수정 end

                //#20180119 인천공항 반품시 공항포스 체크기능 제외 start
                /*
                //#20171227 인천공항 포스연동 start, phj
                if (PosMstManager.GetPosOption(POS_OPTION.OPT512) == "1")
                {
                    // 인천공항 pos에서 결제내역 조회
                    
                    //#20180119 start,phj
                    //기존
                    //if (m_cAirPortTran.i_return_Data(sSaleDate, sTradeNo, sNewTradeNo, "1", "N") != 1)
                    //변경
                    //원거래일자에서 영업일자로 변경.
                    //공항포스 18일 결제 후 19일 반품 시 --> 자사포스 18일자로 반품 요청하기 때문에 에러남. 19일자로 요청하도록 변경.

                    UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "IncheonAirport Return YN Check!!! --> Sale_Dt :" + m_cPosStatus.Base.SaleDate + ", TradeNo :" + sTradeNo + ", NewTradeNo :" + sNewTradeNo );

                    if (m_cAirPortTran.i_return_Data(m_cPosStatus.Base.SaleDate, sTradeNo, sNewTradeNo, "1", "N") != 1)
                    //#20180119 end,phj

                    {
                        //WinManager.ConfirmMessage("통합POS에서 반품되지 않은 영수증 입니다.");
                        //WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0764);

                        //#20180119 start,phj
                        UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "IncheonAirport Return YN Check!!! --> false ");
                        //#20180119 end,phj

                        return false;
                    }
                }
                //#20171227 인천공항 포스연동 end, phj
                */
                //#20180119 인천공항 반품시 공항포스 체크기능 제외 end


                //#20171020 log 추가 
                UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "TradeDiv: " + m_cTrnStatus.Head.TradeDiv +
                                     "SaleDate : " + sSaleDate + 
                                     "PosNo : " + sPosNo +
                                     "TradeNo : " + sTradeNo +
                                     "TradeKind : " + sTradeKind +
                                     "OrgInfo : " + sOrgInfo +
                                     "RtnInfo : " + sRtnInfo +
                                     "DutchPayYn : " + sDutchPayYn);

                //////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // 반품 가능여부 체크
                //////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //#20170928 낱개 반품 한 영수증 반품 기능 start
                //기존
                //if (sTradeKind.StartsWith(ItemConst.TRAN_DIV.REFUND) == true)
                //변경
                if ((sTradeKind.StartsWith(ItemConst.TRAN_DIV.REFUND) == true) && (sOrgInfo != ""))
                //#20170928 낱개 반품 한 영수증 반품 기능 end
                {
                    // 반품 영수증
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0230);
                    return bRet;
                }
                else if (sRtnInfo != "")
                {
                    // 반품된 영수증
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0229);
                    return bRet;
                }
                //#20170928 낱개 반품 한 영수증 반품 기능 start
                
                else if (sOrgInfo != "")
                {
                    // 반품된 영수증
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0229);
                    return bRet;
                }
                //#20170928 낱개 반품 한 영수증 반품 기능 end


                //else if (sDutchPayYn == "1")
                //{
                //    // 금액 더치페이 거래!
                //    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0630);
                //    return bRet;
                //}

                // 해피오더 매출의 경우 알림 메시지 변경
                //if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0253) != true) return bRet;
                //if (sTradeKind == ItemConst.TRAN_KIND.FORIGN.O2O)
                //170914 dkshin 해피오더 매출의 경우 알림 메시지 변경(반품)
                if( sTradeKind.Substring(1) == ItemConst.TRAN_KIND.FORIGN.O2O)
                {
                    if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0728) != true) return bRet;
                }
                else
                {
                    if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0253) != true) return bRet;
                }

                if (m_bServerTranCall == false)
                {
                    // 반품 가능여부 체크
                    bRet = m_cSaleRefund.ChekcRefundTran(sSaleDate, sPosNo, sTradeNo);
                    if (bRet == false) return bRet;
                }


                //#20171020 log 추가 
                UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                    "반품시작!!! -> 거래구분 : " + m_cTrnStatus.Head.TradeDiv + "(" + m_cTrnStatus.Head.TradeNo + ")");

                //////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // 반품 사유코드 등록
                //////////////////////////////////////////////////////////////////////////////////////////////////////////////
                frmSelReasonCode fForm = (frmSelReasonCode)FormManager.GetForm(FormManager.FORM_REASON_CODE);
                if (fForm == null)
                {
                    fForm = new frmSelReasonCode();
                    FormManager.AddForm(FormManager.FORM_REASON_CODE, fForm);
                }
                fForm.ReasonGroup = PosConst.COMMON_CODE_GROUP.Z0008;    // 사유 그룹코드
                if (fForm.ShowDialog() != DialogResult.OK) return false;
                
                m_cTrnStatus.Head.RtnReasonCd = fForm.ReasonCode;       // 선택된 사유코드
                m_cTrnStatus.Head.RtnReasonMemo = fForm.ReasonName;     // 선택된 사유명

                // 거래구분 설정 => 반품
                //#20170928 낱개 반품 한 영수증 반품 기능 start
                //기존
                //m_cTrnStatus.Head.TradeDiv = ItemConst.TRAN_DIV.REFUND;
                //변경
                
                if (m_cTrnStatus.Head.TradeDiv == ItemConst.TRAN_DIV.REFUND)
                {
                    m_cTrnStatus.Head.TradeDiv = ItemConst.TRAN_DIV.NORMAL;
                }
                else
                {
                    m_cTrnStatus.Head.TradeDiv = ItemConst.TRAN_DIV.REFUND;
                }

                //#20170928 낱개 반품 한 영수증 반품 기능 end

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


                //#20171020 log 추가 
                UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                    "거래구분: " + m_cTrnStatus.Head.TradeDiv + "(" + m_cTrnStatus.Head.TradeNo + ")" +
                    "반품코드: " + m_cTrnStatus.Head.RtnReasonCd +
                    "반품메모: " + m_cTrnStatus.Head.RtnReasonMemo);

                //#20180119 인천공항 반품시 공항포스 체크기능 제외 start
                /*
                //#20171227 인천공항 포스연동 start, phj
                if (PosMstManager.GetPosOption(POS_OPTION.OPT512) == "1")
                {
                    // 인천공항 pos에서 결제내역 조회
                    
                    //#20180119 start,phj
                    //기존
                    //if (m_cAirPortTran.i_return_Data(sSaleDate, sTradeNo, sNewTradeNo, "1", "Y") != 1)
                    //변경
                    //원거래일자에서 영업일자로 변경.
                    //공항포스 18일 결제 후 19일 반품 시 --> 자사포스 18일자로 반품 요청하기 때문에 에러남. 19일자로 요청하도록 변경.

                    UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                         System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                         System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                         "IncheonAirport Return Try!!! --> Sale_Dt :" + m_cPosStatus.Base.SaleDate + ", TradeNo :" + sTradeNo + ", NewTradeNo :" + sNewTradeNo);

                    if (m_cAirPortTran.i_return_Data(m_cPosStatus.Base.SaleDate, sTradeNo, sNewTradeNo, "1", "Y") != 1)
                    //#20180119 end,phj 

                    {
                        //WinManager.ConfirmMessage("통합POS에서 반품되지 않은 영수증 입니다.");
                        //WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0764);
                        //#20180119 start,phj
                        UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "IncheonAirport Return Try!!! --> false ");
                        //#20180119 end,phj

                        return false;
                    }
                }
                //#20171227 인천공항 포스연동 end, phj
                */
                //#20180119 인천공항 반품시 공항포스 체크기능 제외 end


                //////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // 영수증 반품
                //////////////////////////////////////////////////////////////////////////////////////////////////////////////
                frmRefundPay fFormPay = (frmRefundPay)FormManager.GetForm(FormManager.FORM_SAL_RETURN_RECEIPT_PAY);
                if (fFormPay == null)
                {
                    fFormPay = new frmRefundPay();
                    FormManager.AddForm(FormManager.FORM_SAL_RETURN_RECEIPT_PAY, fFormPay);
                }
                if (fFormPay.ShowDialog() != DialogResult.OK)return false;
                
                // 수동주방출력옵션 처리 
                SaleMainProcess saleMainProc = new SaleMainProcess();
                saleMainProc.MenualOrderKtchProcess();
                
                this.Update();

                // #20170616, 해피앱 스탬프 Start
                //20171025 dkshin 전문 영수증번호 전거래의 영수증번호로 중복등록되는 문제 수정-> 거래 완료(PosSaleExecute) 후 처리 start
                /*IHappyAppStamp m_cHappyAppStamp = (IHappyAppStamp)sManager.InitServiceInstance(ServiceLists.BSV_SALE.DLL, ServiceLists.BSV_SALE.HPAPP_STAMP);
                m_cTrnStatus.Sale.HappyAppMemNo = m_cHappyAppStamp.CheckHappyAppStamp();

                if (m_cPosStatus.Base.TrainingFlag == "0" &&                  // 운영모드
                    PosMstManager.GetPosOption(POS_OPTION.OPT327) == "1" &&   // 해피앱 스탬프 사용
                    m_cTrnStatus.Sale.HappyAppMemNo != "")                    // 해피앱 회원번호 존재(해피앱 고객) 
                {
                    // 해피앱 스탬프 취소
                    m_cHappyAppStamp.SetHappyAppStamp();
                }*///end
                // #20170616, 해피앱 스탬프 End

                // 거래 완료 처리
                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;

                //17.05.18 dkshin 쇼킹박스 추가
                IHoldDeal m_cHoldDeal = (IHoldDeal)sManager.InitServiceInstance(ServiceLists.BSV_SALE.DLL, ServiceLists.BSV_SALE.HOLD_DEAL);
                DataTable dt = m_cHoldDeal.SearchShockingBoxPayCompleteList(sSaleDate,sTradeNo);
                //if (dt != null || dt.Rows.Count > 0)
                if (!(dt == null || dt.Rows.Count == 0))
                {
                    DataRow dr = dt.Rows[0];

                    m_cHoldDeal.UpdateShockingBOXPayComplete(dr["SALE_DT"].ToString(),dr["POS_NO"].ToString(),dr["REG_NO"].ToString());
                }

                //2017-06-02 dkshin 해피앱 추후적립
                if (m_cPosStatus.Mst.CntryDiv == ItemConst.CNTRY_DIV.KR)
                {
                    if (m_cSaleRefund.SearchTrHpAppAfterSaveYN(sSaleDate, sPosNo, sTradeNo))
                    {
                        m_cSaleRefund.Refund_HPAPP_After_Update_Tran(sSaleDate, sPosNo, sTradeNo);
                    }
                }

                // 거래데이터 재조회
                if (m_bServerTranCall == false)
                {
                    TradeDealSearch("", "", "", "");
                }
                else
                {
                    TradeDealSearch(m_cPosStatus.Base.SaleDate, m_cPosStatus.Base.PosNo, sNewTradeNo, "");
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }

            return bRet;
        }

        /// <summary>
        /// 내역 불러오기
        /// </summary>
        /// <returns></returns>
        private bool LoadPluTrade()
        {
            bool bRet = false;

            try
            {
                if (m_cPosStatus.Sale.EtcOperateMode == PosConst.ETC_OPERATION_MODE.MENU_EXECUTE) return false; 
                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 sTradeNo = grdSearchList.CsmGridGetCell(nRow, 3);
                               
                if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0254) != true) return bRet;

                // 거래데이터 로딩 처리
                bRet = m_cSaleRefund.LoadLocalTranPlu(sSaleDate, sPosNo, sTradeNo);
                if (bRet == false) return bRet;

                //#20180529 내역불러오기 한 경우 거스름돈이 유지되는 현상 수정 start
                m_cPosStatus.Sale.ChangeCashAmt = 0;
                //#20180529 내역불러오기 한 경우 거스름돈이 유지되는 현상 수정 end

                ISalePluItemUs cPluService = (ISalePluItemUs)sManager.InitServiceInstance(ServiceLists.BSV_SALE.DLL, ServiceLists.BSV_SALE.SALE_PLU_ITEM);
                cPluService.ItemDcAllClear(true, true);

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

            return 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
                    // 기존
                    //TradeDealSearch(sSaleDate, sPosNo, "", sSaleTime);
                    TradeDealSearch(sSaleDate, sPosNo, sTradeNo, sSaleTime);
                    //#20170623, 해피앱 추후적립_바코드 수정_lsr End
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        private void btnDate_Click(object sender, EventArgs e)
        {
            try
            {
                string sDate = WinBasic.ShowForm(new string[] { FormManager.FORM_CALENDAR });
                if (sDate != "" && sDate.Length == 8)
                {
                    // 반품가능일자 : 모든회사 30일 제한 => PC가 아니면 30일로 제한(2017.07.20)
                    if (m_cPosStatus.Mst.CorpDiv != ItemConst.CORP_DIV.PC)
                    {
                        DateTime dtNew = DateTime.ParseExact(sDate, "yyyyMMdd", null);
                        if (CmUtil.LongParse(dtNew.AddDays(30).ToString("yyyyMMdd")) < CmUtil.LongParse(m_cPosStatus.Base.SaleDate))
                        {
                            string sMsg = string.Format(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0547), 30);
                            WinManager.ErrorMessage(sMsg);
                            //WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0547);
                            return;
                        }
                    }
                    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);
            }
        }

        private void txtSaleDate_Load(object sender, EventArgs e)
        {

        }

        private void grdSearchItem_GridKeyDownEvent(object sender, string sMenuKey)
        {
            try
            {
                if(sMenuKey == PosKey.MENU_KEY.SCANKEY_UP_ARROW)
                {
                    grdSearchList.CsmGridScroll("UP");
                }
                else if(sMenuKey == PosKey.MENU_KEY.SCANKEY_DOWN_ARROW)
                {
                    grdSearchList.CsmGridScroll("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);
            }
        }

    }
}
