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

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

namespace Cosmos.Win
{
    public partial class frmLabelBarcodePrint : Form
    {
        #region 변수 선언
        private string m_sMessageType;
        private string m_sMessageStr;

        private string m_sItemNm = "";

        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private StateServer StateObject = (StateServer)StateServer.GetInstance();
        private ILabelPrinterUs m_cLabelPrinterUs = null;
        private PosStatus m_cPosStatus = null;
        private DeviceStatus m_cDevStatus;                                          // 디바이스 관리
        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스
        
        bool bConnection = false;
        #endregion 변수 선언

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

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

            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
            m_cLabelPrinterUs = (ILabelPrinterUs)sManager.InitServiceInstance(ServiceLists.AGENT_OLEDEVICE.DLL, ServiceLists.AGENT_OLEDEVICE.DEVICE_LABELPRINTER);

            m_cPosStatus = (PosStatus)StateObject.POS;
            m_cDevStatus = (DeviceStatus)StateObject.DEVICE;        //POS 장치정보
        }

        private void frmLabelBarcodePrint_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 + "()", "");

            // Measuring Agent Stop
            if (m_cPosStatus.Mst.CntryDiv == ItemConst.CNTRY_DIV.KR && m_cPosStatus.Mst.CorpDiv == ItemConst.CORP_DIV.BR)
            {
                if (m_cDevStatus.Scale.UseYn == true)
                {
                    IMeasuring cMeasuringMain = (IMeasuring)sManager.InitServiceInstance(ServiceLists.AGENT_MEASURING.DLL, ServiceLists.AGENT_MEASURING.MEASURING_MAIN);
                    cMeasuringMain.StopMeasuring();
                }
            }

            this.BackgroundImage = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_MSGBOX);

            InitControl();

            ReadyToBarcode();
        }

        private void frmLabelBarcodePrint_FormClosing(object sender, FormClosingEventArgs e)
        {
            m_cLabelPrinterUs.CloseDevice();

            // Measuring Agent Start
            if (m_cPosStatus.Mst.CntryDiv == ItemConst.CNTRY_DIV.KR && m_cPosStatus.Mst.CorpDiv == ItemConst.CORP_DIV.BR)
            {
                if (m_cDevStatus.Scale.UseYn == true)
                {
                    IMeasuring cMeasuringMain = (IMeasuring)sManager.InitServiceInstance(ServiceLists.AGENT_MEASURING.DLL, ServiceLists.AGENT_MEASURING.MEASURING_MAIN);
                    cMeasuringMain.StartMeasuring();
                }
            }

            UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", lblTitle.Text);
        }
        #endregion 생성자 & 소멸자

        #region 폼 컨트롤 초기화
        /// <summary>
        /// 폼 컨트롤 초기화
        /// </summary>
        private void InitControl()
        {
            CmMessage m_PosConfig = CmMessage.MakeMessageFromFile(BaseCom.NxIniPath + PosConst.INI_FILE_NAME.PosConfig);

            string sFont = m_PosConfig.GetMessage("GLOBAL").GetMessageValue("Font");
            FormManager.SetFormAllControlFont(this, sFont);

            long nScreenSizeUser = CmUtil.LongParse(m_PosConfig.GetMessage("GLOBAL").GetMessageValue("ScreenSizeUser"));
            FormManager.MovePopUpForm(this, false, nScreenSizeUser);

            lblTitle.BackColor = Color.FromArgb(70, 86, 98);
            lblTitle.ForeColor = Color.White;   //Color.FromArgb(35, 31, 32);

            // 라벨 이름 설정
            lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0731);

            m_sMessageType = PosConst.MSG_BOX_TYPE.ERROR;

            tbBarcodeNum.Text = string.Empty;

            bConnection = m_cLabelPrinterUs.OpenDevice(m_cPosStatus.Base.OlePosLabelPrinterSerialPortNumber, (int)m_cPosStatus.Base.OlePosLabelPrinterSerialBaudRate);
            if (bConnection == true)
            {
                m_sMessageType = PosConst.MSG_BOX_TYPE.CONFIRM;
                m_sMessageStr = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0313);
            }
            else
            {
                m_sMessageType = PosConst.MSG_BOX_TYPE.ERROR;
                m_sMessageStr = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0312);
            }


            switch (m_sMessageType)
            {
                case PosConst.MSG_BOX_TYPE.CONFIRM:     // 확인메시지
                    btnOk.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0009);    //확인

                    break;
                case PosConst.MSG_BOX_TYPE.ERROR:     // 에러메시지
                    btnOk.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0009);    //확인

                    lblTitle.BackColor = Color.Red;
                    lblTitle.ForeColor = Color.White;

                    break;
            }

            lblMessage.Text = m_sMessageStr;

            this.TopMost = true;

        }
        #endregion 폼 컨트롤 초기화

        #region Control Event
        private void tbBarcodeNum_KeyDown(object sender, KeyEventArgs e)
        {
            string sRet = UserCom.RST_ERR;
            string sInputData = string.Empty;
            string sItemCd = string.Empty;
            string sScanCd = string.Empty;
            string sShtcutItemNm = string.Empty;

            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    sInputData = tbBarcodeNum.Text;
                    tbBarcodeNum.Text = string.Empty;

                    if (sInputData.Length > 0)
                    {
                        sRet = m_cDataCommon.SeletItemMstToBarCode(m_cPosStatus.Base.StoreNo, sInputData, ref sItemCd, ref sScanCd, ref sShtcutItemNm);

                        if (sRet != UserCom.RST_ERR)
                        {
                            //출력 함수 호출
                            LabelPrinterBarCode(sShtcutItemNm, sInputData);
                        }
                        //if (m_cPosStatus.Mst.CorpDiv == ItemConst.CORP_DIV.BR)
                        //{
                        //    if (sInputData.Length == 16)
                        //    {
                        //        if (CmUtil.MidH(sInputData, 10, 6) == "N9999X")
                        //        {
                        //            sItemCd = CmUtil.MidH(sInputData, 4, 6);
                        //        }
                        //        else
                        //        {
                        //            sItemCd = CmUtil.MidH(sInputData, 10, 6);
                        //        }
                        //    }
                        //    else
                        //    {
                        //        sItemCd = sInputData;
                        //    }

                        //    //유통기한 체크
                        //    if (ScanBarcodeCheck(m_cPosStatus.Base.StoreNo, sInputData, sItemCd, ref sShtcutItemNm) == false)
                        //    {
                        //        return;
                        //    }
                        //}

                        
                    }

                    ReadyToBarcode();
                }
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion Control Event

        #region User Method
        /// <summary>
        /// 텍스트박스에 포커스를 고정
        /// </summary>
        private void ReadyToBarcode()
        {
            try
            {
                tbBarcodeNum.Select();
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
        }

        private void ControlOnFormClick(object sender, EventArgs e)
        {
            try
            {
                ReadyToBarcode();
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
        }

        private void LabelPrinterBarCode(string sItemNm, string sScanCode)
        {
            try
            {
                string sStorNm = CmUtil.GetDataRowStr(PosMstManager.GetMstStore(), PosMst.MST_STORE.DATA.STORNM);    //점포명
                
                m_cLabelPrinterUs.PrintProductBarCodeInfo(sItemNm, sScanCode, sStorNm);
            }
            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 바코드 유통기간 체크
        ///// <summary>
        ///// 바코드스캔 코드 체크
        ///// </summary>
        ///// <param name="sScanCode"></param>
        ///// <returns></returns>
        //private bool ScanBarcodeCheck(string sSubStoreNo, string sScanCode, string sItemCode, ref string sShtcutItemNm)
        //{

        //    bool bRet = true;

        //    string sMsg = "";
        //    string sCreateDate = string.Empty;  //생산일자
        //    string sExpireDt = string.Empty;    //유통기한
        //    string sProduceDt = string.Empty;

        //    try
        //    {
        //        //유통기한 가져오기
        //        DataTable dtDataInfo = m_cDataCommon.SeletItemMstToItemCode(sSubStoreNo, sItemCode);
        //        if (dtDataInfo == null || dtDataInfo.Rows.Count == 0)
        //        {
        //            WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0010));
        //            bRet = false;
        //        }
        //        else
        //        {
        //            DataRow dr = dtDataInfo.Rows[0];

        //            int iExpire = CmUtil.GetDataRowInt(dr, PosMst.MST_ITEM.DATA.DISTBT_EXPIRE_NOD);
        //            sShtcutItemNm = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM.DATA.SHTCUT_ITEMNM);

        //            if (iExpire > 0)
        //            {

        //                // 년 2byte                                  월 2byte                                   일 2byte
        //                sProduceDt = "20" + AlphaToDate(sScanCode.Substring(0, 1)) + AlphaToDate(sScanCode.Substring(1, 1)) + AlphaToDate(sScanCode.Substring(2, 1));

        //                if (sProduceDt.Length != 8)
        //                {
        //                    UserLog.WriteLogFile(UserCom.LOG_DEBUG, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
        //                        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "InputBarCodeToDate = " + sProduceDt);
        //                }
        //                else
        //                {
        //                    //유통기간 날짜구하기!
        //                    sExpireDt = GetExpireDate(sProduceDt, iExpire);

        //                    if (sExpireDt != "")
        //                    {
        //                        if (sExpireDt != DateTime.Now.ToString("yyyyMMdd"))
        //                        {
        //                            if (CmUtil.IntParse(sProduceDt) < CmUtil.IntParse(sExpireDt))
        //                            {
        //                                sCreateDate = string.Format("{0}-{1}-{2}", sProduceDt.Substring(0, 4), sProduceDt.Substring(4, 2), sProduceDt.Substring(6, 2));
        //                                sExpireDt = string.Format("{0}-{1}-{2}", sExpireDt.Substring(0, 4), sExpireDt.Substring(4, 2), sExpireDt.Substring(6, 2));
        //                                sMsg = string.Format(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0525), CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM.DATA.SHTCUT_ITEMNM), sCreateDate, sExpireDt);

        //                                WinManager.ErrorMessage(sMsg);
        //                                bRet = 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);
        //    }

        //    return bRet;
        //}

        ///// <summary>
        ///// 유통기간 문자열 날짜 변환
        ///// </summary>
        ///// <param name="sScanCode"></param>
        ///// <returns></returns>
        //private string AlphaToDate(string sScanCode)
        //{

        //    string sRet = "";

        //    try
        //    {
        //        string[] aAlpha = new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "A"
        //                                       , "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"
        //                                       , "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U"
        //                                       , "V" };

        //        for (int iRow = 0; iRow <= aAlpha.Length - 1; iRow++)
        //        {
        //            if (aAlpha[iRow] == sScanCode)
        //            {
        //                sRet = (iRow + 1).ToString().PadLeft(2, '0');
        //                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);
        //    }
        //    return sRet;
        //}

        ///// <summary>
        ///// 유통기간 일자 및 체크
        ///// </summary>
        ///// <param name="sExpireDt"></param>
        ///// <returns></returns>
        //private string GetExpireDate(string sCreateDate, int iExpireDay)
        //{
        //    string EDate = "";

        //    try
        //    {
        //        string SDate = string.Format("{0}-{1}-{2}", sCreateDate.Substring(0, 4), sCreateDate.Substring(4, 2), sCreateDate.Substring(6, 2));

        //        DateTime T1 = DateTime.Parse(SDate);
        //        DateTime T2 = T1.AddDays(iExpireDay);

        //        EDate = T2.Date.ToString("yyyyMMdd");

        //    }
        //    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 EDate;
        //}

        //#endregion 바코드 유통기간 체크
        #endregion User Method
    }
}
