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

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

namespace Cosmos.Win
{
    public partial class frmEmpCommute : Form
    {

        #region Variable

        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        private PosStatus m_cPosStatus = new PosStatus();                           // 기본정보 참조
        private IDataServiceUs m_cEmpCommute = null;
        private IDataServiceUs m_cEtcInEmp = null;                                  // 직원 방문 및 제조기사 등록

        private DeviceStatus m_cDevStatus = new DeviceStatus();                     // 디바이스 관리
        private PosOLEDevice.DelegateOlePos delegatePos;

        private DataTable m_dtItemInit;                                             // 조회 상품 리스트

        //#20171101 출/퇴근 카드리딩 기능추가 start,phj
        private IDatabaseSQL m_cSqlDbService = null;                                // 데이터베이스 관리
        //#20171101 출/퇴근 카드리딩 기능추가 end,phj

        #endregion

        #region 생성자 & 소멸자
        public frmEmpCommute()
        {
            InitializeComponent();

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

            m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보

            m_cEtcInEmp = (IDataServiceUs)sManager.InitServiceInstance(ServiceLists.BSV_BASIC.DLL, ServiceLists.BSV_BASIC.ETC_IN_EMP);      // 본사방품내역조회
            m_cEmpCommute = (IDataServiceUs)sManager.InitServiceInstance(ServiceLists.BSV_BASIC.DLL, ServiceLists.BSV_BASIC.EMP_COMMUTE);    // 직원 출/퇴근 등록
            //#20171101 출/퇴근 카드리딩 기능추가 start,phj
            m_cSqlDbService = (IDatabaseSQL)sManager.InitServiceInstance(ServiceLists.AGENT_DATABASE.DLL, ServiceLists.AGENT_DATABASE.DATABASE_MSSQL);
            //#20171101 출/퇴근 카드리딩 기능추가 end,phj

            delegatePos = new PosOLEDevice.DelegateOlePos(OnDeviceEvent);
            m_cDevStatus = (DeviceStatus)StateObject.DEVICE;
        }
        /// <summary>
        /// 폼로드
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmCheck_Load(object sender, EventArgs e)
        {
            UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "");
            InitControl();
        }
        /// <summary>
        /// 폼클로즈
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmCheck_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>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmCheck_Activated(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(delegatePos);
        }
        /// <summary>
        /// 폼디엑티브
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmCheck_Deactivate(object sender, EventArgs e)
        {
            PosOLEDevice.SetEventHandle(null);
        }

        #endregion 생성자 & 소멸자

