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 frmForeign : 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_cForeign = 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 frmForeign()
        {
            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_cForeign = (IPaymentUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.FOREIGN);
        }

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

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

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

        private void frmForeign_FormClosing(object sender, FormClosingEventArgs e)
        {
            ICustDisplayUs cCustDisp = (ICustDisplayUs)sManager.InitServiceInstance(ServiceLists.ASV_CUSTDISPLAY.DLL, ServiceLists.ASV_CUSTDISPLAY.CUST_DISPLAY);
            cCustDisp.DisplaySaleItemList(false, true, 0);       // 고객화면 표시
            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);

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

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

                //테마색상 적용!
                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);
                
                btnExit.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BTN_CLOSE);
                if (btnExit.Image != null) btnExit.Text = "";

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

                m_sPay_DC_Grp_Type = ItemConst.TR_ITEM_ID.FOREIGNEX_ITEM;
                m_sPay_DC_CD = ItemConst.TR_ITEM_ID.FOREIGNEX.USD;

                lblSaleAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0037);                       // 받을금액
                lblPayAmt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0299);                        // 받은금액

                btnEnter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0263);                         // 결제

                lblInfo.Text = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0244);                          // 알림 문구
                lblInfo.Font = new Font(m_cPosStatus.Base.FONT, 12);

                txtSaleAmt.Text = m_cPosStatus.Global.NumericTOCurrency(m_cTrnStatus.Sale.RemainPayAmt);            // 받을금액
                txtPayAmt.Text = "0";                                                                               // 받은금액

                m_sInPutType = "";                                                                                  // 입력구분
                m_sInPutData = "";                                                                                  // 입력데이터
                m_sInEncData = "";                                                                                  // 카드데이터

                bNotDoubleClik = false;

                LoadFuncMaster();                                                                                   // 환율 조회 표시
            }
            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)
                    {
                        for (int iLoop = dgvData.CurrentRow.Index + 1; iLoop <= dgvData.Rows.Count - 1; iLoop++)
                        {
                            if (dgvData.Rows[iLoop].Visible == false)
                            {
                                bNotDoubleClik = false;
                                continue;
                            }
                            dgvData.Rows[iLoop].Selected = true;
                            dgvData.Rows[iLoop].Cells[dgvData.CurrentCell.ColumnIndex].Selected = true;
                            break;
                        }
                    }
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnEnter)                 // 승인
                {
                    // 승인
                    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 (((DataGridView)sender) == dgvData)
                    {
                        // 승인
                        sRet = CompleteTxtInPut();
                        if (sRet != UserCom.RST_OK) return;

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

                }
                else if (sFuncValue == PosKey.MENU_KEY.CLEAR)
                {
                    if (((DataGridView)sender) == dgvData)
                    {
                        dgvData.SelectedRows[0].Cells[2].Value = "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 (m_cDataService.DoubleParse(txtPayAmt.Text) <= 0)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0034);

                    dgvData.Select();
                    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;
            int index = 0;

            try
            {
                // 승인
                if (CheckTxtInPut(null, false) != true) return sRet;

                // 입력한 위치 찾기
                for (int iLoop = 0; iLoop < dgvData.RowCount; iLoop ++ )
                {
                    if (m_cDataService.DoubleParse(dgvData.Rows[iLoop].Cells[4].Value.ToString()) > 0)
                    {
                        index = iLoop;
                        break;
                    }
                }

                if (dgvData.Rows[index].Cells[0].Value.ToString() == PosConst.FOREIGNCURRENCY_TYPE.USD) m_sPay_DC_CD = ItemConst.TR_ITEM_ID.FOREIGNEX.USD;
                else if (dgvData.Rows[index].Cells[0].Value.ToString() == PosConst.FOREIGNCURRENCY_TYPE.EUR) m_sPay_DC_CD = ItemConst.TR_ITEM_ID.FOREIGNEX.EUR;
                else if (dgvData.Rows[index].Cells[0].Value.ToString() == PosConst.FOREIGNCURRENCY_TYPE.JPY) m_sPay_DC_CD = ItemConst.TR_ITEM_ID.FOREIGNEX.JPY;
                else if (dgvData.Rows[index].Cells[0].Value.ToString() == PosConst.FOREIGNCURRENCY_TYPE.CNY) m_sPay_DC_CD = ItemConst.TR_ITEM_ID.FOREIGNEX.CNY;

                double nForeignAmt = m_cDataService.DoubleParse(dgvData.Rows[index].Cells[2].EditedFormattedValue.ToString());              // 받은금액(외화)
                double nPayAmt = m_cDataService.DoubleParse(dgvData.Rows[index].Cells[4].Value.ToString());                                 // 받은금액(원화)
                double nChangeAmt = m_cDataService.DoubleParse(dgvData.Rows[index].Cells[5].Value.ToString());                              // 거스름금액
                double nExchangeAmt = m_cDataService.DoubleParse(dgvData.Rows[index].Cells[6].Value.ToString());                            // 환율

                sRet = m_cForeign.SetPayment(new string[] { m_sPosMenuKey, m_sPay_DC_Grp_Type, m_sPay_DC_CD, nForeignAmt.ToString(), nPayAmt.ToString(), nChangeAmt.ToString(), nExchangeAmt.ToString() });
                if (sRet != UserCom.RST_OK) return sRet;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
            return sRet;
        }

        /// <summary>
        /// 조회 처리
        /// </summary>
        /// <returns></returns>
        private bool SearchTxtInPut(string sSearchType)
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                // 조회
                return true;
            }
            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 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.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
                dgvData.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
                dgvData.Font = this.Font;
                dgvData.DefaultCellStyle.Font = new Font(m_cPosStatus.Base.FONT, 14);
                
                dgvData.Font = new Font(m_cPosStatus.Base.FONT, 12);
                dgvData.RowHeadersDefaultCellStyle.Font = new Font(m_cPosStatus.Base.FONT, 12);

                // 타이틀 설정
                dgvData.Columns[1].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0296);
                dgvData.Columns[2].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0297);
                dgvData.Columns[2].DefaultCellStyle.BackColor = Color.FromArgb(255, 224, 192);
                dgvData.Columns[3].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0298);
                dgvData.Columns[4].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0299);
                dgvData.Columns[5].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0300);
                dgvData.Columns[6].HeaderText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0301);
                dgvData.Refresh();

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

        #region 환율 조회 표시
        /// <summary>
        /// 환율 조회 표시
        /// </summary>
        /// <returns>성공/실패</returns>
        public bool LoadFuncMaster()
        {
            double nForeignRate = 0;    // 환율            
            double nForeignUnit = 0;    // 단위 
            double nPayAmt = 0;         // 받을돈

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

                // List 조회 (마스터 조정후 쿼리 수정 필요)
                DataTable dtMemu = m_cDataCommon.SelectForeign();
                if (dtMemu == null) return  false;
                if (dtMemu.Rows.Count <= 0) return false;
                //{
                //    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0217); // 메뉴키 마스터가 없습니다
                //    return false;
                //}

                // 메뉴정보 설정
                foreach (DataRow dr in dtMemu.Rows)
                {
                    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].HeaderCell.Value = (iRow + 1).ToString();
                    dgvData.Rows[iRow].Cells[0].Value = CmUtil.GetDataRowStr(dr, PosMst.MST_FOREIGN_RATE_KEY.DATA.EXCHG_RATE_CD);           // 외화 코드
                    dgvData.Rows[iRow].Cells[1].Value = CmUtil.GetDataRowStr(dr, PosMst.MST_FOREIGN_RATE_KEY.DATA.EXCHG_RATE_NM);           // 외화 명
///                    dgvData.Rows[iRow].Cells[2].Value = "0";                                                                             // 받은금액(외화)

                    nForeignRate = CmUtil.GetDataRowDouble(dr, PosMst.MST_FOREIGN_RATE_KEY.DATA.EXCHG_RATE_AMT);                            // 환율
                    nForeignUnit = CmUtil.GetDataRowDouble(dr, PosMst.MST_FOREIGN_RATE_KEY.DATA.EXCHG_RATE_UNIT);                           // 단위

                    if (nForeignRate > 0)
                    {
                        nPayAmt = CmUtil.DoubleDivision(m_cDataService.DoubleParse(txtSaleAmt.Text.ToString()), nForeignRate);                      // 받을돈
                        nPayAmt = CmUtil.DoubleMultiplication(nPayAmt, nForeignUnit);                                                       // 받을돈 * 단위
                        nPayAmt = CmUtil.MathRounds(nPayAmt, PosConst.MATH_ROUND.CEILING, 2);                                               // 라운드 2
                         
                        dgvData.Rows[iRow].Cells[3].Value = m_cPosStatus.Global.NumericTOCurrency(nPayAmt, 3, ",", 2, ".");                 // 받을금액(외화)
                    }
                    dgvData.Rows[iRow].Cells[4].Value = "0";                                                                                // 받은금액(원화)
                    dgvData.Rows[iRow].Cells[5].Value = "0";                                                                                // 거스름금액
                    dgvData.Rows[iRow].Cells[6].Value = m_cPosStatus.Global.NumericTOCurrency(CmUtil.GetDataRowDouble(dr, PosMst.MST_FOREIGN_RATE_KEY.DATA.EXCHG_RATE_AMT));    // 환율
                    dgvData.Rows[iRow].Cells[7].Value = m_cPosStatus.Global.NumericTOCurrency(CmUtil.GetDataRowDouble(dr, PosMst.MST_FOREIGN_RATE_KEY.DATA.EXCHG_RATE_UNIT));   // 환전 단위
                }
                dgvData.Refresh();
                dgvData.CurrentCell = dgvData.Rows[0].Cells[2];
                dgvData.Select();

                string sForeignInfo = "";
                for(int iRow = 0 ; iRow < dgvData.Rows.Count ; iRow++)
                {
                    sForeignInfo += dgvData.Rows[iRow].Cells[1].Value + "[" + dgvData.Rows[iRow].Cells[0].Value + "]" + "|"; // 외화 코드
                    sForeignInfo += dgvData.Rows[iRow].Cells[3].Value + "|"; // 받을금액(외화)
                }
                if (sForeignInfo != "")
                {
                    ICustDisplayUs cCustDisp = (ICustDisplayUs)sManager.InitServiceInstance(ServiceLists.ASV_CUSTDISPLAY.DLL, ServiceLists.ASV_CUSTDISPLAY.CUST_DISPLAY);
                    cCustDisp.DisplayForeignCashList(sForeignInfo);       // 고객화면 표시
                }

                return true;
            }
            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 void dgvData_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            double nForeignRate = 0;    // 환율      
            double nForeignUnit = 0;    // 단위 
            double nPayAmt = 0;         // 받은돈
            double nForeignAmt = 0;     // 받을금액(외화)
            double nSumAmt = 0;         // 받은금액(원화)
            double nRefAmt = 0;         // 거스름

            try
            {
                if (dgvData.Rows.Count <= 0) return;
                if (e.ColumnIndex != 2) return;
                if (e.RowIndex < 0) return;

                int iRow = e.RowIndex;

                // 받은금액이 있는 경우 다른 외화 사용불가
                if (m_cDataService.DoubleParse(txtPayAmt.Text.ToString()) > 0 && m_cDataService.DoubleParse(dgvData.Rows[iRow].Cells[4].Value.ToString()) <= 0)
                {
                    dgvData.Rows[iRow].Cells[2].Value = "";
                    return;
                }

                if (CmUtil.IsNumber(m_cDataService.DoubleParse(dgvData.Rows[iRow].Cells[e.ColumnIndex].Value.ToString()).ToString()) != true && dgvData.Rows[iRow].Cells[e.ColumnIndex].Value.ToString() != "")
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0036);
                    dgvData.Rows[iRow].Cells[e.ColumnIndex].Value = "";
                    return;
                }

                nPayAmt = m_cDataService.DoubleParse(dgvData.Rows[iRow].Cells[2].EditedFormattedValue.ToString());                                         // 받은돈
                nForeignRate = m_cDataService.DoubleParse(dgvData.Rows[iRow].Cells[6].Value.ToString());                                    // 환율
                nForeignUnit = m_cDataService.DoubleParse(dgvData.Rows[iRow].Cells[7].Value.ToString());                                    // 단위
 
                // 받을금액(외화)
                nForeignAmt = CmUtil.DoubleDivision(m_cDataService.DoubleParse(txtSaleAmt.Text.ToString()), nForeignRate);                  // 받을돈
                nForeignAmt = CmUtil.DoubleMultiplication(nForeignAmt, nForeignUnit);                                               // 받을돈 * 단위
                nForeignAmt = CmUtil.MathRounds(nForeignAmt, PosConst.MATH_ROUND.CEILING, 2);                                       // 라운드 2

                nSumAmt = CmUtil.DoubleDivision(nPayAmt, nForeignUnit);                                                             // 받을돈 / 단위
                nSumAmt = CmUtil.MathRounds(CmUtil.DoubleMultiplication(nSumAmt, nForeignRate), PosConst.MATH_ROUND.CEILING, CmUtil.IntParse(m_cPosStatus.Mst.PayRudDwLoc));    // 받은금액(원화)
                if (nSumAmt > m_cDataService.DoubleParse(txtSaleAmt.Text.ToString()))
                    nRefAmt = CmUtil.DoubleSubtraction(nSumAmt, m_cDataService.DoubleParse(txtSaleAmt.Text.ToString()));                    // 거스름

                if (nForeignAmt > nPayAmt)
                    nForeignAmt = CmUtil.DoubleSubtraction(nForeignAmt, nPayAmt);
                else
                    nForeignAmt = 0;
                
                // 화면 표시
                dgvData.Rows[iRow].Cells[3].Value = m_cPosStatus.Global.NumericTOCurrency(nForeignAmt, 3, ",", 2, ".");             // 받을금액(외화)
                dgvData.Rows[iRow].Cells[4].Value = m_cPosStatus.Global.NumericTOCurrency(nSumAmt);                                 // 받은금액(원화)
                dgvData.Rows[iRow].Cells[5].Value = m_cPosStatus.Global.NumericTOCurrency(nRefAmt);                                 // 거스름

                txtPayAmt.Text = m_cPosStatus.Global.NumericTOCurrency(nSumAmt); 

                dgvData.Refresh();
            }
            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;
            }
        }
        #endregion

        private void dgvData_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {

                dgvData.EditMode = DataGridViewEditMode.EditProgrammatically;
                dgvData.Rows[e.RowIndex].Cells[2].Selected = true;
                dgvData.BeginEdit(true);
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.ToString());
            }

        }

    }
}
