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>
    /// 주방프린터 수동출력 (장치선택, OPT425 = "1")
    /// </summary>
    /// <remarks>
    /// 업무요건 
    /// 1. 주방프린터 사용시      (OPT506 = "1")
    /// 2. 주방프린터 수동출력 시 (OPT425 = "1")
    /// 3. 주방프린터 장치 설정이 존재 할때
    /// 4. 주문 사품 중 주방프린터 출력 상품이 존재 할 때 
    /// 5. AS-IS POS 시스템에서는 베스킨/던킨 에서만 사용하는 기능 
    /// 
    /// 6. 선택한 장치에 연계된 출력대상상품 만 출력. 
    /// 7. 전체일 때는 "99" 장치코드에 연계된 상품을 매장에 출력가능한 모든 주방프린터로 출력 
    /// </remarks>
    public partial class frmMenualOrderKps : 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;                                     // 마스터 서비스 
        private ITableUs m_cTableService = null;                                    // 테이블 서비스  

        /// <summary>
        /// 주방프린터 버튼 목록 
        /// </summary>
        private List<CsmButton> lstKtchButton = new List<CsmButton>();
        /// <summary>
        /// 주방프린터 목록 
        /// </summary>
        private List<KtchDevice> lstKtchDevices = new List<KtchDevice>();
        /// <summary>
        /// 주방프린터 정보 
        /// </summary>
        private class KtchDevice
        {
            public string subShop = string.Empty; 
            public string SysCode = string.Empty;
            public string SysName = string.Empty;
            public int    LinkItemCount = 0;
        }

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

        /// <summary>
        /// 생성자  
        /// </summary>
        public frmMenualOrderKps()
        {
            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);
            m_cTableService = (ITableUs)sManager.InitServiceInstance(ServiceLists.BSV_TABLE.DLL, ServiceLists.BSV_TABLE.TABLE_SERVICE);

            // 장치버튼 리스트 
            lstKtchButton.Add(btnPrt00);
            lstKtchButton.Add(btnPrt01);
            lstKtchButton.Add(btnPrt02);
            lstKtchButton.Add(btnPrt03);
            lstKtchButton.Add(btnPrt04);
            lstKtchButton.Add(btnPrt05);
            lstKtchButton.Add(btnPrt06);
            lstKtchButton.Add(btnPrt07);
            lstKtchButton.Add(btnPrt08);
            lstKtchButton.Add(btnPrt09);
        }

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

                if (DisplayKtchButton() == false)
                {
                    UserLog.WriteLogFile(UserCom.LOG_IOS, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                              System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                              System.Reflection.MethodBase.GetCurrentMethod().Name + "()", "Close Abort");

                    this.DialogResult = System.Windows.Forms.DialogResult.Abort;
                    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 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);

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

                lblTitle.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0972);
                lblGuideMsg.Text = MessageManager.GetGuideMessage(POS_MESSAGE.GUIDE.MSG_0010);

                btnPrtAll.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0226);
                btnPrtAll.Tag = "99";

                btnPrtNo.Text = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0973);
            }
            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 DisplayKtchButton()
        {
            try
            {
                lstKtchDevices.Clear();

                // 주방프린트 사용(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) != "1") 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.KTCH_SYS_CD, MAX(A.KTCH_SYS_NM) AS KTCH_SYS_NM, COUNT(B.ITEM_CD) AS ITEMCNT \n"
                           + "  FROM MST_KTCH_DEVICE           A WITH(NOLOCK) \n"
                           + "  LEFT JOIN MST_KTCH_DEVICE_ITEM B WITH(NOLOCK) \n"
                           + "    ON A.CMP_CD      = B.CMP_CD      \n"
                           + "   AND A.STOR_CD     = B.STOR_CD     \n"
                           + "   AND CASE WHEN B.KTCH_SYS_CD = '99' THEN 1 ELSE A.SUB_STOR_CD END \n"
                           + "     = CASE WHEN B.KTCH_SYS_CD = '99' THEN 1 ELSE B.SUB_STOR_CD END \n"
                           + "   AND CASE WHEN B.KTCH_SYS_CD = '99' THEN 1 ELSE A.KTCH_SYS_CD END \n"
                           + "     = CASE WHEN B.KTCH_SYS_CD = '99' THEN 1 ELSE B.KTCH_SYS_CD END \n"
                           + "   AND A.USE_YN       = '{3}'         \n"
                           + "   AND B.USE_YN       = '{3}'         \n"
                           + "   AND B.FLOOR_CD + B.SUB_STOR_CD + B.ITEM_CD IN ({2}) \n"
                           + " WHERE A.CMP_CD       = '{0}'         \n"
                           + "   AND A.STOR_CD      = '{1}'         \n"
                           + "   AND A.KTCH_SYS_CD  <> '99'         \n"
                           + "   AND A.KTCH_SYS_DIV = '" + PosConst.KTCH_SYS_DIV.KPS + "' \n"
                           + " GROUP BY A.SUB_STOR_CD, A.KTCH_SYS_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;
                foreach (DataRow dr in dt.Rows)
                {
                    KtchDevice device = new KtchDevice();
                    device.subShop = CmUtil.GetDataRowStr(dr, "SUB_STOR_CD").Trim();
                    device.SysCode = CmUtil.GetDataRowStr(dr, "KTCH_SYS_CD").Trim();
                    device.SysName = CmUtil.GetDataRowStr(dr, "KTCH_SYS_NM").Trim();
                    device.LinkItemCount = CmUtil.GetDataRowInt(dr, "ITEMCNT");

                    lstKtchDevices.Add(device);
                }

                // 장치에 연계된 상품이 없으면, 종료
                int itemSum = lstKtchDevices.Sum(x => x.LinkItemCount);
                if (itemSum == 0) return false; 

                // 장치버튼 초기화 
                for (var i = 0; i < lstKtchButton.Count; i++)
                {
                    lstKtchButton[i].Text = string.Empty;       // name
                    lstKtchButton[i].Tag = string.Empty;        // code
                    lstKtchButton[i].Visible = false;
                }
                btnPrtAll.BackColor = Color.FromArgb(101, 115, 126);
                btnPrtAll.ForeColor = Color.White;
                btnPrtAll.Enabled = true; 

                // 장치버튼 화면표시 
                int idx = 0;
                foreach (KtchDevice d in lstKtchDevices)
                {
                    CsmButton btn = null; 

                    if (d.SysCode == "99") continue;

                    if (idx >= lstKtchButton.Count) continue;
                    btn = lstKtchButton[idx];
                    idx++;
                    btn.Tag = d.subShop + d.SysCode;
                    btn.Text = d.SysName;
                    btn.BackColor = d.LinkItemCount > 0 ? Color.FromArgb(101, 115, 126) : Color.FromArgb(219, 219, 219);
                    btn.ForeColor = d.LinkItemCount > 0 ? Color.White : Color.DarkGray;
                    btn.Enabled = d.LinkItemCount > 0 ? true : false;
                    btn.Visible = true;
                }

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

        private void btnExit_Click(object sender, EventArgs e)
        {
            try
            {
                // 출력안함
                btnKtchDevice_Click(btnPrtNo, 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);
            }
        }

        private void btnKtchDevice_Click(object sender, EventArgs e)
        {
            try
            {
                m_cTrnStatus.Sale.MenualOrderValue = string.Empty;


                // 출력안함.
                if (sender == btnPrtNo)
                {
                    m_cTrnStatus.Sale.MenualOrderValue = "NOPRINT";
                    this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
                    this.Close();
                    return; 
                }
                // 전체 
                if (sender == btnPrtAll)
                {
                    m_cTrnStatus.Sale.MenualOrderValue = "99";
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    this.Close();
                    return;
                }

                string code = ((CsmButton)sender).Tag.ToString().Trim();
                if (string.IsNullOrWhiteSpace(code)) return; 

                KtchDevice d = lstKtchDevices.Single(x => x.subShop + x.SysCode == code);
                if (d.LinkItemCount == 0) return;

                m_cTrnStatus.Sale.MenualOrderValue = code;
                this.DialogResult = System.Windows.Forms.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);
            }
        }
    }
}
