using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

namespace Cosmos.Win
{
    public partial class frmEtcInEMP : Form
    {
        #region Variable
        
        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private DeviceStatus m_cDevStatus = new DeviceStatus();                     // 디바이스 관리
        private TranStatus m_cTrnStatus = new TranStatus();                         // 거래정보 참조        
        //private IICReaderUs m_cDeviceICReader = null;
        private PosStatus m_cPosStatus = new PosStatus();                           // 기본정보 참조
        private IDataServiceUs m_cEtcInEmp = null;                                  // 직원 방문 및 제조기사 등록

        private PosOLEDevice.DelegateOlePos delegatePos;

        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        
        private DataTable m_dtItemInit;                                             // 아이템 리스트

        #endregion Variable
        
        #region 생성자 & 소멸자

        public frmEtcInEMP()
        {
            InitializeComponent();

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

            m_cDevStatus = (DeviceStatus)StateObject.DEVICE;
            m_cTrnStatus = (TranStatus)StateObject.TRAN;    // POS 거래정보
            m_cPosStatus = (PosStatus)StateObject.POS;             // POS 기본정보

            //m_cDeviceICReader = (IICReaderUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_ICREADER);
            m_cEtcInEmp = (IDataServiceUs)sManager.InitServiceInstance(ServiceLists.BSV_BASIC.DLL, ServiceLists.BSV_BASIC.ETC_IN_EMP);  // 본사방품내역조회

            delegatePos = new PosOLEDevice.DelegateOlePos(OnDeviceEvent);
        }

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

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

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

        private void frmEtcInEMP_Activated(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(delegatePos);
        }

        private void frmEtcInEMP_Deactivate(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(null);
        }
        
        #endregion 생성자 & 소멸자      
        
