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 frmTestEduPlu : 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_dtTestMode;
        /// <summary>
        /// 시험항목 데이터 위치
        /// </summary>
        private int m_nTestModePos;

        /// <summary>
        /// 시험 오답횟수
        /// </summary>
        private int m_nTestErrCnt = 0;
        /// <summary>
        /// 시험 정답횟수
        /// </summary>
        private int m_nTestSucCnt = 0;
        /// <summary>
        /// 시험 현재위치
        /// </summary>
        private int m_nTestNowRow = 0;
        /// <summary>
        /// 시험 시험갯수
        /// </summary>
        private int m_nTestMaxCnt = 0;
        /// <summary>
        /// 정답 상품코드
        /// </summary>
        private string m_sTestPluCode = "";

        /// <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 frmTestEduPlu()
        {
            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 frmTestEduPlu_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();
            SearchTestData();
        }

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

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

        private void frmTestEduPlu_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.Size = new Size(800, 600);
                // 이미지 로딩 처리
                picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_800X600);
                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);

                //테마색상 적용!
                btnNext.BackColor = CmUtil.GetColorToString(m_cPosStatus.ScnMst.ThemeColor);
                btnExit.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BTN_CLOSE);
                if (btnExit.Image != null) btnExit.Text = "";

                if (m_sPosMenuKeyIn == PosKey.MENU_KEY.TEST_MODE_PLU_ALL)
                    lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0460); 
                else
                    lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0461);

                lblPluImg.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0462);
                lblTestTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0463);
                lblTestDesc.Text = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0296);

                lblCashierName.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0150);
                txtCashierName.Text = m_sCashierName;

                tmrEduPlu.Tag = "";
                picPluImg.Tag = "";
                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 SearchTestData()
        {
            try
            {
                m_nTestSucCnt = 0;
                m_nTestNowRow = 0;
                m_nTestMaxCnt = 10;

                m_dtTestMode = (DataTable)m_cTestMode.GetData(new string[] { "TEST_MODE_PLU_ALL" });

                //if (m_sPosMenuKeyIn == PosKey.MENU_KEY.TEST_MODE_PLU_ALL)
                //    m_dtTestMode = (DataTable)m_cTestMode.GetData(new string[] { "TEST_MODE_PLU_ALL" });
                //else
                //    m_dtTestMode = (DataTable)m_cTestMode.GetData(new string[] { "TEST_MODE_PLU_NEW" });

                if (m_dtTestMode == null || m_dtTestMode.Rows.Count == 0)
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0294);
                    return;
                }

                if (m_nTestMaxCnt > m_dtTestMode.Rows.Count) m_nTestMaxCnt = m_dtTestMode.Rows.Count;

                NextTestDisplay();
            }
            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) == btnNext)               // 다음
                {
                    if (tmrEduPlu.Tag.ToString() == "SUCCESS")
                    {
                        NextTestDisplay();
                    }
                    else if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0168) == true)     // 다음화면 진행시 시험을 통과 할수 없습니다. 그래도 진행 하시겠습니까?
                    {
                        m_nTestNowRow++;
                        NextTestDisplay();
                    }
                    tmrEduPlu.Tag = "";
                }
                else if ((UI.CsmButton)sender == btnExit)
                {
                    if (m_nTestNowRow > 0)
                    {
                        if (WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0168) == false)
                        {
                            bNotDoubleClik = false;
                            return;
                        }
                        // 시험결과 저장(TEST_KIND, CASHIER_NO, TEST_ENTRY_ID, PASS_CNT, TEST_CNT, TEST_PASS_YN)
                        if (m_sPosMenuKeyIn == PosKey.MENU_KEY.TEST_MODE_PLU_ALL)
                            m_cTestMode.Execute(new string[] { "2", m_sCashierNo, "", m_nTestSucCnt.ToString(), m_nTestMaxCnt.ToString(), "0" });
                        else
                            m_cTestMode.Execute(new string[] { "3", m_sCashierNo, "", m_nTestSucCnt.ToString(), m_nTestMaxCnt.ToString(), "0" });
                    }

                    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>
        /// <returns></returns>
        private bool NextTestDisplay()
        {
            string sTestPluName = "";
            string sTestPluPrice ="";

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

                m_nTestErrCnt = 0;
                lblTestResult.Text = "";

                if (m_nTestNowRow >= m_nTestMaxCnt)        // 시험완료
                {
                    bool bRet = WinManager.QuestionMessage(POS_MESSAGE.ERROR.MSG_0299);

                    if (m_sPosMenuKeyIn == PosKey.MENU_KEY.TEST_MODE_PLU_ALL)
                        m_cTestMode.Execute(new string[] { "2", m_sCashierNo, "", m_nTestSucCnt.ToString(), m_nTestMaxCnt.ToString(), (m_nTestSucCnt == m_nTestMaxCnt) ? "1" : "0" });
                    else
                        m_cTestMode.Execute(new string[] { "3", m_sCashierNo, "", m_nTestSucCnt.ToString(), m_nTestMaxCnt.ToString(), (m_nTestSucCnt == m_nTestMaxCnt) ? "1" : "0" });

                    if (bRet == false)
                    {
                        this.DialogResult = DialogResult.OK;
                        this.Close();

                        return true;
                    }
                    else
                    {
                        m_nTestSucCnt = 0;
                        m_nTestNowRow = 0;
                    }
                }

                lblStep.Text = "▶ STEP : " + string.Format("{0:D2} / {1:D2}", m_nTestNowRow + 1, m_nTestMaxCnt);
                lblError.Text = "▶ " + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0727) + " : " + string.Format("{0:D2} / {1:D2}", m_nTestSucCnt, m_nTestNowRow - m_nTestSucCnt);

                // 시험 문항 랜덤 출제
                Random rndPos = new Random(int.Parse(DateTime.Now.ToString("HHmmss")));
                if (m_nTestNowRow % 3 == 0) m_nTestModePos = rndPos.Next(m_dtTestMode.Rows.Count);

                m_sTestPluCode = "";
                for (int i = 0; i < m_dtTestMode.Rows.Count; i++)
                {
                    DataRow drTest = m_dtTestMode.Rows[m_nTestModePos];

                    if (m_sPosMenuKeyIn == PosKey.MENU_KEY.TEST_MODE_PLU_NEW)
                    {
                        string sStartDT = CmUtil.GetDataRowStr(drTest, PosMst.MST_ITEM.DATA.NEW_ITEM_START_DT);
                        string sFinishDT = CmUtil.GetDataRowStr(drTest, PosMst.MST_ITEM.DATA.NEW_ITEM_FNSH_DT);
                        
                        if (sStartDT == "" || CmUtil.LongParse(m_cPosStatus.Base.SaleDate) < CmUtil.LongParse(sStartDT) || CmUtil.LongParse(m_cPosStatus.Base.SaleDate) > CmUtil.LongParse(sFinishDT))
                        {
                            m_nTestModePos++;
                            if (m_nTestModePos >= m_dtTestMode.Rows.Count) m_nTestModePos = 0;
                            continue;
                        }
                    }
                     
                    //string sFileName = CmUtil.GetDataRowStr(drTest, PosMst.MST_ITEM.DATA.SALE_IMG_FILE_NM).Trim();
                    //picPluImg.Image = CmUtil.LoadImage(BaseCom.NxCDPPath + PosConst.MST_IMG_PATH.ITEM + sFileName);
                    //if (picPluImg.Image == null)
                    //{
                    //    sFileName = CmUtil.GetDataRowStr(drTest, PosMst.MST_ITEM.DATA.BTN_ITEM_IMG).Trim();
                    //    picPluImg.Image = CmUtil.LoadImage(BaseCom.NxCDPPath + PosConst.MST_IMG_PATH.ITEM + sFileName);
                    //}
                    string sFileName = CmUtil.GetDataRowStr(drTest, PosMst.MST_ITEM.DATA.ITEM_CD).Trim() + "_FULL.PNG";
                    picPluImg.Image = CmUtil.LoadImage(BaseCom.NxCDPPath + PosConst.MST_IMG_PATH.ITEM + sFileName);
                    if (picPluImg.Image == null)
                    {
                        sFileName = CmUtil.GetDataRowStr(drTest, PosMst.MST_ITEM.DATA.ITEM_CD).Trim() + ".PNG";
                        picPluImg.Image = CmUtil.LoadImage(BaseCom.NxCDPPath + PosConst.MST_IMG_PATH.ITEM + sFileName);
                    }
                    if (picPluImg.Image == null)
                    {
                        m_nTestModePos++;
                        if (m_nTestModePos >= m_dtTestMode.Rows.Count) m_nTestModePos = 0;
                        continue;
                    }

                    m_sTestPluCode = CmUtil.GetDataRowStr(drTest, PosMst.MST_ITEM.DATA.ITEM_CD);
                    sTestPluName = CmUtil.GetDataRowStr(drTest, PosMst.MST_ITEM.DATA.SHTCUT_ITEMNM);

                    if (PosMstManager.GetPosOption(POS_OPTION.OPT005) == "0")
                        sTestPluPrice = m_cPosStatus.Global.NumericTOCurrency(CmUtil.GetDataRowDouble(drTest, PosMst.MST_ITEM.DATA.TAKE_OUT_SALE_AMT));
                    else
                        sTestPluPrice = m_cPosStatus.Global.NumericTOCurrency(CmUtil.GetDataRowDouble(drTest, PosMst.MST_ITEM.DATA.TAKE_IN_SALE_AMT));

                    lblPluInfo.Text = CmUtil.GetDataRowStr(drTest, PosMst.MST_ITEM.DATA.ITEM_INFO).Trim() + "\n" + CmUtil.GetDataRowStr(drTest, PosMst.MST_ITEM.DATA.CALORY_INFO).Trim();

                    lblPluName.Text = sTestPluName;
                    lblPluName.Visible = false;
                    break;
                }

                if (m_sTestPluCode == "")
                {
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0294);
                    btnTestMenu.ClearMenuButtonInfo();                     // 설정된 메뉴정보 초기화
                    tmrEduPlu.Enabled = true;
                    return false;
                }

                //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                btnTestMenu.SetMenuButtonCount(3, 3);                  // 메뉴버튼갯수 설정
                btnTestMenu.BackColor = CmUtil.GetColorToString("223223223");
                btnTestMenu.VisibleUpDown = false;
                btnTestMenu.BackColorUpDown = Color.White;
                btnTestMenu.ForeColorUpDown = Color.Black;

                btnTestMenu.ClearMenuButtonInfo();                     // 설정된 메뉴정보 초기화
                    
                int nStartPos = m_dtTestMode.Rows.Count - 10 > 0 ? rndPos.Next(m_dtTestMode.Rows.Count - 10) : 0;
                int nTestPluPos = rndPos.Next(m_dtTestMode.Rows.Count > 9 ? 9 : m_dtTestMode.Rows.Count);
                int nExamMaxRow = 0;

                bool bExistSuccess = false;
                for (int j = nStartPos; j < m_dtTestMode.Rows.Count; j++)
                {
                    DataRow dr = m_dtTestMode.Rows[j];
                    if (CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY.DATA.ITEM_CD) == m_sTestPluCode && bExistSuccess == true) continue;

                    nExamMaxRow++;
                    Cosmos.UI.CsmMenu.MenuBtnInfo cMenuInfo = new Cosmos.UI.CsmMenu.MenuBtnInfo();
                    cMenuInfo.sClassCode = "00";      // 대분류코드
                    cMenuInfo.sGroupCode = "0000";    // 중분류코드
                    cMenuInfo.nSeqNo = nExamMaxRow;   // 표시순번

                    if (CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY.DATA.ITEM_CD) == m_sTestPluCode || nTestPluPos == (nExamMaxRow - 1))
                    {
                        cMenuInfo.sMenuCode = m_sTestPluCode;               // 메뉴 연결코드
                        cMenuInfo.sMenuName = sTestPluName;                 // 메뉴 명
                        cMenuInfo.sMenuPrice = sTestPluPrice;               // 메뉴 가격
                        bExistSuccess = true;
                    }
                    else
                    {
                        cMenuInfo.sMenuCode = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM_KEY.DATA.ITEM_CD);                   // 메뉴 연결코드
                        cMenuInfo.sMenuName = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM.DATA.SHTCUT_ITEMNM);                 // 메뉴 명

                        if (PosMstManager.GetPosOption(POS_OPTION.OPT005) == "0")
                            cMenuInfo.sMenuPrice = m_cPosStatus.Global.NumericTOCurrency(CmUtil.GetDataRowDouble(dr, PosMst.MST_ITEM.DATA.TAKE_OUT_SALE_AMT));      // 메뉴 가격
                        else
                            cMenuInfo.sMenuPrice = m_cPosStatus.Global.NumericTOCurrency(CmUtil.GetDataRowDouble(dr, PosMst.MST_ITEM.DATA.TAKE_IN_SALE_AMT));      // 메뉴 가격
                    }
                    cMenuInfo.cBackColor = Color.White;         // 버튼 백 컬러
                    cMenuInfo.cForeColorName = Color.Black;     // 메뉴명 컬러
                    cMenuInfo.cForeColorPrice = Color.Red;      // 메뉴가격 컬러
                    cMenuInfo.fFontSizeName = 10;               // 메뉴명 폰트 사이즈
                    cMenuInfo.fFontSizePrice = 10;              // 메뉴 가격 폰트 사이즈
                    cMenuInfo.nButtonSize = 0;                  // 메뉴버튼 사이즈(0:일반,1:가로확대,2:세로확대,3:가로세로확대)
                    cMenuInfo.cMenuImage = "";

                    btnTestMenu.AddMenuButtonInfo(cMenuInfo);

                    if (nExamMaxRow == 9) break;
                }
                btnTestMenu.DisplayMenuButton("00", "0000");

                m_nTestModePos++;
                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

        private void btnTestMenu_MenuClickHandler(object sender, string sMenuCode)
        {
            try
            {
                if (tmrEduPlu.Tag != null && tmrEduPlu.Tag.ToString() == "SUCCESS") return;

                if (sMenuCode == m_sTestPluCode) 
                {
                    // 정답
                    if (m_nTestErrCnt == 0) m_nTestSucCnt++;

                    lblPluName.Visible = true;

                    lblTestResult.ForeColor = Color.Blue;
                    lblTestResult.Text = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0297);
                    
                    m_nTestNowRow++;
                    tmrEduPlu.Tag = "SUCCESS";
                }
                else
                {
                    lblTestResult.ForeColor = Color.Red;
                    lblTestResult.Text = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0298);

                    m_nTestErrCnt++;
                    tmrEduPlu.Tag = "FAIL";
                }
                tmrEduPlu.Enabled = 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);
            }
        }

        private void tmrEduPlu_Tick(object sender, EventArgs e)
        {
            try
            {
                tmrEduPlu.Enabled = false;
                
                if (m_sTestPluCode == "")
                {
                    // 시험문재가 없거나 출제 오류이면 화면 종료
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                    return;
                }

                if (tmrEduPlu.Tag.ToString() == "SUCCESS")
                {
                    //NextTestDisplay();
                }
                else
                {
                    lblTestResult.ForeColor = Color.White;
                }
                //tmrEduPlu.Tag = "";
                //lblTestResult.Text = "";
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
    }
}
