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

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

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 외상
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Win
{
    public partial class frmSaleOnCustomer : Form
    {

        #region 변수 선언

        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        private PosStatus m_cPosStatus = new PosStatus();                           // 기본정보 참조
        private TranStatus m_cTrnStatus = new TranStatus();                         // 거래정보 참조        
        private DeviceStatus m_cDevStatus = new DeviceStatus();                     // 디바이스 관리

        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스
        private IDataProcessUs m_cDataService = null;
        private IPaymentUs m_cSaleOnCustomer = null;

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

        private bool bNotDoubleClik = false;                                        // 더블 클릭 방지용

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

        /// <summary>
        /// 입력구분
        /// </summary>
        private string m_sInPutType = "";
        /// <summary>
        /// 입력데이터
        /// </summary>
        private string m_sInPutData = "";
        /// <summary>
        /// 카드데이터
        /// </summary>
        private string m_sInEncData = "";
        /// <summary>
        /// 결제구분
        /// </summary>
        private string m_sPay_DC_Grp_Type = "";
        /// <summary>
        /// 결제상세구분
        /// </summary>
        private string m_sPay_DC_CD = "";

        #endregion 변수 선언

        #region 생성자 & 소멸자 & 폼초기화
        public frmSaleOnCustomer()
        {
            InitializeComponent();

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

            m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
            m_cTrnStatus = (TranStatus)StateObject.TRAN;    // POS 거래정보 
            m_cDataService = (IDataProcessUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_SERVICE);
            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
            m_cSaleOnCustomer = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.SALEONCUSTOMER);
        }

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

            // Rhee, 2017/09/22 딜리버리 외매(선매) 추가 -- START
            if (m_sPosMenuKey == "00293")        
            {
                // 딜리버리 외매(선매) 조회
                SearchTxtInPut("4");
            }
            // Rhee, 2017/09/22 딜리버리 외매(선매) 추가 -- END
        }

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

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

        private void frmSaleOnCustomer_FormClosing(object sender, FormClosingEventArgs e)
        {
            UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", lblTitle.Text);
        }

        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            try
            {
                // 이미지 로딩 처리
                this.Size = new Size(800, 578);
                this.Location = new Point(1024 - 800 - 10, 768 - 600);
                picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_800X578);
                picBack.Location = new Point(0, 0);

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

                //테마색상 적용!
                btnEnter.BackColor = CmUtil.GetColorToString(m_cPosStatus.ScnMst.ThemeColor);
                padInPut.ThemeColor = m_cPosStatus.ScnMst.ThemeColor;
                padInPut.ClearBtnText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0817);
                padInPut.SearchBtnText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1018);

                //버튼이미지 적용
                btnAllPgUp.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_14X9_UP2_BASIC);
                btnAllPgUp.ImageAlign = ContentAlignment.MiddleCenter;
                btnAllPgUp.BorderStyle = BorderStyle.None;
                btnAllPgDw.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_14X9_DOWN2_BASIC);
                btnAllPgDw.ImageAlign = ContentAlignment.MiddleCenter;
                btnAllPgDw.BorderStyle = BorderStyle.None;
                btnAllUp.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_14X9_UP1_BASIC);
                btnAllUp.ImageAlign = ContentAlignment.MiddleCenter;
                btnAllUp.BorderStyle = BorderStyle.None;
                btnAllDw.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.NAVIBTN_14X9_DOWN1_BASIC);
                btnAllDw.ImageAlign = ContentAlignment.MiddleCenter;
                btnAllDw.BorderStyle = BorderStyle.None;

                if (btnAllPgUp.Image != null) btnAllPgUp.Text = "";
                if (btnAllPgDw.Image != null) btnAllPgDw.Text = "";
                if (btnAllUp.Image != null) btnAllUp.Text = "";
                if (btnAllDw.Image != null) btnAllDw.Text = "";

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

                // 타이틀
                if (m_sPosMenuKey == PosKey.MENU_KEY.CREDIT_CUSTOMER) lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0283);

                m_sPay_DC_Grp_Type = ItemConst.TR_ITEM_ID.CREDIT_ITEM;
                // Rhee, 2017/09/22 딜리버리 외매(선매) 추가 -- START
                // 기존
                //m_sPay_DC_CD = ItemConst.TR_ITEM_ID.CREDIT.CREDIT_PAY;

                // 변경
                if (m_sPosMenuKey == "00293")
                {                                   // 딜리버리(외매)
                    m_sPay_DC_CD = ItemConst.TR_ITEM_ID.CREDIT.CREDIT_PAY_DELIVERY;
                    btnSearchType1.Visible = false;
                    btnSearchType2.Visible = false;
                    btnSearchType3.Visible = true;
                }
                else
                {                                   // 외상
                    m_sPay_DC_CD = ItemConst.TR_ITEM_ID.CREDIT.CREDIT_PAY;
                    btnSearchType1.Visible = true;
                    btnSearchType2.Visible = true;
                    btnSearchType3.Visible = false;
                }
                // Rhee, 2017/09/22 딜리버리 외매(선매) 추가 -- END

                lblSaleAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0037);                       // 받을금액
                lblPayAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0049);                        // 결제금액 *
                lblCustNM.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0287);                        // 고 객 명
                lblTel.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0279);                           // 전화번호
                lblDCAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0036);                         // 할인금액

                lblCustID.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0369);                        // 검색코드

                btnSearch.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0309);                        // 고객찾기
                btnEnter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0057);                         // 승인

                btnSearchType1.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0284);
                btnSearchType2.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0285);
                // Rhee, 2017/09/22 딜리버리 외매(선매) 추가 -- START
                btnSearchType3.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1036);                   // 딜리버리(외매) - 외상
                // Rhee, 2017/09/22 딜리버리 외매(선매) 추가 -- END

                txtSaleAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cTrnStatus.Sale.RemainPayAmt);            // 받을금액 
                txtPayAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cTrnStatus.Sale.RemainPayAmt);             // 결제금액
                txtPayAmt.ReadOnly = true;
                txtPayAmt.Enabled = false;

                txtDCAmt.Text = "0";                                                                                // 할인금액
                
                m_sInPutType = "";                                                                                  // 입력구분
                m_sInPutData = "";                                                                                  // 입력데이터
                m_sInEncData = "";                                                                                  // 카드데이터

                DataGridSetting();                                                                                  // 그리드 초기화

                txtCustNo.Text = "";                                                                                // 고객번호
                txtCustNm.Text = "";                                                                                // 고객명
                txtTel.Text = "";                                                                                   // 전화번호
                txtPayAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cTrnStatus.Sale.RemainPayAmt);             // 결제금액
                txtCustID.Text = "";

                bNotDoubleClik = false;

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

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

                if ((UI.CsmButton)sender == btnAllUp)                               // 상단 그리드 Up
                {
                    if (dgvData.Rows.Count == 0)
                    {
                        bNotDoubleClik = false;
                        return;
                    }
                    if (dgvData.CurrentRow.Index > 0)
                    {
                        for (int iLoop = dgvData.CurrentRow.Index - 1; iLoop >= 0; iLoop--)
                        {
                            if (dgvData.Rows[iLoop].Visible == false) continue;

                            dgvData.Rows[iLoop].Selected = true;
                            dgvData.Rows[iLoop].Cells[dgvData.CurrentCell.ColumnIndex].Selected = true;
                            break;
                        }
                    }
                }
                else if ((UI.CsmButton)sender == btnAllDw)                          // 상단 그리드 Down
                {
                    if (dgvData.Rows.Count == 0)
                    {
                        bNotDoubleClik = false;
                        return;
                    }
                    
                    if (dgvData.CurrentRow.Index < dgvData.Rows.Count - 1)
                    {
                        if (dgvData.Rows.Count == 0)
                        {
                            bNotDoubleClik = false;
                            return;
                        }
                        for (int iLoop = dgvData.CurrentRow.Index + 1; iLoop <= dgvData.Rows.Count - 1; iLoop++)
                        {
                            if (dgvData.Rows[iLoop].Visible == false) continue;

                            dgvData.Rows[iLoop].Selected = true;
                            dgvData.Rows[iLoop].Cells[dgvData.CurrentCell.ColumnIndex].Selected = true;
                            break;
                        }
                    }
                }
                else if ((UI.CsmButton)sender == btnAllPgUp)                               // 상단 그리드 PgUp
                {
                    if (dgvData.Rows.Count == 0 || dgvData.CurrentRow.Index <= 0)
                    {
                        bNotDoubleClik = false;
                        return;
                    }

                    int nPageRow = 13;
                    int iLoop = dgvData.CurrentRow.Index - nPageRow;
                    if (iLoop <= 0) iLoop = 0;

                    dgvData.Rows[iLoop].Selected = true;
                    dgvData.Rows[iLoop].Cells[dgvData.CurrentCell.ColumnIndex].Selected = true;
                }
                else if ((UI.CsmButton)sender == btnAllPgDw)                          // 상단 그리드 PgDown
                {
                    if (dgvData.Rows.Count == 0)
                    {
                        bNotDoubleClik = false;
                        return;
                    }

                    int nPageRow = 13;
                    int iLoop = dgvData.CurrentRow.Index + nPageRow;

                    if (iLoop >= dgvData.Rows.Count - 1) iLoop = dgvData.Rows.Count - 1;

                    if (iLoop != dgvData.CurrentRow.Index)
                    {
                        dgvData.Rows[iLoop].Selected = true;
                        dgvData.Rows[iLoop].Cells[dgvData.CurrentCell.ColumnIndex].Selected = true;
                    }
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnSearchType1)           // 개인
                {                    
                    // 조회
                    SearchTxtInPut("2");
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnSearchType2)           // 법인
                {
                    // 조회
                    SearchTxtInPut("1");
                }
                // Rhee, 2017/09/22 딜리버리 외매(선매) 추가 -- START
                else if (((Cosmos.UI.CsmButton)sender) == btnSearchType3)           // 딜리버리(외매) - 외상
                {
                    // 조회
                    SearchTxtInPut("4");
                }
                // Rhee, 2017/09/22 딜리버리 외매(선매) 추가 -- END
                else if (((Cosmos.UI.CsmButton)sender) == btnSearch)                // 고객찾기
                {
                    // 조회
                    SearchTxtInPut("");
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnEnter)                 // 승인
                {
                    if (m_sPosMenuKey == "00293")
                    {
                        // 승인
                        //sRet = UserCom.RST_OK;
                        sRet = CompleteTxtInPut();
                    }
                    else
                    {
                        // 승인
                        sRet = CompleteTxtInPut();
                    }
                    bNotDoubleClik = false;
                    if (sRet != UserCom.RST_OK) return;

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

        /// <summary>
        /// 닫기
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            try
            {
                txtEditBox_EditBoxKeyDownEvent(null, PosKey.MENU_KEY.ESC_PREVIOUS);
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion

        #region 텍스트박스 키 입력 이벤트 처리 
        /// <summary>
        /// 텍스트박스 키 입력 이벤트 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="sFuncValue"></param>
        private void txtEditBox_EditBoxKeyDownEvent(object sender, string sFuncValue)
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                if (sFuncValue == PosKey.MENU_KEY.ENTER)
                {
                    //if (((Cosmos.UI.CsmPosEditBox)sender) == txtCustID)
                    //{
                    //    // 검색
                    //    btnProc_Click(btnSearch, null);
                    //}

                    //if (((Cosmos.UI.CsmPosEditBox)sender) == txtPayAmt)
                    //{
                        // 승인
                        sRet = CompleteTxtInPut();
                        if (sRet != UserCom.RST_OK) return;

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

                }
                else if (sFuncValue == PosKey.MENU_KEY.CLEAR)
                {
                    if (((Cosmos.UI.CsmPosEditBox)sender) == txtPayAmt)
                    {
                        txtPayAmt.Text = "0";
                    }
                }
                else if (sFuncValue == PosKey.MENU_KEY.ESC_PREVIOUS)
                {
                    this.DialogResult = DialogResult.Cancel;
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

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

        /// <summary>
        /// 코드 변경시 초기화
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtCardNo_EditBoxTextChangedEvnet(object sender, EventArgs e)
        {
            m_sInPutType = "";                                                                                  // 입력구분
            m_sInPutData = "";                                                                                  // 입력데이터
            m_sInEncData = "";                                                                                  // 카드데이터
        }
        #endregion

        #region 텍스트박스 입력 유효성 체크
        /// <summary>
        /// 텍스트박스 입력 유효성 체크
        /// </summary>
        /// <param name="sender"></param>
        /// <returns></returns>
        private bool CheckTxtInPut(object sender, bool bSearchMode)
        {
            try
            {
                // 번호 체크
                if (txtCustNo.Text.Length <= 0 && bSearchMode != true)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0213);
                    return false;
                }

                // 금액 체크
                if (txtPayAmt.Value.Length > 10 || m_cDataService.LongParse(txtPayAmt.Value) <= 0)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0036);
                    txtPayAmt.Focus();
                    return false;
                }

                if (CmUtil.AmountCut(m_cDataService.DoubleParse(txtPayAmt.Value), CmUtil.IntParse(m_cPosStatus.Mst.PayRudDwLoc)) != m_cDataService.DoubleParse(txtPayAmt.Value))
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0036);
                    txtPayAmt.Focus();
                    return false;
                }

                // 선택된 고객 체크
                if (dgvData.SelectedRows.Count <= 0)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0213);
                    return false;                
                }

                // 결제금액 체크
                if ( CmUtil.DoubleAdd(m_cDataService.DoubleParse(txtPayAmt.Value.ToString()), m_cDataService.DoubleParse(txtDCAmt.Text.ToString())) > m_cDataService.DoubleParse(txtSaleAmt.Text.ToString()))
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0039);
                    txtSaleAmt.Focus();
                    return false;
                }

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

        #region 텍스트박스 입력 완료 처리
        /// <summary>
        /// 결제 처리
        /// </summary>
        /// <param name="nFlowMode"></param>
        /// <returns></returns>
        private string CompleteTxtInPut()
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                // 승인
                if (CheckTxtInPut(null, false) != true) return sRet;

                txtCustNo.Text = dgvData.SelectedRows[0].Cells[1].Value.ToString().Trim();
                txtCustNm.Text = dgvData.SelectedRows[0].Cells[2].Value.ToString().Trim();
                txtTel.Text = dgvData.SelectedRows[0].Cells[3].Value.ToString().Trim();
                string sCustType = dgvData.SelectedRows[0].Cells[6].Value.ToString().Trim();
                string sTranFlag = "0";                                                                     // 거래구분 (0:외상, 1:외상취소) 

                sRet = m_cSaleOnCustomer.SetPayment(new string[] { ItemConst.IRT_INQ_TYPE.SALEONCREDIT_USE_INQ, m_sPay_DC_Grp_Type, m_sPay_DC_CD, sTranFlag, sCustType, txtCustNo.Text, txtCustNm.Text, m_cDataService.DoubleParse(txtPayAmt.Value).ToString(), m_cDataService.DoubleParse(txtDCAmt.Text).ToString() });
                if (sRet != UserCom.RST_OK) return sRet;

                txtCustNo.Text = "";                                                                                // 고객번호
                txtCustNm.Text = "";                                                                                // 고객명
                txtTel.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);
            }
            return sRet;
        }
        
        /// <summary>
        /// 조회 처리
        /// </summary>
        /// <returns></returns>
        private string SearchTxtInPut(string sSearchType)
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                // 조회
                string[] saRecvdData = null;

                DataGridSetting();                                                                                  // 그리드 초기화

                if (sSearchType == "")
                {
                    // 고객찾기 팝업
                    frmCustSearch fForm = (frmCustSearch)FormManager.GetForm(FormManager.FORM_PAY_CUST_SEARCH);
                    if (fForm == null)
                    {
                        fForm = new frmCustSearch();
                        FormManager.AddForm(FormManager.FORM_PAY_CUST_SEARCH, fForm);
                    }
                    fForm.SearchCD = txtCustID.Text;
                    fForm.SearchType = ItemConst.IRT_INQ_TYPE.SALEONCREDIT_CUSTINQ;
                    if (fForm.ShowDialog() != DialogResult.OK) return sRet;
                    txtCustID.Value = fForm.PosMenuKeyOut;
                }

                sRet = m_cSaleOnCustomer.SearchPayment(new string[] { ItemConst.IRT_INQ_TYPE.SALEONCREDIT_CUSTINQ, m_sPay_DC_Grp_Type, m_sPay_DC_CD, "0", sSearchType, txtCustID.Text, "0" }, ref saRecvdData);
                if (sRet != UserCom.RST_OK) return sRet;

                for (int iLoop = 0; iLoop < saRecvdData.Length; iLoop++)
                {
                    if (saRecvdData[iLoop].Trim().Length <= 0) continue;

                    string[] aRecvData = saRecvdData[iLoop].Split(new string[] { "|" }, StringSplitOptions.None);

                    if (aRecvData.Length > 0 )
                    {
                        int iRow = dgvData.Rows.Add();

                        dgvData.Rows[iRow].Visible = true;

                        dgvData.Rows[iRow].Cells[0].ReadOnly = false;
                        dgvData.Rows[iRow].DefaultCellStyle.ForeColor = Color.Black;
                        dgvData.Rows[iRow].DefaultCellStyle.SelectionForeColor = Color.Black;

                        dgvData.Rows[iRow].Cells[0].Value = (iRow + 1).ToString();                                                              // No
                        dgvData.Rows[iRow].Cells[1].Value = aRecvData[0].ToString();                                                            // 고객번호
                        dgvData.Rows[iRow].Cells[2].Value = aRecvData[3].ToString();                                                            // 고객명
                        dgvData.Rows[iRow].Cells[3].Value = aRecvData[2].ToString();                                                            // 전화번호
                        dgvData.Rows[iRow].Cells[4].Value = m_cPosStatus.Global.NumericTOCurrency(m_cDataService.DoubleParse(aRecvData[4])).ToString(); // 외상잔액
                        dgvData.Rows[iRow].Cells[5].Value = m_cPosStatus.Global.NumericTOCurrency(m_cDataService.DoubleParse(aRecvData[5])).ToString(); // DC율
                        dgvData.Rows[iRow].Cells[6].Value = aRecvData[1].ToString();                                                            // 고객형태 (0:개인, 1:법인)
                    }
                }

                dgvData.Refresh();

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

                sRet = UserCom.RST_ERR;
            }
            return sRet;
        }
        #endregion

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

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

        }
        /// <summary>
        /// 스캐너 이벤트 처리
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnScannerEvent(object source, EventArgs e)
        {
            string sScanData = m_cDevStatus.Scanner.DataLabel;

            try
            {
                //if (sScanData.Length > 0 && m_sInPutData == "")
                //{
                //    m_sInPutType = PosConst.POS_VAN_MASTER.INPUT_TYPE.VAN_BARCODE_GIFT;
                //    m_sInPutData = sScanData;

                //    txtCardNo.Text = m_sInPutData;

                //    ///                if (m_cTrnStatus.Head.TradeDiv == ItemConst.TRAN_DIV.NORMAL) SearchTxtInPut();
                //}
            }
            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="sInData"></param>
        /// <param name="sCardData"></param>
        /// <param name="sCardNo"></param>
        /// <returns></returns>
        private string EncryptedCardNo(string sInData, ref string sCardData, ref string sCardNo)
        {
            string sEncData = sInData;

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

        /// <summary>
        /// IC 카드 정보 입력 처리
        /// </summary>
        /// <returns></returns>
        private bool GetIcCardData()
        {
            try
            {
 
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            return false;
        }
        #endregion

        #region 그리드 설정 및 사용
        private double DataGridSetting()
        {
            try
            {
                // 초기화
                dgvData.Rows.Clear();

                dgvData.AllowUserToAddRows = false;
                dgvData.EnableHeadersVisualStyles = false;
                dgvData.RowsDefaultCellStyle.BackColor = Color.White;
                dgvData.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(249, 249, 249);
                dgvData.Font = this.Font;
                dgvData.DefaultCellStyle.Font = new Font(m_cPosStatus.Base.FONT, 9.75f);
                //dgvData.DefaultCellStyle.SelectionBackColor = Color.Transparent;

                dgvData.Font = new Font(m_cPosStatus.Base.FONT, 9.75f);
                dgvData.RowHeadersDefaultCellStyle.Font = new Font(m_cPosStatus.Base.FONT, 9.75f);

                // 타이틀 설정
                dgvData.Columns[0].HeaderText = "No";
                dgvData.Columns[1].HeaderText = "CustNO";
                dgvData.Columns[2].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0287);
                dgvData.Columns[3].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0279);
                dgvData.Columns[4].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0289);
                dgvData.Columns[5].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0290);
                dgvData.Columns[6].HeaderText = "CustType";
                dgvData.Refresh();

                txtCustNo.Text = "";                                                                                // 고객번호
                txtCustNm.Text = "";                                                                                // 고객명
                txtTel.Text = "";                                                                                   // 전화번호

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

        #endregion

        #region 고객선택
        private void dgvCustomer_Click(object sender, EventArgs e)
        {
            double nDCAmt = 0;
            double nPayAmt = 0;
            try
            {
                if (dgvData.RowCount <= 0) return;

                txtCustNo.Text = dgvData.SelectedRows[0].Cells[1].Value.ToString();
                txtCustNm.Text = dgvData.SelectedRows[0].Cells[2].Value.ToString();
                txtTel.Text = dgvData.SelectedRows[0].Cells[3].Value.ToString();

                double nDCRate = m_cDataService.DoubleParse(dgvData.SelectedRows[0].Cells[5].Value.ToString());         // 할인율

                // 자동 할인율 적용
                nPayAmt = m_cTrnStatus.Sale.RemainPayAmt;
                if (nDCRate != 0)
                {
                    //nDCAmt = CmUtil.MathAmtPercent(m_cTrnStatus.Sale.RemainPayAmt, nDCRate);
                    //nPayAmt = CmUtil.DoubleSubtraction(nPayAmt, nDCAmt);

                    nDCAmt = CmUtil.MathAmtPercent(m_cTrnStatus.Sale.RemainPayAmt, nDCRate);
                    nDCAmt = CmUtil.MathRounds(nDCAmt, m_cPosStatus.Mst.DcRudDwLocMethd, CmUtil.IntParse(m_cPosStatus.Mst.DcRudDwLoc));

                    // 할인 절삭
                    nPayAmt = CmUtil.DoubleSubtraction(nPayAmt, nDCAmt);
                    nPayAmt = CmUtil.MathRounds(nPayAmt, m_cPosStatus.Mst.ItemRudDwLocMethd, CmUtil.IntParse(m_cPosStatus.Mst.ItemRudDwLoc));
                }

                txtDCAmt.Text = m_cPosStatus.Global.NumericTOCurrency(nDCAmt);                                      // 할인금액

                if (nDCAmt > 0)
                {
                    txtPayAmt.ReadOnly = true;
                    txtPayAmt.Enabled = false;
                }
                else
                {
                    txtPayAmt.ReadOnly = false;
                    txtPayAmt.Enabled = true;
                }
                txtPayAmt.Text = m_cPosStatus.Global.NumericTOCurrency(nPayAmt);             // 결제금액

                txtPayAmt.Select();
                txtPayAmt.SelectText();
            }
            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


    }

}
