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

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

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 시험모드 결과 조회
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Win
{
    public partial class frmTestModeSearch : 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 IDataProcessUs m_cDataSrv = null;
        private IDataServiceUs m_cTestMode = null;                                  // 테스트모드 서비스
        
        private bool bNotDoubleClik = false;

        /// <summary>
        /// 그리드 출력 데이터
        /// </summary>
        private DataTable m_dtGridList;

        /// <summary>
        /// 판매원 코드
        /// </summary>
        private string m_sCashierNo = "";
        public string CashierNo { set { m_sCashierNo = value; } get { return m_sCashierNo; } }
        /// <summary>
        /// 판매원 명
        /// </summary>
        private string m_sCashierName = "";
        public string CashierName { set { m_sCashierName = value; } get { return m_sCashierName; } }

        /// <summary>
        /// 메뉴키 값
        /// </summary>
        private string m_sPosMenuKeyIn;
        public string PosMenuKeyIn { set { m_sPosMenuKeyIn = value; } get { return m_sPosMenuKeyIn; } }

        #endregion 변수 선언

        #region 생성자 & 소멸자 & 폼초기화
        public frmTestModeSearch()
        {
            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_cDataSrv = (IDataProcessUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_SERVICE);
            m_cTestMode = (IDataServiceUs)sManager.InitServiceInstance(ServiceLists.BSV_ADMIN.DLL, ServiceLists.BSV_ADMIN.TEST_MODE);   
        }

        private void frmTestModeSearch_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();
            InitializeGrid();
        }

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

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

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

        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            try
            {
                // 이미지 로딩 처리
                picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_800X600);
                this.Size = new Size(800, 600);
                FormManager.MovePopUpForm(this, false, m_cPosStatus.Sale.ScreenSizeUser);
                FormManager.SetFormAllControlFont(this, m_cPosStatus.Base.FONT);
                FormManager.SetTextBoxGlobalInfo(this, m_cPosStatus.Global.m_stCultureMaster.nGroupingDigits, m_cPosStatus.Global.m_stCultureMaster.strGroupingSymbol
                    , m_cPosStatus.Global.m_stCultureMaster.nDecimalDigits, m_cPosStatus.Global.m_stCultureMaster.strDecimalSymbol);

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

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

                btnPgUp.Image = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_14X9_UP2_BASIC);
                btnUp.Image = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_14X9_UP1_BASIC);
                btnDown.Image = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_14X9_DOWN1_BASIC);
                btnPgDown.Image = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_14X9_DOWN2_BASIC);

                if (btnPgUp.Image != null) btnPgUp.Text = "";
                if (btnUp.Image != null) btnUp.Text = "";
                if (btnDown.Image != null) btnDown.Text = "";
                if (btnPgDown.Image != null) btnPgDown.Text = "";

                if ( m_sPosMenuKeyIn == PosKey.MENU_KEY.TEST_MODE_SEARCH)
                    lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0456); 
                else
                    lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0473); 

                lblCashierName.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0150);
                lblDate.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0354);

                btnSearch.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0004);
                
                txtCashierName.Text = m_sCashierName;
                txtStartDate.InputTypeFormat = m_cPosStatus.Global.m_stCultureMaster.strDatePattern;
                txtStartDate.Text = m_cPosStatus.Global.DateToCulture(m_cPosStatus.Base.SaleDate);
                txtEndDate.InputTypeFormat = m_cPosStatus.Global.m_stCultureMaster.strDatePattern;
                txtEndDate.Text = m_cPosStatus.Global.DateToCulture(m_cPosStatus.Base.SaleDate);
                
                bNotDoubleClik = 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 InitializeGrid()
        {
            try
            {
                gridList.CsmGridColumnHeadersFont = new Font(m_cPosStatus.Base.FONT, 12, gridList.CsmGridColumnHeadersFont.Style);
               
                //DataGridView 자체의 컬럼 헤더 Visible 여부
                gridList.CsmGridColumnHeadersVisible = true;
                //DataGridView 자체의 컬럼 헤더 높이
                gridList.CsmGridColumnHeadersHeight = 35;
                gridList.CsmGridRowsHeight = 38;

                //그리드의 컬럼 수
                gridList.CsmGridColumnCount = 6;
                //그리드의 한 화면에 보이는 로우수
                gridList.CsmGridShowPageRowsCount = 10;

                gridList.CsmGridSetHeaderBackColor(236, 238, 239);                             //그리드 헤더 배경색
                gridList.CsmGridDefaultRowBackColor = Color.FromArgb(255, 255, 255);           //그리드 홀수(Default)행의 배경색 지정
                gridList.CsmGridAlternateRowBackColor = Color.FromArgb(251, 253, 255);         //그리드 짝수(Alternate)행의 배경색 지정
                gridList.CsmGridBackGroundColor = Color.FromArgb(251, 253, 255);               //기본 백그라운드 컬러
                gridList.CsmGridHighlightColor = Color.FromArgb(255, 251, 211);                //그리드 선택 백 컬러
                gridList.CsmGridHighlightTextColor = Color.Black;                              //그리드 선택 글자 컬러

                //각 컬럼별 이름 지정
                gridList.CsmGridColumnName(0, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0014));
                gridList.CsmGridColumnName(1, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0457));      // 시험일자
                gridList.CsmGridColumnName(2, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0475));      // 시험시간
                gridList.CsmGridColumnName(3, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0246));      // 시험항목

                if (m_sPosMenuKeyIn == PosKey.MENU_KEY.TEST_MODE_SEARCH)
                    gridList.CsmGridColumnName(4, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0247));  // 완료여부
                else
                    gridList.CsmGridColumnName(4, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0474));  // 정답전체
                gridList.CsmGridColumnName(5, "");      // 시험ID

                //컬럼넓이 지정(720)
                gridList.CsmGridSetColumnWidth(new int[] {50, 110, 100, 340, 120, 0 });

                //컬럼 정렬 0:왼쪽, 1:가운데, 2:오른쪽
                gridList.CsmGridAlignment(new int[] {1, 1, 1, 0, 1, 2});

                m_dtGridList = new DataTable("GRID_LIST");
                m_dtGridList.Columns.Add(new DataColumn("LIST_NO", typeof(string)));
                m_dtGridList.Columns.Add(new DataColumn("LIST_DATE", typeof(string)));
                m_dtGridList.Columns.Add(new DataColumn("LIST_TIME", typeof(string)));
                m_dtGridList.Columns.Add(new DataColumn("LIST_NAME", typeof(string)));
                m_dtGridList.Columns.Add(new DataColumn("LIST_PASS", typeof(string)));
                m_dtGridList.Columns.Add(new DataColumn("LIST_CODE", typeof(string)));
                m_dtGridList.Clear();
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        /// <summary>
        /// 시험결과 조회 화면 표시
        /// </summary>
        private void SearchTxtInPut()
        {
            try
            {
                m_dtGridList.Clear();

                // 조회 일자
                string sDateStart = m_cPosStatus.Global.CultureToDate(txtStartDate.Text);
                string sDateEnd = m_cPosStatus.Global.CultureToDate(txtEndDate.Text);

                DataTable dtTest;
                if (m_sPosMenuKeyIn == PosKey.MENU_KEY.TEST_MODE_SEARCH)
                    dtTest = (DataTable)m_cTestMode.GetData(new string[] { Column.TR_CASHIER_TEST.ITEM, "1", m_sCashierNo, sDateStart, sDateEnd });
                else
                    dtTest = (DataTable)m_cTestMode.GetData(new string[] { Column.TR_CASHIER_TEST.ITEM, "2", m_sCashierNo, sDateStart, sDateEnd });

                int nRow = 0;
                if (dtTest != null && dtTest.Rows.Count > 0)
                {
                    foreach (DataRow dr in dtTest.Rows)
                    {
                        nRow++;
                        DataRow drNewRow = m_dtGridList.NewRow();
                        drNewRow["LIST_NO"] = nRow.ToString();
                        drNewRow["LIST_DATE"] = m_cPosStatus.Global.DateToCulture( CmUtil.GetDataRowStr(dr, Column.TR_CASHIER_TEST.NAME.TEST_DATE));
                        drNewRow["LIST_TIME"] = CmUtil.StrToTime(CmUtil.GetDataRowStr(dr, Column.TR_CASHIER_TEST.NAME.TEST_DATE).Substring(8, 6));

                        if (m_sPosMenuKeyIn == PosKey.MENU_KEY.TEST_MODE_SEARCH)
                        {
                            drNewRow["LIST_NAME"] = CmUtil.GetDataRowStr(dr, Column.TR_CASHIER_TEST.NAME.TEST_ENTRY_NM);
                            drNewRow["LIST_PASS"] = (CmUtil.GetDataRowStr(dr, Column.TR_CASHIER_TEST.NAME.TEST_PASS_YN) == "1") ? MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0248) : MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0493);
                            drNewRow["LIST_CODE"] = CmUtil.GetDataRowStr(dr, Column.TR_CASHIER_TEST.NAME.TEST_ENTRY_ID);
                        }
                        else
                        {
                            if (CmUtil.GetDataRowStr(dr, Column.TR_CASHIER_TEST.NAME.TEST_KIND) == "2")
                                drNewRow["LIST_NAME"] = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0460);
                            else
                                drNewRow["LIST_NAME"] = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0461);

                            drNewRow["LIST_PASS"] = CmUtil.GetDataRowInt(dr, Column.TR_CASHIER_TEST.NAME.PASS_CNT) + " / " + CmUtil.GetDataRowInt(dr, Column.TR_CASHIER_TEST.NAME.TEST_CNT);
                            drNewRow["LIST_CODE"] = "";
                        }

                        m_dtGridList.Rows.Add(drNewRow);
                    }
                }
                
                if ( nRow == 0)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0294);
                }

                gridList.CsmGridDataSource = m_dtGridList;
                gridList.CsmGridSelectRow(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);
            }
        }
        #endregion

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

                if (((Cosmos.UI.CsmButton)sender) == btnSearch)         // 조회
                {
                    SearchTxtInPut();
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnUp)
                {
                    gridList.CsmGridScroll("UP");
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnDown)
                {
                    gridList.CsmGridScroll("DOWN");
                }
                else if ((UI.CsmButton)sender == btnPgUp)
                {
                    gridList.CsmGridScroll("PAGE UP");
                }
                else if ((UI.CsmButton)sender == btnPgDown)
                {
                    gridList.CsmGridScroll("PAGE DOWN");
                }
                else if ((UI.CsmButton)sender == btnExit)
                {
                    bNotDoubleClik = false;

                    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);
               bNotDoubleClik = false;
            }
            bNotDoubleClik = false;
        }
        #endregion

        private void btnStartDate_Click(object sender, EventArgs e)
        {
            try
            {
                string sDate = WinBasic.ShowForm(new string[] { FormManager.FORM_CALENDAR });
                if (sDate != "" && sDate.Length == 8)
                {
                    txtStartDate.Text = m_cPosStatus.Global.DateToCulture(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);
            }
        }

        private void btnEndDate_Click(object sender, EventArgs e)
        {
            try
            {
                string sDate = WinBasic.ShowForm(new string[] { FormManager.FORM_CALENDAR });
                if (sDate != "" && sDate.Length == 8)
                {
                    txtEndDate.Text = m_cPosStatus.Global.DateToCulture(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);
            }
        }

    }
}
