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 frmCampaignInfo : 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 TranStatus m_cTrnStatus = new TranStatus();                         // 거래정보 참조
        
        private DeviceStatus m_cDevStatus = new DeviceStatus();                     // 디바이스 관리
        private IDataServiceUs m_cPosNoticeCom = null;                              // 공지사항 공통                               
        private ISaleCompleteUs m_cSaleComplete = null;
        private PosOLEDevice.DelegateOlePos delegatePos;
        
        private DataTable m_dtItemInit;                                             // 조회 상품 리스트

        private string m_sPosMenuKeIn;
        public string PosMenuKeyIn { set { m_sPosMenuKeIn = value; } get { return m_sPosMenuKeIn; } }

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

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

            m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
            m_cTrnStatus = (TranStatus)StateObject.TRAN;    // POS 거래정보

            delegatePos = new PosOLEDevice.DelegateOlePos(OnDeviceEvent);
            m_cDevStatus = (DeviceStatus)StateObject.DEVICE;
            m_cPosNoticeCom = (IDataServiceUs)sManager.InitServiceInstance(ServiceLists.BSV_BASIC.DLL, ServiceLists.BSV_BASIC.POS_NOTICE_COM);
            m_cSaleComplete = (ISaleCompleteUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.SALE_COMPLETE);

            GetBtnImg();

        }
        /// <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();

            if (m_sPosMenuKeIn != "") SelectParamList();
        }
        /// <summary>
        /// 폼클로즈
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmCheck_FormClosing(object sender, FormClosingEventArgs e)
        {
            VScrollbar.Attach(null);

            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, 544);

                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);

                txtPrtData.Font = new Font(m_cPosStatus.Base.FONT_FIX, txtPrtData.Font.Size, txtPrtData.Font.Style);

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

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0400);

                BtnPrt.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0257);
                
                InitializeGrid();

                VScrollbar.Attach(txtPrtData);

                SearchDataList();

                this.Select();
            }
            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.CsmGridColumnHeadersHeight = 38;              //DataGridView 자체의 컬럼 헤더 높이
                grdSearchItem.CsmGridColumnHeadersFont = new Font(m_cPosStatus.Base.FONT, 12);  //DataGridView 자체의 컬럼 헤더 폰트
                grdSearchItem.CsmGridRowsHeight = 39;
                grdSearchItem.CsmGridColumnCount = 5;                       //그리드의 컬럼수
                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[] { 40, 120, 257, 0, 0 });   //컬럼넓이 지정(417)
                grdSearchItem.CsmGridAlignment(new int[] { 2, 1, 0, 0, 0 });    //컬럼 정렬 0:왼쪽, 1:가운데, 2:오른쪽

                //각 컬럼별 이름 지정
                grdSearchItem.CsmGridColumnName(0, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0014));
                grdSearchItem.CsmGridColumnName(1, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0398));
                grdSearchItem.CsmGridColumnName(2, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0399));
                grdSearchItem.CsmGridColumnName(3, "CPI_EXPLN");
                grdSearchItem.CsmGridColumnName(4, "CPI_INFO");
                
                //그리드 초기화 테이블
                m_dtItemInit = new DataTable("INIT");
                m_dtItemInit.Columns.Add(new DataColumn("NO", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("CPI_CD", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("CPI_NM", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("CPI_EXPLN", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("CPI_INFO", typeof(string)));
                
                m_dtItemInit.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 GetBtnImg()
        {
            try
            {
                //네이게이션 버튼 이미지 적용!
                btnUp.DefaultImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_UP1_BASIC);
                btnUp.ClickImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_UP1_PRESS);
                btnUp2.DefaultImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_UP2_BASIC);
                btnUp2.ClickImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_UP2_PRESS);

                btnDw.DefaultImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_DOWN1_BASIC);
                btnDw.ClickImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_DOWN1_PRESS);
                btnDw2.DefaultImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_DOWN2_BASIC);
                btnDw2.ClickImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_DOWN2_PRESS);

            }
            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 Control Event
                        
        /// <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="rowIndex"></param>
        private void grdSearchItem_GridClickEvent(object sender, string rowIndex)
        {
            try
            {

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

                txtPrtData.Text = grdSearchItem.CsmGridGetCell(grdSearchItem.CsmGridSelectedRowIndex, 3).Replace("\n", Convert.ToChar(13).ToString() + Convert.ToChar(10).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);
            }
        }

        /// <summary>
        /// 텍스트 박스 드래그 막기!
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtPrtData_Enter(object sender, EventArgs e)
        {
            try
            {
                this.btnUp.Focus();
            }
            catch (Exception) { }

        }
        
        #endregion

        #region User Method
        /// <summary>
        /// 데이터 조회
        /// </summary>
        private void SearchDataList()
        {
            try
            {
                DataTable dt = null;

                dt = (DataTable)m_cPosNoticeCom.GetData(new string[] { PosMst.MST_CPI.TABLE_NAME, "", "", "" });

                if(dt == null || dt.Rows.Count == 0)
                {
                    //데이터 없음!
                    grdSearchItem.CsmGridDataSource = m_dtItemInit;
                    txtPrtData.Text = "";
                    txtPrtData.Tag = "";
                }
                else
                {
                    
                    //그리드 적용!
                    grdSearchItem.CsmGridDataSource = dt;
                    grdSearchItem_GridClickEvent(null, 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);
            }


        }
        /// <summary>
        /// 저널 데이터 컷팅
        /// </summary>
        /// <param name="sPrtData"></param>
        /// <returns></returns>
        private string PrintDispCuting(string sPrtData)
        {
            string sRecvData = string.Empty;
            int iDataLen = 0;

            try
            {
                while(iDataLen <= sPrtData.Length)
                {
                    sRecvData += CmUtil.MidH(sPrtData, iDataLen + 5, 42) + Convert.ToChar(13).ToString() + Convert.ToChar(10).ToString();

                    iDataLen += 47;

                }

            }
            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 sRecvData;

        }

        private void SelectParamList()
        {
            try
            {

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

                for (int iRow = 0; grdSearchItem.CsmGridRowsCount > iRow; iRow++)
                {
                    if (m_sPosMenuKeIn == grdSearchItem.CsmGridGetCell(iRow, 1))
                    {
                        grdSearchItem.CsmGridSelectRow(iRow);
                        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);
            }
        }

             
        #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 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);
                
            }

            
        }
        
        #endregion DeviceEvent 관련

        private void BtnPrt_Click(object sender, EventArgs e)
        {
            try
            {
                if (((Cosmos.UI.CsmButton)sender) == BtnPrt) // 프린트
                {
                    PrintCampaignInfo();
                }

            }
            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>
        /// <returns></returns>
        private bool PrintCampaignInfo()
        {

            bool bRet = false;

            try
            {

                string sPrintData = "";

                if (txtPrtData.Text == "")
                {
                    return bRet;
                }

                string[] aPrtData = txtPrtData.Text.Split(new string[] { Convert.ToChar(13).ToString() + Convert.ToChar(10).ToString() }, StringSplitOptions.None);

                for (int iRow = 0; iRow < aPrtData.Length; iRow++)
                {
                    sPrintData += SetData(aPrtData[iRow].Replace("\r","").Replace("\n",""));
                }

                //6.컷팅
                sPrintData += SetData("");
                sPrintData += PosConst.PRT_HDR.PRT_CUT;

                bRet = m_cSaleComplete.PosSaleRePrint(sPrintData, 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;
        }

        private string SetLine(string sLine)
        {
            string sRet = PosConst.PRT_HDR.PRT_NOR;

            try
            {
                for (int iRow = 0; iRow < 42; iRow++) sRet += sLine;
                sRet = SetData(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;
        }

        private string SetData(string sData)
        {
            string sRet = "";

            try
            {

                int iDataLen = 0;
                while (iDataLen <= CmUtil.LenH(sData))
                {
                    sRet += CmUtil.RPadH(PosConst.PRT_HDR.PRT_NOR + CmUtil.MidH(sData, iDataLen, 42), 47);
                    iDataLen += 42;

                    if (CmUtil.MidH(sData, iDataLen, 42).Trim() == "") break;

                }
                
                
                //sRet = CmUtil.RPadH(sData, 47);
            }
            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;
        }
        

    }
}
