using System;
using System.Collections;
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.UserFrame;
using Cosmos.BaseFrame;
using Cosmos.ServiceProvider;
using Cosmos.Common;
using Cosmos.CommonManager;
using Cosmos.UI;

namespace Cosmos.Win
{
    /// <summary>
    /// 주방프린터 수동 선택 (상품선택)
    /// </summary>
    public partial class frmMenualOrderItem : Form
    {
        private SManager sManager = new SManager();                                 //이 객체를 통해 업무 Service 호출
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   //StateObject : StateServer Object(객체)
        private PosStatus m_cPosStatus;                                             //기본정보 참조
        private TranStatus m_cTrnStatus;                                            //거래정보 참조

        private IMasterUs m_cMstService = null;                                     // 마스터 서비스 
        
        /// <summary>
        /// 리스트 데이터
        /// </summary>
        private DataTable m_dtGridList;

        /// <summary>
        /// 해피오더 목록
        /// </summary>
        public ArrayList HappyOrderList { set; get; }

        /// <summary>
        /// 생성자  
        /// </summary>
        public frmMenualOrderItem()
        {
            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_cMstService = (IMasterUs)sManager.InitServiceInstance(ServiceLists.ASV_MASTER.DLL, ServiceLists.ASV_MASTER.POS_MASTER);

        }

        private void Form_Load(object sender, EventArgs e)
        {
            try
            {
                UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                          System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                          System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "");
                InitControls();
                InitializeGrid();
                if (DisplayGrid() == false)
                {
                    this.DialogResult = System.Windows.Forms.DialogResult.Abort;
                    this.Close();
                    return;
                }
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                    System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

        private void Form_Closing(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);
        }

        private void InitControls()
        {
            try
            {
                this.picBack.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.POP_SIZE_S);
                this.picBack.Location = new Point(0, 0);
                this.picBack.SendToBack(); 
                this.Size = this.picBack.Size = this.picBack.Image.Size;
                FormManager.MovePopUpForm(this, m_cPosStatus.Sale.SaleFlow == PosConst.SALE_FLOW.SALE_END ? true : 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);

                btnEnter.BackColor = CmUtil.GetColorToString(m_cPosStatus.ScnMst.ThemeColor);
                btnEnter.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0009);
                btnExit.Image = ImageManager.GetImage(BaseCom.NxImgPath, ImageManager.BTN_CLOSE);
                if (btnExit.Image != null) btnExit.Text = string.Empty;