        #region 폼 컨트롤 초기화
        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            try
            {
                // 이미지 로딩 처리
                picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_800X600);
                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);

                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 = "";

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

                //테마색상 적용!                
                padInPut.ThemeColor = m_cPosStatus.ScnMst.ThemeColor;
                padInPut.ClearBtnText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0817);
                padInPut.SearchBtnText = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1018);
                
                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0333);
                lblUserNm.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0150);
                lblStat.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0421);
                lblPsw.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0013);
                lblRegDate.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0561);

                // 제조기사는 바코드를 입력하세요(2017.06.15)
                lblMessage.Text = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0697);

                //btnSrh.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0004);
                //BtnSave.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0225);

                btnDate.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.ICON_DATE_BASIC);

                //btnDate.DefaultImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.ICON_DATE_BASIC);
                //btnDate.ClickImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.ICON_DATE_PRESS);

                TxtBoxInit();

                BtnInit();

                InitializeGrid();

                txtSaleDate.InputTypeFormat = m_cPosStatus.Global.m_stCultureMaster.strDatePattern;
                txtSaleDate.Text = m_cPosStatus.Global.DateToCulture(DateTime.Now.ToString("yyyyMMdd"));

                SearchList();

                padInPut.SetActiveControl = txtPsw;

                //dtSaleDate.MaxDate = DateTime.Now;

                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 = 34;              //DataGridView 자체의 컬럼 헤더 높이
                grdSearchItem.CsmGridRowsHeight = 39;
                grdSearchItem.CsmGridColumnCount = 13;                       //그리드의 컬럼수
                grdSearchItem.CsmGridShowPageRowsCount = 11;                 //그리드의 한 화면에 보이는 로우수
                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[] { 131, 131, 131, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });   //컬럼넓이 지정(499)
                grdSearchItem.CsmGridAlignment(new int[] { 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });                //컬럼 정렬 0:왼쪽, 1:가운데, 2:오른쪽

                //각 컬럼별 이름 지정
                grdSearchItem.CsmGridColumnName(0, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0421));
                grdSearchItem.CsmGridColumnName(1, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0239));
                grdSearchItem.CsmGridColumnName(2, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0150));
                grdSearchItem.CsmGridColumnName(3, "CMP_CD");
                grdSearchItem.CsmGridColumnName(4, "STOR_CD");
                grdSearchItem.CsmGridColumnName(5, "CASHIER_ID");
                grdSearchItem.CsmGridColumnName(6, "WORK_DT");
                grdSearchItem.CsmGridColumnName(7, "WORK_STAT");
                grdSearchItem.CsmGridColumnName(8, "WORK_TIME");
                grdSearchItem.CsmGridColumnName(9, "REST_STAT");
                grdSearchItem.CsmGridColumnName(10, "REST_TIME");
                grdSearchItem.CsmGridColumnName(11, "GOOUT_STAT");
                grdSearchItem.CsmGridColumnName(12, "GOOUT_TIME");

                //그리드 초기화 테이블
                m_dtItemInit = new DataTable("INIT");
                m_dtItemInit.Columns.Add(new DataColumn("TOT_STAT", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("REG_TIME", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("CASHIER_NM", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("CMP_CD", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("STOR_CD", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("CASHIER_ID", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("WORK_DT", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("WORK_STAT", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("WORK_TIME", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("REST_STAT", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("REST_TIME", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("GOOUT_STAT", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("GOOUT_TIME", typeof(string)));

                m_dtItemInit.Clear();

                grdSearchItem.CsmGridDataSource = m_dtItemInit;

            }
            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 BtnInit()
        {
            try
            {
                btnWork.Text = "";
                btnWork.Tag = "";
                btnRest.Text = "";
                btnRest.Tag = "";
                btnGoOut.Text = "";
                btnGoOut.Tag = "";

                btnWork.Visible = false;
                btnRest.Visible = false;
                btnGoOut.Visible = 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);

            }
        }

        /// <summary>
        /// 입력박스 초기화
        /// </summary>
        private void TxtBoxInit()
        {
            try
            {
                txtPsw.Text = "";
                txtUserNm.Text = "";
                txtStat.Text = "";

                // Add, 2017.08.30, 제조기사 출퇴근, TimeBarcode = 19 or 22, 비밀번호 항목 길이 조정 
                txtPsw.MaxLength = 22;
            }
            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

        //try
        //    {
        //        string sDate = WinBasic.ShowForm(new string[] { FormManager.FORM_CALENDAR });
        //        if (sDate != "") txtSaleDate.Value = sDate;
        //    }
        //    catch (Exception ex)
        //    {
        //        WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
        //             System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
        //    }


        #region Control Event

        #region 버튼 입력 처리
        /// <summary>
        /// 버튼 입력 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnProc_Click(object sender, EventArgs e)
        {
            try
            {
                if (((Cosmos.UI.CsmButton)sender).Text == "") return;

                if (((Cosmos.UI.CsmButton)sender) == btnWork) // 출퇴근
                {
                    SaveItem(btnWork.Tag.ToString());

                }
                else if (((Cosmos.UI.CsmButton)sender) == btnRest) // 휴식
                {
                    SaveItem(btnRest.Tag.ToString());
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnGoOut) // 외출
                {
                    SaveItem(btnGoOut.Tag.ToString());
                }
                
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion

        /// <summary>
        /// 조회 그리드 업/다운 클릭 이벤트
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelProc_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 btnExit_Click(object sender, EventArgs e)
        {
            try
            {
                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>
        private void InputBoxSetFoucus()
        {
            try
            {
                txtPsw.Text = "";
                txtPsw.Focus();
            }
            catch (Exception) { }

        }

        /// <summary>
        /// 그리드 클릭 이벤트
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="rowIndex"></param>
        private void grdSearchItem_GridClickEvent(object sender, string rowIndex)
        {
            string sStat = string.Empty;

            try
            {
                if (grdSearchItem.CsmGridRowsCount == 0)
                {
                    return;
                }

                BtnInit();

                grdSearchItem.CsmGridHighlightColor = Color.FromArgb(255, 251, 211);                //그리드 선택 백 컬러

                TxtBoxInit();
                BtnInit();

                txtUserNm.Text = grdSearchItem.CsmGridGetCell(grdSearchItem.CsmGridSelectedRowIndex, 2);
                txtUserNm.Tag = grdSearchItem.CsmGridGetCell(grdSearchItem.CsmGridSelectedRowIndex, 5);
                txtStat.Text = grdSearchItem.CsmGridGetCell(grdSearchItem.CsmGridSelectedRowIndex, 0);

                if (grdSearchItem.CsmGridGetCell(grdSearchItem.CsmGridSelectedRowIndex, 11) == "1") //외출
                {
                    btnGoOut.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0563);  //"외출종료";
                    btnGoOut.Tag = ItemConst.EMP_COMMUTE_DIV.GO_OUT_END;  //"6";

                    btnGoOut.Visible = true;

                }
                else if (grdSearchItem.CsmGridGetCell(grdSearchItem.CsmGridSelectedRowIndex, 9) == "1") //휴식
                {
                    btnRest.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0566);  //"휴식종료";
                    btnRest.Tag = ItemConst.EMP_COMMUTE_DIV.REST_END; //"4";

                    btnRest.Visible = true;

                }
                else if (grdSearchItem.CsmGridGetCell(grdSearchItem.CsmGridSelectedRowIndex, 7) == "1") //출근
                {
                    btnWork.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0569);  //"퇴근";
                    btnWork.Tag = ItemConst.EMP_COMMUTE_DIV.WORK_END; //"2";
                    btnRest.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0565);  //"휴식시작";
                    btnRest.Tag = ItemConst.EMP_COMMUTE_DIV.REST_START; //"3";
                    btnGoOut.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0562);  //"외출시작";
                    btnGoOut.Tag = ItemConst.EMP_COMMUTE_DIV.GO_OUT_START; // "5";

                    btnWork.Visible = true;
                    btnRest.Visible = true;
                    btnGoOut.Visible = true;

                }
                else if (grdSearchItem.CsmGridGetCell(grdSearchItem.CsmGridSelectedRowIndex, 7) == "0") //퇴근
                {
                    btnWork.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0568);  //"출근";
                    btnWork.Tag = ItemConst.EMP_COMMUTE_DIV.WORK_START; // "1";

                    btnWork.Visible = true;
                }
                else
                {
                    btnWork.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0568);  //"출근";
                    btnWork.Tag = ItemConst.EMP_COMMUTE_DIV.WORK_START; // "1";

                    btnWork.Visible = 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);
            }
        }

        /// <summary>
        /// 바코드 이벤트
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="sFuncValue"></param>
        private void txtPsw_EditBoxKeyDownEvent(object sender, string sFuncValue)
        {
            try
            {
                if (sFuncValue == PosKey.MENU_KEY.ENTER)
                {
                    if (txtPsw.Text.Length == 0)
                    {
                        return;
                    }
                    //else if (txtPsw.Text.Length < 6)
                    //{
                    //    //비밀번호 입력
                    //}
                    // 직원 출/퇴근 화면에서 제조기사 처리하는 오류 수정(2017.07.12)
                    //else if (txtPsw.Text.Length > 6)
                    //{
                    //    //제조기사 처리
                    //    SetTimeBarcode(txtPsw.Value);
                    //    txtPsw.Text = "";
                    //}

                    //#20171101 출/퇴근 카드리딩 기능추가 start,phj
                    //기존
                    /*
                    // Mod, 2017.08.30, 제조기사 출퇴근 처리 
                    if (m_cPosStatus.Mst.CorpDiv == ItemConst.CORP_DIV.PC)
                    {
                        // 제조기사 TimeBarcode = 19 or 22
                        if (txtPsw.Text.Trim().Length == 19 || txtPsw.Text.Trim().Length == 22)
                        {
                            //제조기사 처리
                            SetTimeBarcode(txtPsw.Value);
                            txtPsw.Text = "";
                        }
                    }
                    */
                    //변경
                    
                    if (m_cPosStatus.Mst.CorpDiv == ItemConst.CORP_DIV.PC)
                    {
                        // 제조기사 TimeBarcode = 19 or 22
                        if (txtPsw.Text.Trim().Length == 19 || txtPsw.Text.Trim().Length == 22)
                        {
                            //제조기사 처리

                            //#17532 방문등록/근태등록 메뉴 옵션처리 start
                            //기존
                            //SetTimeBarcode(txtPsw.Value);
                            //변경

                            //#17743 판매POS 근태관련 옵션 변경 요청드립니다. start
                            //OPT307 근태(출퇴근) 허용여부 값 세분화(0:사용안함, 1:사용함, 2:근태바코드제한)
                            //기존
                            /*
                            if (CmUtil.IsNull(PosMstManager.GetPosOption(POS_OPTION.OPT308), "1") == "0")
                            {
                                //해당 기능은 POS 옵션에서 미사용으로 되어 있습니다.
                                WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0414);
                            }
                            else
                            {
                                SetTimeBarcode(txtPsw.Value);
                            }
                            */
                            //변경
                            if (CmUtil.IsNull(PosMstManager.GetPosOption(POS_OPTION.OPT307), "1") == "2")
                            {
                                //해당 기능은 POS 옵션에서 미사용으로 되어 있습니다.
                                WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0414);
                            }
                            else
                            {
                                SetTimeBarcode(txtPsw.Value);
                            }
                            //#17743 판매POS 근태관련 옵션 변경 요청드립니다. end

                            //#17532 방문등록/근태등록 메뉴 옵션처리 end

                            txtPsw.Text = "";
                        }
                        else
                        {
                            string InputCardNo = string.Empty;
                            InputCardNo = txtPsw.Value;

                            if (InputCardNo.Length > 16)
                            {
                                InputCardNo = InputCardNo.Substring(0, 16);
                            }

                            string Employee_ID = string.Empty;
                            string Employee_NM = string.Empty;
                            string Employee_PW = string.Empty;

                            if (GetEmployeeInfo(InputCardNo, ref Employee_ID, ref Employee_NM, ref Employee_PW) != UserCom.RST_ERR)
                            {
                                txtUserNm.Text = Employee_NM; //이름
                                txtUserNm.Tag = Employee_ID; //아이디
                                txtPsw.Text = Employee_PW; //패스워드
                                txtPsw.Value = Employee_PW; //패스워드

                                //저장 
                                StatusCheck();
                            }
                            else
                            {
                                txtUserNm.Text = string.Empty;
                                txtUserNm.Tag = string.Empty;
                                txtStat.Text = string.Empty;
                                txtPsw.Text = string.Empty;
                                txtPsw.Value = string.Empty;

                                WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0006);
                            }
                        }
                    }
                    
                    //#20171101 출/퇴근 카드리딩 기능추가 end,phj
                }
            }
            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) { }
            
        }

        #endregion

        #region User Method
        /// <summary>
        /// 타임바코드 등록
        /// </summary>
        /// <param name="sINData"></param>
        private void SetTimeBarcode(string sINData)
        {
            try
            {
                //0:관리 카드 번호, 1:방문시간, 2:종료시간, 3:MSR구분, 4: 원바코드 번호
                string sRet = m_cEtcInEmp.Execute(new string[] { sINData, DateTime.Now.ToString("yyyyMMddHHmmss"), DateTime.Now.ToString("yyyyMMddHHmmss"), ItemConst.EMP_VISIT_DIV.MOBILE, sINData });

                if (sRet == UserCom.RST_OK)
                {
                    WinManager.ConfirmMessage(POS_MESSAGE.ERROR.MSG_0340);
                }

            }
            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 SaveItem(string sRegType)
        {

            string sRet = UserCom.RST_ERR;

            try
            {
                //입력 값 체크
                if (CheckTxtInput(sRegType) == false) return;

                //비밀번호 체크
                IServiceUs cService = (IServiceUs)sManager.InitServiceInstance(ServiceLists.BSV_OPEN_CLOSE.DLL, ServiceLists.BSV_OPEN_CLOSE.CASHIER_LOG_ON);
                // 캐셔번호(0), 비밀번호(1)
                sRet = cService.Execute(new string[] { txtUserNm.Tag.ToString().Replace(m_cPosStatus.Base.StoreNo, ""), txtPsw.Value, sRegType });
                if (sRet != UserCom.RST_OK)
                {
                    txtPsw.Value = "";
                    return;
                }

                //등록데이터 저장 0:사원번호, 1:근무일자, 2:근태코드

                string sWorkDay = "";

                if (sRegType == ItemConst.EMP_COMMUTE_DIV.WORK_START)
                {
                    sWorkDay = DateTime.Now.ToString("yyyyMMdd");
                }
                else
                {
                    sWorkDay = grdSearchItem.CsmGridGetCell(grdSearchItem.CsmGridSelectedRowIndex, 6);
                }

                sRet = m_cEmpCommute.Execute(new string[] { txtUserNm.Tag.ToString(), sWorkDay, sRegType });
                if (sRet != UserCom.RST_OK) return;

                //재 조회
                SearchList();
            }
            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 SearchList()
        {
            try
            {

                TxtBoxInit();
                BtnInit();

                string sSaleDate = m_cPosStatus.Global.CultureToDate(txtSaleDate.Text);
                DataTable dt = (DataTable)m_cEmpCommute.GetData(new string[] { "List", sSaleDate, "" });

                if (dt == null || dt.Rows.Count == 0)
                {
                    grdSearchItem.CsmGridDataSource = m_dtItemInit;
                }
                else
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (dr["GOOUT_STAT"].ToString() == "1")
                        {
                            dr["TOT_STAT"] = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0564);  //"외출";
                            dr["REG_TIME"] = FormatTime(dr["GOOUT_TIME"].ToString());
                        }
                        else if (dr["REST_STAT"].ToString() == "1")
                        {
                            dr["TOT_STAT"] = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0567);  //"휴식";
                            dr["REG_TIME"] = FormatTime(dr["REST_TIME"].ToString());
                        }
                        else if (dr["WORK_STAT"].ToString() == "1")
                        {
                            dr["TOT_STAT"] = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0568);  //"출근";
                            dr["REG_TIME"] = FormatTime(dr["WORK_TIME"].ToString());
                        }
                        else if (dr["WORK_STAT"].ToString() == "0")
                        {
                            dr["TOT_STAT"] = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0569);  //"퇴근";
                            dr["REG_TIME"] = FormatTime(dr["WORK_TIME"].ToString());
                        }
                        else
                        {
                            dr["TOT_STAT"] = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0570);  //"등록내역없음";
                        }

                    }

                    grdSearchItem.CsmGridDataSource = dt;
                }

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

        private string FormatTime(string sDate)
        {
            string sRetDate = "";

            try
            {
                if (sDate == "") return sRetDate;

                sRetDate = CmUtil.MidH(sDate, 8, 2) + ":" + CmUtil.MidH(sDate, 10, 2) + ":" + CmUtil.MidH(sDate, 12, 2);
            }
            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 sRetDate;
        }


        /// <summary>
        /// 텍스트박스 입력 유효성 체크
        /// </summary>
        /// <param name="sender"></param>
        /// <returns></returns>
        private bool CheckTxtInput(string sRegType)
        {
            try
            {
                string sSaleDate = m_cPosStatus.Global.CultureToDate(txtSaleDate.Text);

                if (txtUserNm.Text == "" || txtStat.Text == "")
                {
                    //등록할 담당자를 선택하세요.
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0333);
                    return false;
                }
                else if (txtPsw.Text == "")
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0074);
                    return false;
                }
                else if (sRegType == ItemConst.EMP_COMMUTE_DIV.WORK_START && sSaleDate != DateTime.Now.ToString("yyyyMMdd"))
                {
                    //당일 날자만 출근 등록 가능합니다.
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0335);
                    return false;
                }


                int iTime = CmUtil.IntParse(DateTime.Now.ToString("HHmm"));

                if (iTime >= 0 && iTime <= 500 && sSaleDate == DateTime.Now.ToString("yyyyMMdd"))
                {
                    //이전일자 퇴근 체크
                    DataTable dt = (DataTable)m_cEmpCommute.GetData(new string[] { "List", DateTime.Now.AddDays(-1).ToString("yyyyMMdd"), txtUserNm.Tag.ToString() });

                    if (dt == null || dt.Rows.Count == 0)
                    {
                        //없음!
                    }
                    else
                    {
                        if (dt.Rows[0]["WORK_STAT"].ToString() == "1")
                        {
                            // yyyy-mm-dd 일자 퇴근처리가 되질 않았습니다. 처리를 먼저 하세요.
                            WinManager.ErrorMessage(string.Format(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0336), DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd")));
                            return false;
                        }
                    }
                }

                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;
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

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

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

        private void btnDate_Click(object sender, EventArgs e)
        {
            try
            {
                string sDate = WinBasic.ShowForm(new string[] { FormManager.FORM_CALENDAR });
                if (sDate != "")
                {
                    if (CmUtil.IntParse(sDate) > CmUtil.IntParse(DateTime.Now.ToString("yyyyMMdd")))
                    {
                        //미래 일자 처리 안함!
                    }
                    else
                    {
                        txtSaleDate.Text = m_cPosStatus.Global.DateToCulture(sDate);
                        SearchList();
                    }
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        

        #endregion DeviceEvent 관련

        //#20171101 출/퇴근 카드리딩 기능추가 start,phj
        #region 직원 정보 가져오기
        private string GetEmployeeInfo(string InputCardNo, ref string Employee_ID, ref string Employee_NM, ref string Employee_PW)
        {
            string sRet = UserCom.RST_ERR;
            string sQuery = string.Empty;

            Employee_ID = string.Empty;
            Employee_NM = string.Empty;
            Employee_PW = string.Empty;

            DataTable dtData = null;

            try
            {
                sQuery = " select * from MST_USER ";
                sQuery += "  where cmp_cd  ='" + m_cPosStatus.Base.CmpCd + "' ";
                sQuery += "    and stor_Cd = '" + m_cPosStatus.Base.StoreNo + "' ";
                sQuery += "    and RTRIM(cashier_card_no) <> ''";
                sQuery += "    and cashier_card_no = '" + InputCardNo + "' ";
                sQuery += "    and USE_YN  = '" + PosConst.MST_USE_YN.YES + "'";

                if (m_cSqlDbService.DBSelect(sQuery, out dtData) == UserCom.OK)
                {
                    if (dtData == null || dtData.Rows.Count == 0)
                    {
                        //등록되지않은 아이디입니다
                        sRet = UserCom.RST_ERR;
                    }
                    else
                    {
                        DataRow dr = dtData.Rows[0];
                        Employee_ID = CmUtil.GetDataRowStr(dr, "cashier_id");
                        Employee_NM = CmUtil.GetDataRowStr(dr, "cashier_nm");
                        Employee_PW = CmUtil.GetDataRowStr(dr, "cashier_pwd");

                        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;
            }
        }
        #endregion
        //#20171101 출/퇴근 카드리딩 기능추가 end,phj

        //#20171101 출/퇴근 카드리딩 기능추가 start,phj
        #region 출/퇴근 상태 자동처리
        private void StatusCheck()
        {
            try
            {
                string sSaleDate = m_cPosStatus.Global.CultureToDate(txtSaleDate.Text);
                DataTable dt = (DataTable)m_cEmpCommute.GetData(new string[] { "List", sSaleDate, txtUserNm.Tag.ToString() });

                if (dt == null || dt.Rows.Count == 0)
                {
                    //없음!
                    btnWork.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0568);  //"출근";
                    btnWork.Tag = ItemConst.EMP_COMMUTE_DIV.WORK_START; // "1";
                    btnWork.Visible = true;

                    txtStat.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0570);  //등록내역없음

                    btnProc_Click(btnWork, null);
                }
                else
                {

                    if (dt.Rows[0]["GOOUT_STAT"].ToString() == "1") //외출
                    {
                        btnGoOut.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0563);  //"외출종료";
                        btnGoOut.Tag = ItemConst.EMP_COMMUTE_DIV.GO_OUT_END;  //"6";
                        btnGoOut.Visible = true;

                        txtStat.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0564);  //"외출";

                        btnProc_Click(btnGoOut, null);
                    }
                    else if (dt.Rows[0]["REST_STAT"].ToString() == "1") //휴식
                    {
                        btnRest.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0566);  //"휴식종료";
                        btnRest.Tag = ItemConst.EMP_COMMUTE_DIV.REST_END; //"4";
                        btnRest.Visible = true;

                        txtStat.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0567);  //"휴식";

                        btnProc_Click(btnRest, null);
                    }
                    else if (dt.Rows[0]["WORK_STAT"].ToString() == "1") //출근
                    {
                        btnWork.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0569);  //"퇴근";
                        btnWork.Tag = ItemConst.EMP_COMMUTE_DIV.WORK_END; //"2";
                        //btnRest.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0565);  //"휴식시작";
                        //btnRest.Tag = ItemConst.EMP_COMMUTE_DIV.REST_START; //"3";
                        //btnGoOut.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0562);  //"외출시작";
                        //btnGoOut.Tag = ItemConst.EMP_COMMUTE_DIV.GO_OUT_START; // "5";
                        btnWork.Visible = true;
                        //btnRest.Visible = true;
                        //btnGoOut.Visible = true;

                        txtStat.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0568);  //출근

                        btnProc_Click(btnWork, null);
                    }
                    else if (dt.Rows[0]["WORK_STAT"].ToString() == "0")//퇴근
                    {
                        btnWork.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0568);  //"출근";
                        btnWork.Tag = ItemConst.EMP_COMMUTE_DIV.WORK_START; // "1";
                        btnWork.Visible = true;

                        txtStat.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0569);  //퇴근

                        btnProc_Click(btnWork, null);
                    }
                    else //등록내역없음
                    {
                        btnWork.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0568);  //"출근";
                        btnWork.Tag = ItemConst.EMP_COMMUTE_DIV.WORK_START; // "1";
                        btnWork.Visible = true;

                        txtStat.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0570);  //등록내역없음

                        btnProc_Click(btnWork, null);
                    }
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
        #endregion
        //#20171101 출/퇴근 카드리딩 기능추가 end,phj

    }
}
