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 frmTestModeList : 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 DataTable m_dtTestMode;

        /// <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; } }
        
        #endregion 변수 선언

        #region 생성자 & 소멸자 & 폼초기화
        public frmTestModeList()
        {
            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 frmTestModeList_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();
            DisplayGrid(true);
            gridList_GridClickEvent(null, "");
        }

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

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

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

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

                FormManager.SetFormAllControlFont(this, m_cPosStatus.Base.FONT);
                FormManager.SetTextBoxGlobalInfo(this, m_cPosStatus.Global.m_stCultureMaster.nGroupingDigits, m_cPosStatus.Global.m_stCultureMaster.strGroupingSymbol
                    , m_cPosStatus.Global.m_stCultureMaster.nDecimalDigits, m_cPosStatus.Global.m_stCultureMaster.strDecimalSymbol);

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

                btnExit.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BTN_CLOSE);
                if (btnExit.Image != null) btnExit.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 = "";

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0243); 
                lblCashierName.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0150);

                btnEnter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0245);

                bNotDoubleClik = false;

                txtCashierName.Text = m_sCashierName;
            }
            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 = 36;
                gridList.CsmGridRowsHeight = 39;

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

                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_0246));  //시험항목
                gridList.CsmGridColumnName(2, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0247));  //완료여부
                gridList.CsmGridColumnName(3, "");      // 시험ID

                //컬럼넓이 지정(718)
                gridList.CsmGridSetColumnWidth(new int[] {50, 548, 120, 0 });

                //컬럼 정렬 0:왼쪽, 1:가운데, 2:오른쪽
                gridList.CsmGridAlignment(new int[] {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_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 DisplayGrid(bool bMstSearch)
        {
            try
            {
                if (bMstSearch == true)
                {
                    m_dtTestMode = (DataTable)m_cTestMode.GetData(new string[] { PosMst.MST_TEST_MODE.TABLE_NAME, m_sCashierNo });
                    if (m_dtTestMode == null || m_dtTestMode.Rows.Count == 0)
                    {
                        WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0161);    //진행중인 시험이 없습니다.
                        return;
                    }
                }
                if (m_dtTestMode == null || m_dtTestMode.Rows.Count == 0) return;

                m_dtGridList.Clear();

                int nCompCnt = 0;
                for (int i = 0; i < m_dtTestMode.Rows.Count; i++)
                {
                    DataRow dr = m_dtTestMode.Rows[i];

                    DataRow drNewRow = m_dtGridList.NewRow();
                    drNewRow["LIST_NO"] = (i + 1).ToString();
                    drNewRow["LIST_NAME"] = CmUtil.GetDataRowStr(dr, PosMst.MST_TEST_MODE.DATA.TEST_ENTRY_NM);
                    if ( CmUtil.GetDataRowStr(dr, PosMst.MST_TEST_MODE.DATA.TEST_PASS_YN) == "1")
                    {
                        drNewRow["LIST_PASS"] = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0248);
                        nCompCnt++;
                    }
                    else
                    {
                        drNewRow["LIST_PASS"] = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0493);
                    }
                    drNewRow["LIST_CODE"] = CmUtil.GetDataRowStr(dr, PosMst.MST_TEST_MODE.DATA.TEST_ENTRY_ID);

                    m_dtGridList.Rows.Add(drNewRow);
                }
                gridList.CsmGridDataSource = m_dtGridList;
                gridList.CsmGridSelectRow(0); 

                lblStatus.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0226) + string.Format(": {0:D2}   ", m_dtTestMode.Rows.Count)
                                + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0248) + string.Format(": {0:D2}   ", nCompCnt)
                                + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0493) + string.Format(": {0:D2}", m_dtTestMode.Rows.Count - nCompCnt);
            }
            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 버튼 입력 처리

        private void gridList_GridClickEvent(object sender, string rowIndex)
        {
            try
            {
                // 시험항목 설명 표시
                lblExpln.Text = "";

                int nRow = gridList.CsmGridSelectedRowIndex;
                if (nRow < 0) return;

                string sEntryId = gridList.CsmGridGetCell(nRow, 3);
                if (sEntryId == "") return;

                if (m_dtTestMode == null || m_dtTestMode.Rows.Count == 0) return;

                foreach (DataRow dr in m_dtTestMode.Rows)
                {
                    if (sEntryId == CmUtil.GetDataRowStr(dr, PosMst.MST_TEST_MODE.DATA.TEST_ENTRY_ID))
                    {
                        lblExpln.Text += CmUtil.GetDataRowStr(dr, PosMst.MST_TEST_MODE.DATA.TEST_ENTRY_EXPLN1) + "\n";
                        lblExpln.Text += CmUtil.GetDataRowStr(dr, PosMst.MST_TEST_MODE.DATA.TEST_ENTRY_EXPLN2) + "\n";
                        lblExpln.Text += CmUtil.GetDataRowStr(dr, PosMst.MST_TEST_MODE.DATA.TEST_ENTRY_EXPLN3) + "\n";
                        lblExpln.Text += CmUtil.GetDataRowStr(dr, PosMst.MST_TEST_MODE.DATA.TEST_ENTRY_EXPLN4) + "\n";
                        lblExpln.Text += CmUtil.GetDataRowStr(dr, PosMst.MST_TEST_MODE.DATA.TEST_ENTRY_EXPLN5);

                        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>
        /// 버튼 입력 처리
        /// </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) == btnEnter)         // 선택
                {
                    CompleteTxtInPut();
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnUp)
                {
                    gridList.CsmGridScroll("UP");
                    gridList_GridClickEvent(null, "");     // 시험항목 설명표시
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnDown)
                {
                    gridList.CsmGridScroll("DOWN");
                    gridList_GridClickEvent(null, "");     // 시험항목 설명표시
                }
                else if ((UI.CsmButton)sender == btnPgUp)
                {
                    gridList.CsmGridScroll("PAGE UP");
                    gridList_GridClickEvent(null, "");
                }
                else if ((UI.CsmButton)sender == btnPgDown)
                {
                    gridList.CsmGridScroll("PAGE DOWN");
                    gridList_GridClickEvent(null, "");
                }
                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

        #region 입력 완료 처리
        /// <summary>
        /// 시험시작 처리
        /// </summary>
        /// <param name="nFlowMode"></param>
        /// <returns></returns>
        private bool CompleteTxtInPut()
        {
            try
            {
                if (m_dtTestMode == null || m_dtTestMode.Rows.Count == 0) return false;

                int nRow = gridList.CsmGridSelectedRowIndex;
                if (nRow < 0) return false;

                string sEntryId = gridList.CsmGridGetCell(nRow, 3);
                if (sEntryId == "") return false;

                string sTestPassYN = "0";
                foreach (DataRow dr in m_dtTestMode.Rows)
                {
                    if (sEntryId != CmUtil.GetDataRowStr(dr, PosMst.MST_TEST_MODE.DATA.TEST_ENTRY_ID)) continue;

                    // 시험모드 진행 화면
                    frmTestMode fForm = (frmTestMode)FormManager.GetForm(FormManager.FORM_TEST_MODE);
                    if (fForm == null)
                    {
                        fForm = new frmTestMode();
                        FormManager.AddForm(FormManager.FORM_TEST_MODE, fForm);
                    }

                    fForm.TestEntryId = sEntryId;
                    fForm.TestEntryNm = CmUtil.GetDataRowStr(dr, PosMst.MST_TEST_MODE.DATA.TEST_ENTRY_NM);
                    fForm.TestErrPrmtCnt = CmUtil.GetDataRowInt(dr, PosMst.MST_TEST_MODE.DATA.ERR_PRMT_CNT);
                    fForm.TestLimitTime = CmUtil.GetDataRowInt(dr, PosMst.MST_TEST_MODE.DATA.TEST_LMT_TIME);
                    fForm.TestEntryExpln = lblExpln.Text;

                    if (fForm.ShowDialog() == DialogResult.OK)
                    {
                        dr[PosMst.MST_TEST_MODE.DATA.TEST_PASS_YN] = "1";
                        sTestPassYN = "1";
                    }
                    break;
                }

                if (sTestPassYN == "1")
                {
                    DisplayGrid(false);
                    if (nRow < m_dtTestMode.Rows.Count - 1) gridList.CsmGridSelectRow(nRow + 1);
                }

                // 시험결과 저장(TEST_KIND, CASHIER_NO, TEST_ENTRY_ID, PASS_CNT, TEST_CNT, TEST_PASS_YN)
                string sRet = m_cTestMode.Execute(new string[] { "1", m_sCashierNo, sEntryId, "0", "0", sTestPassYN });
                if (sRet != UserCom.RST_OK) 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


    }
}
