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

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

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 제품 조회
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Win
{
    public partial class frmTestPluSearch : 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_sPosMenuKeyIn;
        public string PosMenuKeyIn { set { m_sPosMenuKeyIn = value; } get { return m_sPosMenuKeyIn; } }

        #endregion 변수 선언

        #region 생성자 & 소멸자 & 폼초기화
        public frmTestPluSearch()
        {
            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 frmTestPluSearch_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();
            SearchData();
        }

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

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

        private void frmTestPluSearch_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);

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

                if (m_sPosMenuKeyIn == PosKey.MENU_KEY.TEST_PLU_SEARCH_ALL)
                    lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0476); 
                else
                    lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0477);

                lblPluImg.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0462);


                //네이게이션 버튼 이미지 적용!
                btnUp.DefaultImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_UP1_BASIC);
                btnUp.ClickImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_UP1_PRESS);
                btnPgUp.DefaultImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_UP2_BASIC);
                btnPgUp.ClickImage = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_105X48_UP2_PRESS);

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

                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, FontStyle.Bold);
                
                //DataGridView 자체의 컬럼 헤더 Visible 여부
                gridList.CsmGridColumnHeadersVisible = true;
                //DataGridView 자체의 컬럼 헤더 높이
                gridList.CsmGridColumnHeadersHeight = 44;
                gridList.CsmGridRowsHeight = 38;

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

                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_0478));  // 판매시작일
                gridList.CsmGridColumnName(2, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0015));  // 상품명
                gridList.CsmGridColumnName(3, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0016));  // 단가
                gridList.CsmGridColumnName(4,"");
                gridList.CsmGridColumnName(5,"");
                gridList.CsmGridColumnName(6, "");
                //컬럼넓이 지정(406)
                gridList.CsmGridSetColumnWidth(new int[] { 50, 100, 170, 100, 0, 0, 0 });

                //컬럼 정렬 0:왼쪽, 1:가운데, 2:오른쪽
                gridList.CsmGridAlignment(new int[] { 1, 1, 0, 2, 2, 2, 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_NAME", typeof(string)));
                m_dtGridList.Columns.Add(new DataColumn("LIST_PRC", typeof(string)));
                m_dtGridList.Columns.Add(new DataColumn("LIST_SALEIMG", typeof(string)));
                m_dtGridList.Columns.Add(new DataColumn("LIST_BTNIMG", typeof(string)));
                m_dtGridList.Columns.Add(new DataColumn("LIST_DESC", 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 SearchData()
        {
            try
            {
                DataTable dtData;
                if (m_sPosMenuKeyIn == PosKey.MENU_KEY.TEST_PLU_SEARCH_ALL)
                    dtData = (DataTable)m_cTestMode.GetData(new string[] { "TEST_MODE_PLU_ALL" });
                else
                    dtData = (DataTable)m_cTestMode.GetData(new string[] { "TEST_MODE_PLU_NEW" });

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

                m_dtGridList.Clear();
                int nRow = 0;
                for (int i = 0; i < dtData.Rows.Count; i++)
                {
                    DataRow dr = dtData.Rows[i];

                    string sFileNameFul = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM.DATA.ITEM_CD).Trim() + "_FULL.PNG";
                    string sFileNameBtn = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM.DATA.ITEM_CD).Trim() + ".PNG";
                    if (File.Exists(BaseCom.NxCDPPath + PosConst.MST_IMG_PATH.ITEM + sFileNameFul) == true || File.Exists(BaseCom.NxCDPPath + PosConst.MST_IMG_PATH.ITEM + sFileNameBtn) == true)
                    {
                        DataRow drNewRow = m_dtGridList.NewRow();
                        nRow++;
                        drNewRow["LIST_NO"] = nRow.ToString();
                        drNewRow["LIST_DATE"] = m_cPosStatus.Global.DateToCulture(CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM.DATA.SALE_START_DT));
                        drNewRow["LIST_NAME"] = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM.DATA.SHTCUT_ITEMNM);
                        if (PosMstManager.GetPosOption(POS_OPTION.OPT005) == "0")
                            drNewRow["LIST_PRC"] = m_cPosStatus.Global.NumericTOCurrency(CmUtil.GetDataRowDouble(dr, PosMst.MST_ITEM.DATA.TAKE_OUT_SALE_AMT));
                        else
                            drNewRow["LIST_PRC"] = m_cPosStatus.Global.NumericTOCurrency(CmUtil.GetDataRowDouble(dr, PosMst.MST_ITEM.DATA.TAKE_IN_SALE_AMT));
                        //drNewRow["LIST_SALEIMG"] = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM.DATA.SALE_IMG_FILE_NM).Trim();
                        //drNewRow["LIST_BTNIMG"] = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM.DATA.BTN_ITEM_IMG).Trim();
                        drNewRow["LIST_SALEIMG"] = sFileNameFul;
                        drNewRow["LIST_BTNIMG"] = sFileNameBtn;
                        drNewRow["LIST_DESC"] = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM.DATA.ITEM_INFO).Trim() + "\n" + CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM.DATA.CALORY_INFO).Trim();

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

                gridList_GridClickEvent(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);
            }
        }
        #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 ((UI.CsmButton)sender == btnUp)
                {
                    gridList.CsmGridScroll("UP");
                    gridList_GridClickEvent(null, "");
                }
                else if ((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

        private void gridList_GridClickEvent(object sender, string rowIndex)
        {
            try
            {
                picPluImg.Image = null;
                lblPluInfo.Text = "";

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

                string sFileName = gridList.CsmGridGetCell(nRow, 4);
                picPluImg.Image = CmUtil.LoadImage(BaseCom.NxCDPPath + PosConst.MST_IMG_PATH.ITEM + sFileName);
                if (picPluImg.Image == null)
                {
                    sFileName = gridList.CsmGridGetCell(nRow, 5);
                    picPluImg.Image = CmUtil.LoadImage(BaseCom.NxCDPPath +  PosConst.MST_IMG_PATH.ITEM + sFileName);
                }

                string sPluInfo = gridList.CsmGridGetCell(nRow, 6);
                lblPluInfo.Text = sPluInfo;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }
    }
}