        #region 폼 컨트롤 초기화
        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            try
            {
                //this.Size = new Size(800, 600);
                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);
                FormManager.MovePopUpForm(this, false, m_cPosStatus.Sale.ScreenSizeUser);
                picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_800X600);

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

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



                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0337);//2017.12.20;다국어 처리;girak.kim; Start                

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

                lblMessage03.Text = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0332);

                txtBarCode.Value = "";
                
                InitializeGrid();

                InputBoxSetFoucus();

            }
            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
            {
                // 상품권 등록정보 표시 그리드
                grdSearchItem.CsmGridColumnHeadersVisible = true;           //DataGridView 자체의 컬럼 헤더 Visible 여부
                grdSearchItem.CsmGridColumnHeadersFont = new Font(m_cPosStatus.Base.FONT, 12);  //DataGridView 자체의 컬럼 헤더 폰트
                grdSearchItem.CsmGridColumnHeadersHeight = 39;              //DataGridView 자체의 컬럼 헤더 높이
                grdSearchItem.CsmGridRowsHeight = 36;
                grdSearchItem.CsmGridColumnCount = 3;                       //그리드의 컬럼수
                grdSearchItem.CsmGridShowPageRowsCount = 12;                 //그리드의 한 화면에 보이는 로우수
                grdSearchItem.CsmGridSetHeaderBackColor(236, 238, 239);                             //그리드 헤더 배경색
                grdSearchItem.CsmGridDefaultRowBackColor = Color.FromArgb(255, 255, 255);           //그리드 홀수(Default)행의 배경색 지정
                grdSearchItem.CsmGridAlternateRowBackColor = Color.FromArgb(251, 253, 255);         //그리드 짝수(Alternate)행의 배경색 지정
                grdSearchItem.CsmGridBackGroundColor = Color.FromArgb(251, 253, 255);               //기본 백그라운드 컬러
                grdSearchItem.CsmGridHighlightColor = Color.FromArgb(255, 251, 211);                //그리드 선택 백 컬러
                grdSearchItem.CsmGridHighlightTextColor = Color.Black;                              //그리드 선택 글자 컬러
                grdSearchItem.CsmGridSetColumnWidth(new int[] { 260, 240, 240 });   //컬럼넓이 지정(964)
                grdSearchItem.CsmGridAlignment(new int[] { 1, 1, 1 });               //컬럼 정렬 0:왼쪽, 1:가운데, 2:오른쪽

                //각 컬럼별 이름 지정
                grdSearchItem.CsmGridColumnName(0, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0051));
                grdSearchItem.CsmGridColumnName(1, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0527));
                grdSearchItem.CsmGridColumnName(2, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0528));                  

                //그리드 초기화 테이블
                m_dtItemInit = new DataTable("INIT");
                m_dtItemInit.Columns.Add(new DataColumn("CARD_NO", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("IN_TIME", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("OUT_TIME", typeof(string)));
                
                m_dtItemInit.Clear();

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

        #endregion 폼 컨트롤 초기화               

        #region Control Event

        /// <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)
                {
                    if (txtBarCode.Text.Length == 0)
                    {
                        txtBarCode.Text = "";
                        return;
                    }

                    SetInDataProcess(ItemConst.EMP_VISIT_DIV.MOBILE, txtBarCode.Text);
                    txtBarCode.Text = "";
                    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);
            }
        }

        /// <summary>
        /// 그리드 위/아래
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrc_Click(object sender, EventArgs e)
        {
            try
            {
                if ((UI.CsmButton)sender == btnUp2)
                {
                    grdSearchItem.CsmGridScroll("PAGE UP");
                }
                else if ((UI.CsmButton)sender == btnUp)
                {
                    grdSearchItem.CsmGridScroll("UP");
                }
                else if ((UI.CsmButton)sender == btnDw)
                {
                    grdSearchItem.CsmGridScroll("DOWN");
                }
                else if ((UI.CsmButton)sender == btnDw2)
                {
                    grdSearchItem.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);
            }
        }

        /// <summary>
        /// 그리드 클릭(거의 없음)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grdSearchItem_Click(object sender, EventArgs e)
        {
            try
            {
                InputBoxSetFoucus();
            }
            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 InputBoxSetFoucus()
        {
            try
            {
                txtBarCode.Text = "";
                txtBarCode.Focus();
            }
            catch (Exception) { }

        }

        /// <summary>
        /// 그리드 클릭 이벤트
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="rowIndex"></param>
        private void grdSearchItem_GridClickEvent(object sender, string rowIndex)
        {
            try
            {
                //InputBoxSetFoucus();
            }
            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 grdSearchItem_Enter(object sender, EventArgs e)
        {
            try
            {
                InputBoxSetFoucus();
            }
            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 Control Event

        #region User Method

        /// <summary>
        /// 등록 데이터 조회
        /// </summary>
        private void SearchData()
        {
            try
            {
                DataTable dt = (DataTable)m_cEtcInEmp.GetData(new string[] { "List", DateTime.Now.ToString("yyyyMMdd"), "" });

                if (dt == null || dt.Rows.Count == 0)
                {
                    grdSearchItem.CsmGridDataSource = m_dtItemInit;
                }
                else
                {
                    grdSearchItem.CsmGridDataSource = dt;
                }

            }
            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="sInType"></param>
        /// <param name="sINData"></param>
        /// <returns></returns>
        private string SetInDataProcess(string sInType, string sINData)
        {

            string sRet = UserCom.RST_ERR;
            string sCardNo = string.Empty;
            
            try
            {

                
                //0:관리 카드 번호, 1:방문시간, 2:종료시간, 3:MSR구분, 4: 원바코드 번호
                sRet = m_cEtcInEmp.Execute(new string[] { sINData, DateTime.Now.ToString("yyyyMMddHHmmss"), DateTime.Now.ToString("yyyyMMddHHmmss"), sInType, sINData });

                if (sRet == UserCom.RST_OK) 
                    SearchData();
                

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


            return sRet;

        }
        #endregion User Method

        #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:

                        //if (!(m_cPosStatus.Base.CmpCd != ItemConst.COMPANY_CODE.PCKR || m_cPosStatus.Base.CmpCd != ItemConst.COMPANY_CODE.BRKR || m_cPosStatus.Base.CmpCd != ItemConst.COMPANY_CODE.SLKR))
                            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)
        {
            try
            {
                string sMsrData = m_cDevStatus.Msr.Track2Data;
                if (sMsrData.Length > 0)
                {
                    SetInDataProcess(ItemConst.EMP_VISIT_DIV.MSR, sMsrData);
                }
            }
            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="source"></param>
        /// <param name="e"></param>
        private void OnScannerEvent(object source, EventArgs e)
        {
            try
            {
                string sScanData = m_cDevStatus.Scanner.DataLabel;
                if (sScanData.Length > 0)
                {
                    SetInDataProcess(ItemConst.EMP_VISIT_DIV.MOBILE, sScanData);
                }
            }
            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>
        /// 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 DeviceEvent 관련

        //#Rhee, 20180124 키패드 추가 Start
        /// <summary>
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCardNo_Click(object sender, EventArgs e)
        {
            try
            {
                frmInputDataMin fForm = new frmInputDataMin();
                fForm.PosMenuKeyIn = "STAFFCARD";
                if (fForm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string sCardNo = fForm.PosInPutData;
                    if (sCardNo.Length > 0)
                    {
                        //txtBarCode.Text = sCardNo;
                        SetInDataProcess(ItemConst.EMP_VISIT_DIV.MOBILE, sCardNo);
                        txtBarCode.Text = "";
                        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);
            }
        }
        //#Rhee, 20180124 키패드 추가 End
    }
}
