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 frmItemSearch : 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 IDataProcessUs m_cDataService = null;
        private ISalePluItemUs m_cPluService = null;                                //판매 등록 관리

        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스

        private DeviceStatus m_cDevStatus = new DeviceStatus();                     // 디바이스 관리
        private PosOLEDevice.DelegateOlePos delegatePos;

        private string[,] aStr = new string[5,2];                                  //조건값

        private int iChrPage = 1;                                                   //단어 검색 페이지

        private DataTable m_dtItemInit;                                             // 조회 상품 리스트
        private DataTable m_dtSelect;                                               // 조회 상품 리스트

        private string m_sPosMenuKeyOut;
        public string PosMenuKeyOut { set { m_sPosMenuKeyOut = value; } get { return m_sPosMenuKeyOut; } }

        #endregion
        
        #region 생성자 & 소멸자
        public frmItemSearch()
        {
            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_cDataService = (IDataProcessUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_SERVICE);
            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
            m_cPluService = (ISalePluItemUs)sManager.InitServiceInstance(ServiceLists.BSV_SALE.DLL, ServiceLists.BSV_SALE.SALE_PLU_ITEM);
            delegatePos = new PosOLEDevice.DelegateOlePos(OnDeviceEvent);
            m_cDevStatus = (DeviceStatus)StateObject.DEVICE;

            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();
            InitializeGrid();
        }
        /// <summary>
        /// 폼클로즈
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmCheck_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>
        /// <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, 600);

                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 = "";

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

                lblItemTy.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0221);
                lblSubStor.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0222);
                lblSearch.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0223);
                btnAdd.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0224);
                btnDel.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0021);
                BtnSave.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0126);

                txtStrDsp.Text = "";

                m_sPosMenuKeyOut = "";

                aStr = new string[5, 2];

                LoadKey();

                ComboBoxInit();

                iChrPage = 1;
            }
            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
            {
                //네이게이션 버튼 이미지 적용!

                btnUp2.Image = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_14X9_UP2_BASIC);
                btnUp.Image = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_14X9_UP1_BASIC);
                btnDw.Image = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_14X9_DOWN1_BASIC);
                btnDw2.Image = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_14X9_DOWN2_BASIC);
                btnUpS.Image = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_14X9_UP1_BASIC);
                btnDwS.Image = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_14X9_DOWN1_BASIC);
                
                if (btnUp2.Image != null) btnUp2.Text = "";
                if (btnUp.Image != null) btnUp.Text = "";
                if (btnDw.Image != null) btnDw.Text = "";
                if (btnDw2.Image != null) btnDw2.Text = "";
                if (btnUpS.Image != null) btnUpS.Text = "";
                if (btnDwS.Image != null) btnDwS.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);
            }
        }

        /// <summary>
        /// 콤보박스 초기화
        /// </summary>
        private void ComboBoxInit()
        {

            try
            {

                cbItemTy.Items.Clear();

                //상품 유형 셋팅
                cbItemTy.Items.Add("1-" + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0226));
                cbItemTy.Items.Add("2-" + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0227));
                cbItemTy.SelectedIndex = 0;



                cbSubStor.Items.Clear();

                //현재 매장에 정보를 읽어 온다.
                cbSubStor.Items.Add(CmUtil.GetDataRowStr(PosMstManager.GetMstStore(), PosMst.MST_STORE.DATA.STOR_CD) + "-"+ CmUtil.GetDataRowStr(PosMstManager.GetMstStore(), PosMst.MST_STORE.DATA.STORNM));

                //서브 점포 정보를 읽어 온다.
                DataTable dt = m_cDataCommon.SelectSubStr(PosMst.MST_COMPLEX_SHOP_STOR.TABLE_NAME);

                if (dt == null || dt.Rows.Count <= 0)
                {
                    //없음!
                }
                else
                {
                    foreach(DataRow dr in dt.Rows)
                    {
                        cbSubStor.Items.Add(CmUtil.GetDataRowStr(dr, PosMst.MST_COMPLEX_SHOP_STOR.DATA.COMPLEX_SHOP_STOR_CD) + "-" + CmUtil.GetDataRowStr(PosMstManager.GetMstStore(), PosMst.MST_COMPLEX_SHOP_STOR.DATA.COMPLEX_SHOP_STOR_NM));
                    }
                }
                cbSubStor.SelectedIndex = 0;

            }
            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.CsmGridColumnHeadersFont = new Font(m_cPosStatus.Base.FONT, 12);  //DataGridView 자체의 컬럼 헤더 폰트
                grdSearchItem.CsmGridColumnHeadersHeight = 39;              //DataGridView 자체의 컬럼 헤더 높이
                grdSearchItem.CsmGridRowsHeight = 40;
                grdSearchItem.CsmGridColumnCount = 6;                       //그리드의 컬럼수
                grdSearchItem.CsmGridShowPageRowsCount = 7;                 //그리드의 한 화면에 보이는 로우수
                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[] { 30, 90, 180, 91, 0, 0 });   //컬럼넓이 지정(392)
                grdSearchItem.CsmGridAlignment(new int[] { 2, 1, 0, 2, 1, 1 });               //컬럼 정렬 0:왼쪽, 1:가운데, 2:오른쪽

                //각 컬럼별 이름 지정
                grdSearchItem.CsmGridColumnName(0, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0014));
                grdSearchItem.CsmGridColumnName(1, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0178));
                grdSearchItem.CsmGridColumnName(2, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0015));
                grdSearchItem.CsmGridColumnName(3, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0231));
                grdSearchItem.CsmGridColumnName(4, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0222));
                grdSearchItem.CsmGridColumnName(5, "SUB_SET_MNG_TYPE");


                // 상품권 등록정보 표시 그리드
                grdSelectItem.CsmGridColumnHeadersVisible = false;          //DataGridView 자체의 컬럼 헤더 Visible 여부
                grdSelectItem.CsmGridColumnHeadersFont = new Font(m_cPosStatus.Base.FONT, 12);  //DataGridView 자체의 컬럼 헤더 폰트
                grdSelectItem.CsmGridColumnHeadersHeight = 34;              //DataGridView 자체의 컬럼 헤더 높이
                grdSelectItem.CsmGridRowsHeight = 34;
                grdSelectItem.CsmGridColumnCount = 6;                       //그리드의 컬럼수
                grdSelectItem.CsmGridShowPageRowsCount = 4;                 //그리드의 한 화면에 보이는 로우수
                grdSelectItem.CsmGridSetHeaderBackColor(236, 238, 239);                             //그리드 헤더 배경색
                grdSelectItem.CsmGridDefaultRowBackColor = Color.FromArgb(255, 255, 255);           //그리드 홀수(Default)행의 배경색 지정
                grdSelectItem.CsmGridAlternateRowBackColor = Color.FromArgb(251, 253, 255);         //그리드 짝수(Alternate)행의 배경색 지정
                grdSelectItem.CsmGridBackGroundColor = Color.FromArgb(251, 253, 255);               //기본 백그라운드 컬러
                grdSelectItem.CsmGridHighlightColor = Color.FromArgb(255, 251, 211);                //그리드 선택 백 컬러
                grdSelectItem.CsmGridHighlightTextColor = Color.Black;                              //그리드 선택 글자 컬러
                grdSelectItem.CsmGridSetColumnWidth(new int[] { 30, 90, 180, 91, 0, 0 });     //컬럼넓이 지정(392)
                grdSelectItem.CsmGridAlignment(new int[] { 2, 1, 0, 2, 1, 1 });               //컬럼 정렬 0:왼쪽, 1:가운데, 2:오른쪽

                
                //그리드 초기화 테이블
                m_dtItemInit = new DataTable("INIT");
                m_dtItemInit.Columns.Add(new DataColumn("NO", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("ITEM_CD", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("ITEM_NM", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("SALE_PRC", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("SUB_STOR_CD", typeof(string)));
                m_dtItemInit.Columns.Add(new DataColumn("SUB_SET_MNG_TYPE", typeof(string)));

                m_dtItemInit.Clear();


                m_dtSelect = m_dtItemInit.Clone();

            }
            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 LoadKey()
        {

            bool bRet = false;

            try
            {
                DataTable dtFuncKey = m_cPluService.SearchMenuMaster(PosMst.MST_PLU_NM.TABLE_NAME);
                if (dtFuncKey == null || dtFuncKey.Rows.Count <= 0)
                {
                    // WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0000); // 기능키 그룹 마스터가 없습니다
                    return false;
                }

                // 문자 기능키 초기화
                btnFuncChar.SetFuncButtonCount(4, 4);                 // 버튼갯수 설정
                btnFuncChar.VisibleUpDown = false;
                btnFuncChar.BackColor = CmUtil.GetColorToString("202207213");
                btnFuncChar.BackColorUpDown = Color.GhostWhite; // CCmUtil.GetColorToString("225230236");
                btnFuncChar.ClearFuncButtonInfo();                    // 설정된 메뉴정보 초기화

                foreach (DataRow dr in dtFuncKey.Rows)
                {
                    Cosmos.UI.CsmFunc.FuncBtnInfo cFuncInfo = new Cosmos.UI.CsmFunc.FuncBtnInfo();

                    cFuncInfo.sGroupCode = CmUtil.GetDataRowStr(dr, PosMst.MST_PLU_NM.DATA.KEY_MODE);       // 분류코드
                    cFuncInfo.nSeqNo = CmUtil.GetDataRowInt(dr, PosMst.MST_PLU_NM.DATA.P_POSITION);            // 표시순번
                    cFuncInfo.sFuncText = CmUtil.GetDataRowStr(dr, PosMst.MST_PLU_NM.DATA.PLU_NM);          // 기능 명


                    cFuncInfo.sFuncCode = string.Format("{0}^{1}^{2}^{3}^{4}^{5}^{6}^", CmUtil.GetDataRowStr(dr, PosMst.MST_PLU_NM.DATA.PLU_NM)
                        ,CmUtil.GetDataRowStr(dr, PosMst.MST_PLU_NM.DATA.PLU_1_FR),CmUtil.GetDataRowStr(dr, PosMst.MST_PLU_NM.DATA.PLU_1_TO)
                        ,CmUtil.GetDataRowStr(dr, PosMst.MST_PLU_NM.DATA.PLU_2_FR),CmUtil.GetDataRowStr(dr, PosMst.MST_PLU_NM.DATA.PLU_2_TO)
                        ,CmUtil.GetDataRowStr(dr, PosMst.MST_PLU_NM.DATA.PLU_3_FR),CmUtil.GetDataRowStr(dr, PosMst.MST_PLU_NM.DATA.PLU_3_TO));
                    

                    cFuncInfo.cBackColor = Color.White;  // 백 컬러
                    cFuncInfo.cForeColor = Color.Black;  // 명 컬러
                    cFuncInfo.fFontSize = 10;           // 명 폰트 사이즈
                    cFuncInfo.nButtonSize = 0;          // 버튼 사이즈(0:일반,1:가로확대,2:세로확대,3:가로세로확대)

                    btnFuncChar.AddFuncButtonInfo(cFuncInfo);
                }
                                                
                dtFuncKey = m_cPluService.SearchMenuMaster(PosMst.MST_PLU_AMT.TABLE_NAME);
                if (dtFuncKey == null || dtFuncKey.Rows.Count <= 0)
                {
                    // WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0000); // 기능키 그룹 마스터가 없습니다
                    return false;
                }


                // 금액 기능키 초기화
                btnFuncAmt.SetFuncButtonCount(4, 4);                 // 버튼갯수 설정
                btnFuncAmt.VisibleUpDown = false;
                btnFuncAmt.BackColor = CmUtil.GetColorToString("202207213");
                btnFuncAmt.BackColorUpDown = Color.GhostWhite; // CmUtil.GetColorToString("225230236");
                btnFuncAmt.ClearFuncButtonInfo();                    // 설정된 메뉴정보 초기화

                foreach (DataRow dr in dtFuncKey.Rows)
                {
                    Cosmos.UI.CsmFunc.FuncBtnInfo cFuncInfo = new Cosmos.UI.CsmFunc.FuncBtnInfo();

                    cFuncInfo.sGroupCode = "000";                                                           // 분류코드
                    cFuncInfo.nSeqNo = CmUtil.GetDataRowInt(dr, PosMst.MST_PLU_AMT.DATA.P_POSITION);           // 표시순번
                    cFuncInfo.sFuncText = CmUtil.GetDataRowStr(dr, PosMst.MST_PLU_AMT.DATA.PLU_AMT_NM);     // 기능 명


                    cFuncInfo.sFuncCode = string.Format("{0}^{1}^{2}^", CmUtil.GetDataRowStr(dr, PosMst.MST_PLU_AMT.DATA.PLU_AMT_NM)
                        , CmUtil.GetDataRowStr(dr, PosMst.MST_PLU_AMT.DATA.FROM_AMT), CmUtil.GetDataRowStr(dr, PosMst.MST_PLU_AMT.DATA.TO_AMT));
                    
                    cFuncInfo.cBackColor = Color.White; // 백 컬러
                    cFuncInfo.cForeColor = Color.Black; // 명 컬러
                    cFuncInfo.fFontSize = 10;           // 명 폰트 사이즈
                    cFuncInfo.nButtonSize = 0;          // 버튼 사이즈(0:일반,1:가로확대,2:세로확대,3:가로세로확대)

                    btnFuncAmt.AddFuncButtonInfo(cFuncInfo);
                }


                btnFuncChar.DisplayFuncButton("1");
                btnFuncAmt.DisplayFuncButton("000");


                bRet = 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 bRet;

        }


        #endregion
        
        #region Control Event
                
        #region 버튼 입력 처리
        /// <summary>
        /// 버튼 입력 처리
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnProc_Click(object sender, EventArgs e)
        {
            try
            {
                if (((Cosmos.UI.CsmButton)sender) == btnAdd) // 추가
                {
                    RegItemAdd();
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnDel) // 삭제
                {
                    DelItem();
                }
                else if (((Cosmos.UI.CsmButton)sender) == btnBack)  // 지우기
                {

                    if (txtStrDsp.Text.Length == 1 || txtStrDsp.Text.Length == 0)
                    {
                        BackSpace();
                        txtStrDsp.Text = "";
                        grdSearchItem.CsmGridDataSource = m_dtItemInit;
                    }
                    else
                    {
                        BackSpace();

                        SetDspStr();

                        //조회 호출
                        ItemSearchToDb("");
                    }

                }
                else if (((Cosmos.UI.CsmButton)sender) == BtnSave) // 저장
                {
                    SaveItem();

                }
                
            }
            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
        /// <summary>
        /// 문자 검색 조건 클릭 이벤트
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="sFuncCode"></param>
        private void btnFuncChar_FuncClickHandler(object sender, string sFuncCode)
        {
            try
            {

                string[] aParam = new string[5];

                bool bRet = false;


                if (SpitFuncCode(sFuncCode, ref aParam) == true)
                {
                    switch(aParam[1].ToString())
                    {
                        case "CH":  // 조건 값 체인지
                            {
                                if(iChrPage == 3)
                                {
                                    iChrPage = 1;
                                }
                                else
                                {
                                    iChrPage++;
                                }

                                btnFuncChar.DisplayFuncButton(iChrPage.ToString());

                                break;
                            }
                        case "SH":  //전체 조회
                            {
                                txtStrDsp.Text = "";
                                aStr = new string[5, 2];
                                ItemSearchToDb("");
                                break;
                            }
                        default:
                            {
                                bRet = SetQueryWhere(aParam);
                                break;
                            }

                    }


                    if(bRet == true)
                    {
                        
                        SetDspStr();

                        //조회 호출
                        ItemSearchToDb("");
                    }

                }

            }
            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="sFuncCode"></param>
        private void btnFuncAmt_FuncClickHandler(object sender, string sFuncCode)
        {

            string sSQL = string.Empty;
            string[] aParam = new string[6];
            bool bRet = false;

            try
            {
                
                if (SpitFuncCode(sFuncCode, ref aParam) == true)
                {

                    if (aParam.Length > 2)
                    {
                        for (int iRow = 1; iRow < aParam.Length; iRow++)
                        {

                            if (iRow % 2 == 0 && aParam[iRow] != "")
                            {

                                if (PosMstManager.GetPosOption(POS_OPTION.OPT005) == "0")
                                {
                                    sSQL = string.Format(" AND A.TAKE_OUT_SALE_AMT BETWEEN {0} AND {1} ", aParam[iRow - 1], aParam[iRow]);
                                }
                                else
                                {
                                    sSQL = string.Format(" AND A.TAKE_IN_SALE_AMT BETWEEN {0} AND {1} ", aParam[iRow - 1], aParam[iRow]);
                                }
                            }

                        }

                        bRet = true;
                    }
                }

                if(bRet == true)
                {

                    SetDspStr();

                    //조회 호출
                    ItemSearchToDb(sSQL);
                }
            }
            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 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="e"></param>
        private void btnSarhProc_Click(object sender, EventArgs e)
        {
            try
            {
                if ((UI.CsmButton)sender == btnUpS)
                {
                    grdSelectItem.CsmGridScroll("UP");
                }
                else if ((UI.CsmButton)sender == btnDwS)
                {
                    grdSelectItem.CsmGridScroll("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="e"></param>
        private void cbItemTy_TextChanged(object sender, EventArgs e)
        {
            try
            {
                //ItemSearchToDb("");
            }
            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 User Method
        /// <summary>
        /// 등록 상품 저장
        /// </summary>
        private void SaveItem()
        {
            try
            {

                //선택 아이템 체크
                if (m_dtSelect.Rows.Count == 0)
                {
                    return;
                }
                
                //스트링 붙여 담기
                foreach(DataRow dr in m_dtSelect.Rows)
                {
                    m_sPosMenuKeyOut += CmUtil.RPadH(dr[4].ToString(),10) + dr[1].ToString() + "^";   
                }

                //정상 종료 확인
                this.DialogResult = DialogResult.OK;
                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);
                
            }
        }

        /// <summary>
        /// 상품 추가
        /// </summary>
        private void RegItemAdd()
        {

            try
            {

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

                string sSubSetMngType = grdSearchItem.CsmGridGetCell(grdSearchItem.CsmGridSelectedRowIndex, 5);


                // 마스터 이행시 일반 상품이 부가 상품으로 처리 되어 포스에서 체크 막음 임시!
                //if(sSubSetMngType == "1")
                //{
                //    //1:부가메뉴상품
                //    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0156);
                //    return;
                //}
                if(sSubSetMngType == "2")
                {
                    //2:세트상품
                    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0155);
                    return;
                }

                DataRow drNewRow = m_dtSelect.NewRow();
                drNewRow["NO"] = grdSelectItem.CsmGridRowsCount + 1;
                drNewRow["ITEM_CD"] = grdSearchItem.CsmGridGetCell(grdSearchItem.CsmGridSelectedRowIndex, 1);
                drNewRow["ITEM_NM"] = grdSearchItem.CsmGridGetCell(grdSearchItem.CsmGridSelectedRowIndex, 2);
                drNewRow["SALE_PRC"] = grdSearchItem.CsmGridGetCell(grdSearchItem.CsmGridSelectedRowIndex, 3);
                drNewRow["SUB_STOR_CD"] = grdSearchItem.CsmGridGetCell(grdSearchItem.CsmGridSelectedRowIndex, 4);
                drNewRow["SUB_SET_MNG_TYPE"] = grdSearchItem.CsmGridGetCell(grdSearchItem.CsmGridSelectedRowIndex, 5);

                m_dtSelect.Rows.Add(drNewRow);


                grdSelectItem.CsmGridDataSource = m_dtSelect;
                grdSelectItem.Refresh();



                int index = grdSelectItem.CsmGridRowsCount - 1;
                grdSelectItem.CsmGridFirstDisplayedScrollingRowIndex = 0;
                grdSelectItem.CsmGridSelectRow(index);

            }
            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 DelItem()
        {

            try
            {

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

                int iRow = int.Parse(grdSelectItem.CsmGridGetCell(grdSelectItem.CsmGridSelectedRowIndex, 0));

                m_dtSelect.Rows[iRow - 1].Delete();


                if (m_dtSelect.Rows.Count > 0 )
                {
                    int iSeq = 1;

                    foreach(DataRow dr in m_dtSelect.Rows)
                    {
                        dr[0] = iSeq;
                        iSeq++;
                    }

                }


                grdSelectItem.CsmGridDataSource = m_dtSelect;
                grdSelectItem.Refresh();

            }
            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="FuncCode"></param>
        /// <param name="aParam"></param>
        /// <returns></returns>
        private bool SpitFuncCode(string FuncCode, ref string[] aParam)
        {

            bool bRet = false;

            try
            {
                aParam = FuncCode.Split(new string[] { "^" }, StringSplitOptions.None);

                bRet = 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 bRet;

        }

        /// <summary>
        /// 쿼리 WHERE 절 만들기
        /// </summary>
        /// <param name="aParam"></param>
        /// <returns></returns>
        private bool SetQueryWhere(string[] aParam)
        {
            bool bRet = false;

            int iCnt = -1;
            string sSQL = string.Empty;

            try
            {

                for (int iRow = 0; iRow <= aStr.GetLength(0) - 1 ; iRow++)
                {
                    if (string.IsNullOrEmpty(aStr[iRow,0]) == true)
                    {

                        aStr[iRow, 0] = aParam[0];
                        iCnt = iRow;
                        break;
                    }

                }

                if (iCnt < 0) return false;

                if (aParam[0].Length > 1)
                {

                    sSQL += " AND (";

                    for (int iRow = 1; iRow < aParam.Length; iRow++)
                    {
                        if (iRow % 2 == 0 && aParam[iRow] != "")
                        {
                            //#Rhee, 20180131 미주 중간 제품 이름으로 검색해도 조회되게끔 수정 Start
                            // 기존
                            //sSQL += string.Format(" {0} (SUBSTRING(SHTCUT_ITEMNM,{1},1) >= '{2}' AND SUBSTRING(SHTCUT_ITEMNM,{1},1) < '{3}')"
                            //,iRow / 2 == 1 ? "":"OR" , iCnt + 1, aParam[iRow - 1], aParam[iRow]);
                            // 변경
                            if (m_cPosStatus.Base.CmpCd.ToUpper().Equals("PCUS"))
                            {
                                sSQL += string.Format(" {0} SHTCUT_ITEMNM LIKE '%{2}%' "
                                    , iRow / 2 == 1 ? "" : "OR", iCnt + 1, aParam[iRow - 1], aParam[iRow]);
                            }
                            else
                            {
                                sSQL += string.Format(" {0} (SUBSTRING(SHTCUT_ITEMNM,{1},1) >= '{2}' AND SUBSTRING(SHTCUT_ITEMNM,{1},1) < '{3}')"
                                    , iRow / 2 == 1 ? "" : "OR", iCnt + 1, aParam[iRow - 1], aParam[iRow]);
                            }
                            //#Rhee, 20180131 미주 중간 제품 이름으로 검색해도 조회되게끔 수정 End
                        }
                    }
                    aStr[iCnt, 1] = sSQL + ")";
                }
                else
                {
                    for (int iRow = 1; iRow < aParam.Length; iRow++)
                    {
                        if (iRow % 2 == 0 && aParam[iRow] != "")
                        {
                            //#Rhee, 20180131 미주 중간 제품 이름으로 검색해도 조회되게끔 수정 Start
                            // 기존
                            //sSQL = string.Format(" AND (SUBSTRING(SHTCUT_ITEMNM,{0},1) >= '{1}' AND SUBSTRING(SHTCUT_ITEMNM,{0},1) < '{2}')"
                            //    , iCnt + 1, aParam[iRow - 1], aParam[iRow]);
                            // 변경
                            if (m_cPosStatus.Base.CmpCd.ToUpper().Equals("PCUS"))
                            {
                                sSQL = string.Format(" AND SHTCUT_ITEMNM LIKE '%{1}%' "
                                , iCnt + 1, aParam[iRow - 1], aParam[iRow]);
                            }
                            else
                            {
                                sSQL = string.Format(" AND (SUBSTRING(SHTCUT_ITEMNM,{0},1) >= '{1}' AND SUBSTRING(SHTCUT_ITEMNM,{0},1) < '{2}')"
                                , iCnt + 1, aParam[iRow - 1], aParam[iRow]);
                            }
                            //#Rhee, 20180131 미주 중간 제품 이름으로 검색해도 조회되게끔 수정 End
                            aStr[iCnt, 1] += sSQL;
                        }
                    }
                }

                bRet = 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 bRet;


        }
        /// <summary>
        /// 검색 조건 박스 표시
        /// </summary>
        private void SetDspStr()
        {
            try
            {
                txtStrDsp.Text = "";

                for (int iRow = 0; iRow < aStr.GetLength(0); iRow++)
                {
                    if (string.IsNullOrEmpty(aStr[iRow, 0]) == false)
                    {

                        if (iRow == 0)
                        {
                            txtStrDsp.Text = aStr[iRow, 0].ToString();
                        }
                        else
                        {
                            txtStrDsp.Text += "-" + aStr[iRow, 0].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>
        private void BackSpace()
        {
            try
            {
                for (int iRow = aStr.GetLength(0) - 1; iRow >= 0; iRow--)
                {
                    if (string.IsNullOrEmpty(aStr[iRow, 0]) == false )
                    {
                        aStr[iRow, 0] = "";
                        aStr[iRow, 1] = "";

                        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="sAmtQuery"></param>
        private void ItemSearchToDb(string sAmtQuery)
        {
            string sParm1 = string.Empty;
            string sParm2 = string.Empty;

            try
            {
                //sParm2 = sAmtQuery;

                for (int iRow = 0; iRow < aStr.GetLength(0); iRow++)
                {
                    if (string.IsNullOrEmpty(aStr[iRow, 0]) == false)
                    {
                        sParm2 += aStr[iRow, 1];
                    }
                }

                //상품 유형 체크
                if(cbItemTy.Text.Substring(0, 1) == "2")
                    sParm2 += string.Format(" AND '{0}' BETWEEN A.NEW_ITEM_START_DT AND A.NEW_ITEM_FNSH_DT ", m_cPosStatus.Base.SaleDate);


                //서브매장 코드 체크

                string sStrTemp = cbSubStor.Text;
                string[] aParam = sStrTemp.Split(new string[] { "-" }, StringSplitOptions.None);
                sParm1 = aParam[0];

                if (string.IsNullOrEmpty(sAmtQuery) == false)
                    sParm2 += sAmtQuery;
                
                DataTable dt = m_cPluService.SearchMenuMaster(PosMst.MST_ITEM_SEARCH.TABLE_NAME, sParm1, sParm2);
                if (dt == null || dt.Rows.Count <= 0)
                {
                    grdSearchItem.CsmGridDataSource = m_dtItemInit;
                }
                else
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        dr["SALE_PRC"] = m_cPosStatus.Global.NumericTOCurrency(m_cDataService.DoubleParse(dr["SALE_PRC"].ToString()));
                    }
                    grdSearchItem.CsmGridDataSource = dt;

                    if (grdSearchItem.CsmGridRowsCount > 0) grdSearchItem.CsmGridSelectRow(grdSearchItem.CsmGridRowsCount - 1);


                    grdSearchItem.CsmGridSelectRow(0);

                }

                //grdSearchItem.Refresh();

            }
            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
            {
                m_sPosMenuKeyOut = "";
                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 관련

    }
}