                btnUp.Image = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_14X9_UP1_BASIC);
                btnDn.Image = CmUtil.LoadImage(BaseCom.NxImgPath + ImageManager.NAVIBTN_14X9_DOWN1_BASIC);
                if (btnUp.Image != null) btnUp.Text = string.Empty;
                if (btnDn.Image != null) btnDn.Text = string.Empty;

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0972);
                lblMemo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0177);

                txtMemo.Text = m_cTrnStatus.Sale.MenualOrderMemo;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                            System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                            ex.Message);
            }
        }

        private void InitializeGrid()
        {
            try
            {
                gridList.Tag = false; 

                gridList.CsmGridColumnHeadersFont = new Font(m_cPosStatus.Base.FONT, 12, gridList.CsmGridColumnHeadersFont.Style);

                //DataGridView 자체의 컬럼 헤더 Visible 여부
                gridList.CsmGridColumnHeadersVisible = true;
                gridList.CsmGridRowsHeight = 40;

                //그리드의 컬럼 수
                gridList.CsmGridColumnCount = 5;
                //그리드의 컬럼 헤더 높이 
                gridList.CsmGridRowsHeight = 30;
                //그리드의 한 화면에 보이는 로우수
                gridList.CsmGridShowPageRowsCount = 9;

                //그리드 홀수(Default)/짝수(Alternate)행의 배경색 지정
                gridList.BackColor = Color.White;
                gridList.ForeColor = Color.Black;
                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_0226));
                gridList.CsmGridColumnName(2, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0178));
                gridList.CsmGridColumnName(3, MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0015));

                //컬럼넓이 지정 
                gridList.CsmGridSetColumnWidth(new int[] { 70, 0, 0, 270, 0 });
                gridList.CsmGridColumnShowHide(1, false);
                gridList.CsmGridColumnShowHide(2, false);

                //컬럼 정렬 0:왼쪽, 1:가운데, 2:오른쪽
                gridList.CsmGridAlignment(new int[] { 1, 0, 0, 0, 0 });

                //컬럼헤더 대신 할 버튼
                btnSelectAll.Text = "□" + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0226);
                btnSelectAll.Width = 67;

                m_dtGridList = new DataTable("GRID_LIST");
                m_dtGridList.Columns.Add(new DataColumn("ITEM_CH", typeof(string)));
                m_dtGridList.Columns.Add(new DataColumn("SUB_STR", typeof(string)));
                m_dtGridList.Columns.Add(new DataColumn("ITEM_CD", typeof(string)));
                m_dtGridList.Columns.Add(new DataColumn("ITEM_NM", typeof(string)));
                m_dtGridList.Columns.Add(new DataColumn("ROW_IDX", typeof(string)));

                m_dtGridList.Clear();

                gridList.CsmGridDataSource = m_dtGridList;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                            System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                            ex.Message);
            }
        }

        private bool DisplayGrid()
        {
            try
            {
                m_dtGridList.Clear();
                gridList.CsmGridClear();
                gridList.SuspendLayout();

                // 주방프린트 사용(0 : 미사용, 1 : 사용)
                if (PosMstManager.GetPosOption(POS_OPTION.OPT506) != "1") return false;

                // 선불 주문대기번호 사용(0 : 미사용, 1 : 사용)
                if (m_cPosStatus.Base.PosType == PosConst.POS_TYPE.PRE_PAYMENT &&
                    PosMstManager.GetPosOption(POS_OPTION.OPT008) == "0") return false;

                // 주방프린터 자동/수동 출력 여부 (0:자동 1:수동(프린터선택) 2:수동(상품선택))
                if (PosMstManager.GetPosOption(POS_OPTION.OPT425) != "2") return false;

                // 주문상품/해피오더 목록에서 주문중 또는 주문수정 상품 추출 
                List<string> lstktchItems = new List<string>();

                if (HappyOrderList != null)
                {
                    // 해피오더 일때
                    foreach (Column.TR_HPORD.HPORD_ITEM item in HappyOrderList)
                    {
                        lstktchItems.Add(string.Format("'{0}{1}{2}'", "999", m_cPosStatus.Base.StoreNo, item.GoodsCode));
                    }
                }
                else
                {
                    // 일반주문 일때
                    ArrayList pluItems = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);
                    foreach (Column.TR_PLU.DATA item in pluItems)
                    {
                        if (item.ORDER_OK_FLAG == PosConst.PLU_ORDER_OK_FLAG.ORDER_OK) continue;

                        if (string.IsNullOrWhiteSpace(m_cTrnStatus.Head.FloorCd) == false)
                            lstktchItems.Add(string.Format("'{0}{1}{2}'", m_cTrnStatus.Head.FloorCd, item.SUB_SHOP_CD, item.ITEM_PLU_CD));
                        lstktchItems.Add(string.Format("'{0}{1}{2}'", "999", item.SUB_SHOP_CD, item.ITEM_PLU_CD));
                    }
                }
                if (lstktchItems.Count == 0) return false;

                // 대상상품 중 주방프린터 출력 상품 조회
                //string fmt = "SELECT A.SUB_STOR_CD, A.ITEM_CD, MAX(C.ITEM_NM) ITEM_NM, COUNT(B.KTCH_SYS_CD) KTCH_CNT \n"
                //           + "  FROM MST_KTCH_DEVICE_ITEM A WITH(NOLOCK) \n"
                //           + "     , MST_KTCH_DEVICE      B WITH(NOLOCK) \n"
                //           + "     , MST_ITEM             C WITH(NOLOCK) \n"
                //           + " WHERE A.CMP_CD = B.CMP_CD AND A.STOR_CD = B.STOR_CD \n"          // AND A.SUB_STOR_CD = B.SUB_STOR_CD AND A.KTCH_SYS_CD = B.KTCH_SYS_CD \n"
                //           + "   AND CASE WHEN A.KTCH_SYS_CD = '99' THEN 1 ELSE A.SUB_STOR_CD + A.KTCH_SYS_CD END \n"
                //           + "     = CASE WHEN A.KTCH_SYS_CD = '99' THEN 1 ELSE B.SUB_STOR_CD + B.KTCH_SYS_CD END \n"
                //           + "   AND A.CMP_CD = C.CMP_CD AND A.STOR_CD = C.STOR_CD AND A.SUB_STOR_CD = C.SUB_STOR_CD AND A.ITEM_CD = C.ITEM_CD         \n"
                //           + "   AND A.FLOOR_CD + A.SUB_STOR_CD + A.ITEM_CD IN ({2}) \n"
                //           + "   AND A.USE_YN = '{3}'                \n"
                //           + "   AND B.USE_YN = '{3}'                \n"
                //           + "   AND B.KTCH_SYS_CD <> '99'           \n"
                //           + "   AND A.CMP_CD = '{0}'                \n"
                //           + "   AND A.STOR_CD = '{1}'               \n"
                //           + " GROUP BY A.SUB_STOR_CD, A.ITEM_CD "
                //           ;
                string fmt = "SELECT A.SUB_STOR_CD, A.ITEM_CD, COUNT(B.KTCH_SYS_CD) KTCH_CNT \n"
                           + "  FROM MST_KTCH_DEVICE_ITEM A WITH(NOLOCK) \n"
                           + "     , MST_KTCH_DEVICE      B WITH(NOLOCK) \n"
                           + " WHERE A.CMP_CD = B.CMP_CD AND A.STOR_CD = B.STOR_CD \n"
                           + "   AND CASE WHEN A.KTCH_SYS_CD = '99' THEN 1 ELSE A.SUB_STOR_CD + A.KTCH_SYS_CD END \n"
                           + "     = CASE WHEN A.KTCH_SYS_CD = '99' THEN 1 ELSE B.SUB_STOR_CD + B.KTCH_SYS_CD END \n"
                           + "   AND A.CMP_CD       = '{0}'             \n"
                           + "   AND A.STOR_CD      = '{1}'             \n"
                           + "   AND A.FLOOR_CD + A.SUB_STOR_CD + A.ITEM_CD IN ({2}) \n"
                           + "   AND A.USE_YN       = '{3}'             \n"
                           + "   AND B.USE_YN       = '{3}'             \n"
                           + "   AND B.KTCH_SYS_DIV = '" + PosConst.KTCH_SYS_DIV.KPS + "' \n"
                           + "   AND B.KTCH_SYS_CD <> '99'              \n"
                           + " GROUP BY A.SUB_STOR_CD, A.ITEM_CD "
                           ;
                string sql = string.Format(fmt, m_cPosStatus.Base.CmpCd
                                              , m_cPosStatus.Base.StoreNo
                                              , string.Join(",", lstktchItems.ToArray())
                                              , PosConst.MST_USE_YN.YES);

                DataTable dt = m_cMstService.Select(new string[] { sql });

                if (dt == null || dt.Rows.Count == 0) return false;

                if (HappyOrderList != null)
                {
                    // 해피오더 일때,     해피오더는 2017.02.04 현재 구조상 복합매장 대응이 불가능 하다.
                    for (var i = 0; i < HappyOrderList.Count; i++)
                    { 
                        Column.TR_HPORD.HPORD_ITEM item = (Column.TR_HPORD.HPORD_ITEM)HappyOrderList[i];

                        var exp = string.Format("SUB_STOR_CD = '{0}' AND ITEM_CD = '{1}'", m_cPosStatus.Base.StoreNo, item.GoodsCode);
                        var dr = dt.Select(exp, "ITEM_CD ASC");
                        if (dr.Length == 0) continue;

                        var idx = -1;
                        if (string.IsNullOrWhiteSpace(m_cTrnStatus.Sale.MenualOrderValue) == false) 
                            idx = m_cTrnStatus.Sale.MenualOrderValue.IndexOf(i.ToString());

                        DataRow newRow = m_dtGridList.NewRow();
                        newRow["ITEM_CH"] = idx < 0 ? "□" : "√";        // □ √
                        newRow["SUB_STR"] = m_cPosStatus.Base.StoreNo;
                        newRow["ITEM_CD"] = item.GoodsCode.Trim();
                        newRow["ITEM_NM"] = item.GoodsName.Trim();
                        newRow["ROW_IDX"] = i.ToString();
                        m_dtGridList.Rows.Add(newRow);
                    }
                }
                else
                { 
                    // 일반주문 일때
                    ArrayList pluItems = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);
                    for (var i = 0; i < pluItems.Count; i++)
                    {
                        Column.TR_PLU.DATA item = (Column.TR_PLU.DATA)pluItems[i];

                        if (item.ORDER_OK_FLAG == PosConst.PLU_ORDER_OK_FLAG.ORDER_OK) continue;

                        //if (item.CANCEL_DIV == PosConst.CANCEL_DIV.CANCEL ||
                        //    item.CANCEL_DIV_MAIN == PosConst.CANCEL_DIV.CANCEL) continue;

                        
                        // 상품구분(0:일반, 1:세트, 2:세트자식, 3:부가상품, 4:세트할인, 5:상품권(추가))
                        string itemPluCd = item.SUBPRC_MENU_KEY_DIV == "1" ? item.SUB_MENU_MAIN_CD : item.ITEM_PLU_CD;
                        var exp = string.Format("SUB_STOR_CD = '{0}' AND ITEM_CD = '{1}'", item.SUB_SHOP_CD, itemPluCd);
                        var dr = dt.Select(exp, "ITEM_CD ASC");
                        var isPrint = dr.Length == 0 ? false : true;

                        if (isPrint)
                        {
                            var idx = -1;
                            if (string.IsNullOrWhiteSpace(m_cTrnStatus.Sale.MenualOrderValue) == false)
                                idx = m_cTrnStatus.Sale.MenualOrderValue.IndexOf(i.ToString());

                            DataRow newRow = m_dtGridList.NewRow();
                            newRow["ITEM_CH"] = idx < 0 ? "□" : "√";        // □ √
                            newRow["SUB_STR"] = item.SUB_SHOP_CD;
                            newRow["ITEM_CD"] = item.ITEM_PLU_CD;
                            newRow["ITEM_NM"] = item.ITEM_NAME;
                            newRow["ROW_IDX"] = i.ToString();
                            m_dtGridList.Rows.Add(newRow);
                        }
                    }
                }

                return gridList.CsmGridRowsCount > 0 ? true : 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 false;
            }
            finally
            {
                gridList.CsmGridDataSource = m_dtGridList;
                gridList.Focus();
                gridList.ResumeLayout();
            }
        }


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

        private void gridList_GridClickEvent(object sender, string rowIndex)
        {
            try
            {
                if ((bool)gridList.Tag == true)
                {
                    gridList.Tag = false; 
                    return;
                }

                int row = CmUtil.IntParse(rowIndex);
                if (row < 0) return;

                // □ √
                string check = m_dtGridList.Rows[row][0].ToString() == "□" ? "√" : "□";
                m_dtGridList.Rows[row][0] = check;
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                            System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                            ex.Message);
            }
        }
       
        private void Button_Click(object sender, EventArgs e)
        {
            try
            {
                if (sender == btnDn)
                {
                    gridList.Tag = true;
                    gridList.CsmGridScroll("DOWN");
                }
                else if (sender == btnUp)
                {
                    gridList.Tag = true;
                    gridList.CsmGridScroll("UP");
                }
                else if (sender == btnSelectAll)
                {
                    // □ √
                    string check = ((CsmButton)sender).Text.Substring(0, 1) == "□" ? "√" : "□";
                    btnSelectAll.Text = check + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0226);
                    foreach (DataRow dr in m_dtGridList.Rows)
                    {
                        dr["ITEM_CH"] = check; 
                    }
                }
                else if (sender == btnExit)
                {
                    this.DialogResult = DialogResult.Cancel;
                    this.Close();
                }
                else if (sender == btnEnter)
                {
                    CompleteInputValue();
                    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);
            }
        }

        private bool CompleteInputValue()
        { 
            try 
            {
                List<string> selItems = new List<string>();
                foreach (DataRow dr in m_dtGridList.Rows)
                {
                    if (dr["ITEM_CH"].ToString().Trim() == "√")
                    {
                        //var key = string.Format("{0}{1}", dr["SUB_STR"].ToString().Trim(), dr["ITEM_CD"].ToString().Trim());
                        //selItems.Add(key);
                        var rowIdx = CmUtil.GetDataRowInt(dr, "ROW_IDX");
                        selItems.Add(rowIdx.ToString());
                    }
                }

                m_cTrnStatus.Sale.MenualOrderValue = selItems.Count > 0 
                                                   ? string.Join(",", selItems.ToArray()) 
                                                   : string.Empty;
                m_cTrnStatus.Sale.MenualOrderMemo = txtMemo.Text.TrimEnd();

                return true; 
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                            System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                            ex.Message);
                return false; 
            }
        }
    }
}
