using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Runtime.InteropServices;

using Cosmos.BaseFrame;
using Cosmos.UserFrame;
using Cosmos.ServiceProvider;
using Cosmos.Common;
using Cosmos.Service;
using Cosmos.Win;
using Cosmos.CommonManager;
using System.Timers;
//using System.Threading;
using SPC.Kiosk.Common;
using SPC.Kiosk.PB.Model;
using System.Collections.ObjectModel;

namespace SPC.Kiosk.DataHelper
{
    public class PosDataService : IDisposable
    {
        #region [ Members ]
        private SManager sManager = null;                                   // 이 객체를 통해 업무 Service 호출
        private StateServer StateObject = null;                             // StateObject : StateServer Object (객체)
        private PosStatus m_cPosStatus = null;                              // 기본정보 참조
        private TranStatus m_cTrnStatus = null;                             // 거래정보 참조
        protected IDataCommonUs m_cDataCommon = null;
        private IDataProcessUs m_cDataService = null;                               // 거래데이터 합계금액 계산 및 관리




        private SaleMainProcess m_cSaleMainProc = null;                             // 판매화면 기능 관리

        /// <summary>
        /// POS 초기화 필요 유무
        /// </summary>
        public bool NeedInitModule { get; set; }
        #endregion Members


        #region [ Ctor & Dispose ]
        /// <summary>
        /// Ctor
        /// </summary>
        public PosDataService()
        {
            try
            {
                sManager = new SManager();
                StateObject = (StateServer)StateServer.GetInstance();
                if (!NeedInitModule)
                {
                    m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
                    m_cTrnStatus = (TranStatus)StateObject.TRAN;    // POS 거래정보 
                    m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);

                    m_cDataService = (IDataProcessUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_SERVICE);


                    m_cSaleMainProc = new SaleMainProcess();
                }
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "Ctor", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }


        /// <summary>
        /// Dispose
        /// </summary>
        public void Dispose()
        {
            sManager = null;                                  // 이 객체를 통해 업무 Service 호출
            StateObject = null;                               // StateObject : StateServer Object (객체)
            m_cPosStatus = null;                              // 기본정보 참조
            m_cTrnStatus = null;                              // 거래정보 참조
            m_cDataCommon = null;
        }

        public void DisposePos()
        {
            //sManager = null;
            //StateObject = null;                               // StateObject : StateServer Object (객체)

            m_cTrnStatus.Sale.Clear();
            m_cTrnStatus.Head.Clear();

            m_cDataService.InitTranHeader();
            m_cDataService.DeleteTranItem();
        }
        #endregion Ctor & Dispose


        #region [ Methods ]
        /// <summary>
        /// 점포명 조회
        /// </summary>
        /// <returns></returns>
        public string StoreName()
        {
            if (NeedInitModule) return string.Empty;
            string result = string.Empty;
            try
            {

                result = CmUtil.GetDataRowStr(PosMstManager.GetMstStore(), PosMst.MST_STORE.DATA.STORNM);
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "StoreName()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
                result = string.Empty;
            }
            return result;
        }
        public void GetCashBill(ref double _cashBill, ref double _taxbill)
        {
            _cashBill = m_cDataService.GetCashAmt();
            if (_cashBill > 0)
            {
                _taxbill = m_cDataService.GetPaymentAmtVAT(_cashBill);
            }
        }

        /// <summary>
        /// 영수증 인쇄 
        /// </summary>
        /// <param name="_bellNo">진동벨번호</param>
        /// <param name="_isTalk">알림톡유무</param>
        /// <param name="_isHappyPoint">HappyPoint 적립유무</param>
        /// <param name="_isOkCashBag">Ok CashBag 적립유무</param>
        /// <returns></returns>
        public string PrintReceipt(string _bellNo, bool _isTalk, bool _isHappyPoint, bool _isOkCashBag)
        {
            if (NeedInitModule) return string.Empty;
            string result = string.Empty; //대기번호
            var saleMain = new SaleMainProcess();
            var sRet = "";
            try
            {
                
                //var m_cTrnStatus = 

                if (_isHappyPoint)
                {
					var m_cHappyPoint = (IPaymentExpUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.POINTHAPPYPOINT);
                    Column.TR_ETC.DATA cEtcItem = (Column.TR_ETC.DATA)m_cHappyPoint.GetPayment(new string[] { });
                    ArrayList alEtcItem = (ArrayList)StateObject.GetItemObject(Column.TR_ETC.ITEM);
                    //cEtcItem.CANCEL_DIV = ItemConst.PAY_CANCEL_DIV.NORMAL;
                    //cEtcItem.AMT_ENTRY_09 = 4000d;
                    alEtcItem.Clear();
                    alEtcItem.Add(cEtcItem);
                }
				else if (_isOkCashBag)
                {
                    //var m_cPntOcbSave = (IPaymentExpUs)sManager.InitServiceInstance(ServiceLists.BSV_PAYMENT.DLL, ServiceLists.BSV_PAYMENT.PNT_OCB_SAVE)
                    //Column.TR_ETC.DATA cEtcItem = (Column.TR_ETC.DATA)m_cPntOcbSave.GetPayment(new string[] { });
                    //ArrayList alEtcItem = (ArrayList)StateObject.GetItemObject(Column.TR_ETC.ITEM);
                    ////cEtcItem.CANCEL_DIV = ItemConst.PAY_CANCEL_DIV.NORMAL;
                    ////cEtcItem.AMT_ENTRY_09 = 4000d;
                    //alEtcItem.Clear();
                    //alEtcItem.Add(cEtcItem);
                }
                //영수증 인쇄
                if (!string.IsNullOrEmpty(_bellNo))
                {
                    m_cTrnStatus.Head.OrderNo = _bellNo;
                    m_cTrnStatus.Head.IsBellUse = "1";
                }


                sRet = saleMain.CheckSaleComplete(true);
                //ISaleCompleteUs m_cSaleComplete = (ISaleCompleteUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.SALE_COMPLETE);
                //var sRet = m_cSaleComplete.PosSaleExecute(new string[] { });

                string sFilePath = BaseCom.NxCDPPath + PosConst.MST_IMG_PATH.CDP_COM + "NHS_카드_결제_완료_여_.wav";
                CmUtil.PlaySound(sFilePath);


                result = m_cTrnStatus.Head.OrderNo; //대기번호
                m_cTrnStatus.Head.OrderNo = "";


            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "PrintReceipt()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
                result = string.Empty;
            }
            finally
            {
                if (sRet.Equals(UserCom.ERROR)) DisposePos(); //에러발생 시 거래정보 초기화 에러 없으면 SaleMainProcess에서 초기화 하고 있음..2019.04.17
            }
            return result;
        }


        /// <summary>
        /// 장바구니 전체 변경
        /// </summary>
        /// <param name="_basketItems"></param>
        /// <returns></returns>
        public bool ResetItems(List<M_BasketItem> _basketItems)
        {
            if (NeedInitModule) return false;
            bool result = true;
            try
            {
                //TODO : Clear All Data





                m_cDataService.DeleteTranItem();//주문화면에서 사용한 모든 거래 데이터 삭제
                m_cDataService.InitTranHeader();//거래 정보 초기화

                m_cTrnStatus.Head.TradeDiv = ItemConst.TRAN_DIV.NORMAL;
                m_cTrnStatus.Head.TradeKind = ItemConst.TRAN_KIND.NORMAL.SALE;

                if (_basketItems is List<M_BasketItem> && _basketItems.Count > 0)
                {
                    foreach (var basketItem in _basketItems)
                    {
                        result = SetItem(basketItem);
                        if (!result) break;
                    }
                }
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "ResetItems()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
                result = false;
            }
            return result;
        }

        public bool IsExistITEM_PLU_CD(string _pluCD)
        {
            bool result = false;
            try
            {
                var saleItems = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);
                foreach (var aSaleItem in saleItems)
                {
                    if (aSaleItem is Column.TR_PLU.DATA aItem)
                    {
                        if (aItem.ITEM_PLU_CD.Equals(_pluCD))
                        {
                            result = true;
                            break;
                        }
                    }
                }
            }
            catch (Exception)
            {
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 2019-04-10 - 1997fx11 : 장바구니 아이템 추가또는 업데이트
        /// (존재하는 아이템은 업데이트 그외는 추가처리)
        /// </summary>
        /// <param name="_basketItem"></param>
        /// <returns></returns>
        public bool SetItem(M_BasketItem _basketItem)
        {
            if (NeedInitModule) return false;
            bool result = false;
            try
            {
                //Set Item Process
                string sRet = UserCom.RST_OK;
                string sSubStoreNo = "", sItemCode = "", sScanCode = "";      //    점포코드, 상품코드, 스켄코드
                string sInPutTypeCode = "", sSelRow = "", sInPutData = "";      //  (0:수입력, 1:메뉴, 2:스켄, 3:플레이버) + (메뉴코드,스캔코드), 선택행, 입력데이터

                ISalePluItemUs cPluService = (ISalePluItemUs)sManager.InitServiceInstance(ServiceLists.BSV_SALE.DLL, ServiceLists.BSV_SALE.SALE_PLU_ITEM);
                sSubStoreNo = m_cPosStatus.Base.StoreNo;                // 점포코드
                sItemCode = _basketItem.ItemCode;                           // 상품코드


                sInPutTypeCode = "1" + sSubStoreNo.PadLeft(7, '0') + sItemCode.PadLeft(9, ' ');
                //sInPutTypeCode = sSubStoreNo.PadLeft(7, '0') + sItemCode.PadLeft(9, ' ');

                if (_basketItem.Option == null)
                {
                    //sRet = cPluService.SetItemCode(sSelRow, sInPutTypeCode, _basketItem.Count.ToString());
                    result = m_cSaleMainProc.ExecuteSaleMainProcess(PosKey.MENU_KEY.REGISTER_PLU_ITEM
                                                                        , _basketItem.Count.ToString()
                                                                        , sSelRow
                                                                        , PosConst.SALE_PLU_INPUT_TYPE.MENUKEY + sInPutTypeCode.Substring(1));
                }
                else
                {
                    string sTakeInOut = "1001"; //  기본값 : Take Out.
                    string sUpCharge = "1004";  //  기본값 : 샷추가안함.

                    //foreach (var option in _basketItem.Option)
                    //{
                    //    foreach (var opt in option.Options)
                    //    {
                    //        if (opt.IsSelected)
                    //        {
                    //            if (opt.Kind == OptionKind.Button) { sTakeInOut = opt.Code; }
                    //            else if (opt.Kind == OptionKind.UpCharge) { sUpCharge = opt.Code; }
                    //        }
                    //    }
                    //}

                    //sRet = cPluService.SetItemCode(sSelRow, sInPutTypeCode, _basketItem.Count.ToString());
                    result = m_cSaleMainProc.ExecuteSaleMainProcess(PosKey.MENU_KEY.REGISTER_PLU_ITEM
                                                                        , _basketItem.Count.ToString()
                                                                        , sSelRow
                                                                        , PosConst.SALE_PLU_INPUT_TYPE.MENUKEY + sInPutTypeCode.Substring(1));

                    foreach (var option in _basketItem.Option)
                    {
                        foreach (var opt in option.Options)
                        {
                            if (opt.IsSelected)
                            {
                                ArrayList aSaleItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);
                                Column.TR_PLU.DATA cPluItem = new Column.TR_PLU.DATA();
                                DataTable dtDataInfo = new DataTable();
                                DataRow drPlu;
                                sRet = UserCom.RST_OK;

                                var findIndex = aSaleItem.Count - 1;
                                for (var i = aSaleItem.Count - 1; i > -1; i--)
                                {
                                    if (((Column.TR_PLU.DATA)aSaleItem[i]).ITEM_PLU_CD.Equals(_basketItem.ItemCode))
                                    {
                                        findIndex = i;
                                        break;
                                    }
                                }

                                switch (opt.Kind)
                                {
                                    case OptionKind.Button:



                                        dtDataInfo = m_cDataCommon.SearchNHSOption(sSubStoreNo, opt.Code);
                                        drPlu = dtDataInfo.Rows[0];

                                        cPluItem = new Column.TR_PLU.DATA();
                                        cPluItem.SUB_SHOP_CD = sSubStoreNo;
                                        cPluItem.ITEM_PLU_CD = opt.Code;
                                        cPluItem.ITEM_DIV = ItemConst.PLU_ITEM_DIV.OPT_MENU;
                                        cPluItem.SALE_QTY = _basketItem.Count;
                                        cPluItem.ITEM_NAME = ">>" + CmUtil.GetDataRowStr(drPlu, PosMst.NHS_OPTN_MST.DATA.ITEM_OPTN_NM); ;
                                        cPluItem.SUBPRC_MENU_KEY_DIV = "1";    // 부가메뉴구분(1:속성,2:업차지,3:선택메뉴)
                                        cPluItem.NONSALES_RSN_CD = "0";
                                        cPluItem.NONSALES_RSN_NM = "";
                                        cPluItem.SUB_MENU_MAIN_CD = sItemCode;

                                        aSaleItem.Add(cPluItem);                    // 등록 처리


                                        break;
                                    case OptionKind.Count:
                                        dtDataInfo = m_cDataCommon.SearchNHSOption(sSubStoreNo, opt.Code);
                                        drPlu = dtDataInfo.Rows[0];

                                        cPluItem = new Column.TR_PLU.DATA();
                                        cPluItem.SUB_SHOP_CD = sSubStoreNo;
                                        cPluItem.ITEM_PLU_CD = opt.Code;    // sItemCode;
                                        cPluItem.ITEM_DIV = ItemConst.PLU_ITEM_DIV.OPT_MENU;
                                        cPluItem.SALE_QTY = (long)opt.SelectValue;
                                        cPluItem.ITEM_NAME = ">>" + CmUtil.GetDataRowStr(drPlu, PosMst.NHS_OPTN_MST.DATA.ITEM_OPTN_NM);
                                        cPluItem.SUBPRC_MENU_KEY_DIV = "1";    // 부가메뉴구분(1:속성,2:업차지,3:선택메뉴)
                                        cPluItem.NONSALES_RSN_CD = "0";
                                        cPluItem.NONSALES_RSN_NM = "";
                                        cPluItem.SUB_MENU_MAIN_CD = sItemCode;

                                        aSaleItem.Add(cPluItem);                    // 등록 처리
                                        break;
                                    case OptionKind.Discount:
                                        ((Column.TR_PLU.DATA)aSaleItem[findIndex]).EXCEP_DC_AMT = ((opt.SelectValue < 0 ? (opt.SelectValue * (-1)) : opt.SelectValue) * _basketItem.Count);
                                        ((Column.TR_PLU.DATA)aSaleItem[findIndex]).EXCEP_DC_DIV = ((opt.SelectValue * (-1)) > 0 ? ItemConst.PLU_DC_DIV.ELOVE_DC : "0000");
                                        break;
                                    case OptionKind.UpCharge:
                                        dtDataInfo = m_cDataCommon.SearchNHSOption(sSubStoreNo, opt.Code);
                                        drPlu = dtDataInfo.Rows[0];

                                        cPluItem = new Column.TR_PLU.DATA();
                                        cPluItem.SUB_SHOP_CD = sSubStoreNo;
                                        cPluItem.ITEM_PLU_CD = opt.KindCode;
                                        cPluItem.ITEM_DIV = ItemConst.PLU_ITEM_DIV.OPT_MENU;

                                        cPluItem.SALE_QTY = _basketItem.Count;
                                        cPluItem.ITEM_NAME = ">>" + CmUtil.GetDataRowStr(drPlu, PosMst.NHS_OPTN_MST.DATA.ITEM_OPTN_NM);
                                        cPluItem.SUBPRC_MENU_KEY_DIV = "2";    // 부가메뉴구분(1:속성,2:업차지,3:선택메뉴)
                                        cPluItem.NONSALES_RSN_CD = "0";
                                        cPluItem.NONSALES_RSN_NM = "";
                                        cPluItem.SUB_MENU_MAIN_CD = sItemCode;


                                        cPluItem.SALE_PRC = CmUtil.DoubleParse(CmUtil.GetDataRowStr(drPlu, PosMst.NHS_OPTN_MST.DATA.AMT));

                                        aSaleItem.Add(cPluItem);                    // 등록 처리
                                        break;
                                }





                                //switch (opt.Kind)
                                //{
                                //    case OptionKind.Button:
                                //        if (opt.Code.Equals("1001") || opt.Code.Equals("1002"))
                                //        {
                                //            dtDataInfo = m_cDataCommon.SearchNHSOption(sSubStoreNo, opt.Code);
                                //            drPlu = dtDataInfo.Rows[0];


                                //            if (opt.Code.Equals("1001")) { ((Column.TR_PLU.DATA)aSaleItem[findIndex]).TAKE_IN_OUT_DIV = PosConst.TAKE_IN_OUT_DIV.TAKE_OUT; }
                                //            else if (opt.Code.Equals("1002")) { ((Column.TR_PLU.DATA)aSaleItem[findIndex]).TAKE_IN_OUT_DIV = PosConst.TAKE_IN_OUT_DIV.TAKE_IN; }

                                //            cPluItem = new Column.TR_PLU.DATA();
                                //            cPluItem.SUB_SHOP_CD = sSubStoreNo;
                                //            cPluItem.ITEM_PLU_CD = opt.Code;
                                //            cPluItem.ITEM_DIV = ItemConst.PLU_ITEM_DIV.OPT_MENU;
                                //            cPluItem.SALE_QTY = _basketItem.Count;
                                //            cPluItem.ITEM_NAME = ">>" + CmUtil.GetDataRowStr(drPlu, PosMst.NHS_OPTN_MST.DATA.ITEM_OPTN_NM); ;
                                //            cPluItem.SUBPRC_MENU_KEY_DIV = "1";    // 부가메뉴구분(1:속성,2:업차지,3:선택메뉴)
                                //            cPluItem.NONSALES_RSN_CD = "0";
                                //            cPluItem.NONSALES_RSN_NM = "";
                                //            cPluItem.SUB_MENU_MAIN_CD = sItemCode;
                                //            //cPluItem.PROD_TAKEINOUT_DIV = dgvPluItem.Rows[iRow].Cells[6].Value.ToString();

                                //            aSaleItem.Add(cPluItem);                    // 등록 처리
                                //        }

                                //        break;
                                //    case OptionKind.Discount:
                                //        ((Column.TR_PLU.DATA)aSaleItem[findIndex]).EXCEP_DC_AMT = ((opt.SelectValue < 0 ? (opt.SelectValue * (-1)) : opt.SelectValue) * _basketItem.Count);
                                //        ((Column.TR_PLU.DATA)aSaleItem[findIndex]).EXCEP_DC_DIV = ((opt.SelectValue * (-1)) > 0 ? ItemConst.PLU_DC_DIV.ELOVE_DC : "0000");
                                //        break;
                                //    case OptionKind.UpCharge:
                                //        dtDataInfo = m_cDataCommon.SearchItemCode(sSubStoreNo, opt.KindCode, sScanCode);
                                //        drPlu = dtDataInfo.Rows[0];

                                //        cPluItem = new Column.TR_PLU.DATA();
                                //        cPluItem.SUB_SHOP_CD = sSubStoreNo;
                                //        cPluItem.ITEM_PLU_CD = opt.KindCode;
                                //        cPluItem.ITEM_DIV = ItemConst.PLU_ITEM_DIV.OPT_MENU;
                                //        if (sTakeInOut.Equals("1001"))
                                //        {
                                //            cPluItem.SALE_PRC = CmUtil.DoubleParse(CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.TAKE_OUT_SALE_AMT));
                                //        }
                                //        else
                                //        {
                                //            cPluItem.SALE_PRC = CmUtil.DoubleParse(CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.TAKE_IN_SALE_AMT));
                                //        }
                                //        cPluItem.SALE_QTY = _basketItem.Count;
                                //        cPluItem.ITEM_NAME = ">>" + CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.ITEM_NM);
                                //        cPluItem.SUBPRC_MENU_KEY_DIV = "2";    // 부가메뉴구분(1:속성,2:업차지,3:선택메뉴)
                                //        cPluItem.NONSALES_RSN_CD = "0";
                                //        cPluItem.NONSALES_RSN_NM = "";
                                //        cPluItem.SUB_MENU_MAIN_CD = sItemCode;
                                //        //cPluItem.PROD_TAKEINOUT_DIV = dgvPluItem.Rows[iRow].Cells[6].Value.ToString();

                                //        aSaleItem.Add(cPluItem);                    // 등록 처리

                                //        break;
                                //    case OptionKind.Count:
                                //        if (opt.Code.Equals("1006") || opt.Code.Equals("1007"))
                                //        {
                                //            dtDataInfo = m_cDataCommon.SearchNHSOption(sSubStoreNo, opt.Code);
                                //            drPlu = dtDataInfo.Rows[0];

                                //            cPluItem = new Column.TR_PLU.DATA();
                                //            cPluItem.SUB_SHOP_CD = sSubStoreNo;
                                //            cPluItem.ITEM_PLU_CD = opt.Code;    // sItemCode;
                                //            cPluItem.ITEM_DIV = ItemConst.PLU_ITEM_DIV.OPT_MENU;
                                //            cPluItem.SALE_QTY = (long)opt.SelectValue;
                                //            cPluItem.ITEM_NAME = ">>" + CmUtil.GetDataRowStr(drPlu, PosMst.NHS_OPTN_MST.DATA.ITEM_OPTN_NM);
                                //            cPluItem.SUBPRC_MENU_KEY_DIV = "1";    // 부가메뉴구분(1:속성,2:업차지,3:선택메뉴)
                                //            cPluItem.NONSALES_RSN_CD = "0";
                                //            cPluItem.NONSALES_RSN_NM = "";
                                //            cPluItem.SUB_MENU_MAIN_CD = sItemCode;
                                //            //cPluItem.PROD_TAKEINOUT_DIV = dgvPluItem.Rows[iRow].Cells[6].Value.ToString();

                                //            aSaleItem.Add(cPluItem);                    // 등록 처리
                                //        }

                                //        break;
                                //    default:
                                //        break;
                                //}

                                if (sRet != UserCom.RST_OK) { break; }
                            }

                            if (sRet != UserCom.RST_OK) { break; }
                        }
                    }
                }

                //if (sRet == UserCom.RST_OK) { result = true; }
                //else { result = false; }
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "SetItem()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
                result = false;
            }
            return result;
        }


        /// <summary>
        /// 장바구니 아이템 삭제 또는 업데이트 
        /// (수량이 동일 하면 삭제 다르면 업데이트 필요)
        /// </summary>
        /// <param name="_basketItem"></param>
        /// <returns></returns>
        public bool DelItem(M_BasketItem _basketItem)
        {
            bool result = false;
            try
            {
                //TODO : Delete Item Process
                //result = m_cSaleMainProc.CancelPluItem(_basketItem.p_Index.ToString());
                
                m_cSaleMainProc.CancelPluItem("0");
                result = true;
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "DelItem()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
                result = false;
            }
            return result;
        }


        /// <summary>
        /// 장바구니옵션 변경
        /// (수량이 동일 하면 삭제 다르면 업데이트 필요)
        /// </summary>
        /// <param name="_basketItem"></param>
        /// <returns></returns>
        public bool UpdatedItem(M_BasketItem _basketItem)
        {
            bool result = false;
            try
            {
                //TODO : Delete Item Process
                result = true;
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "DelItem()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
                result = false;
            }
            return result;
        }
        #endregion Methods


        public ObservableCollection<M_BasketItem> AddItemToBasket(ObservableCollection<M_BasketItem> _targetBasket
                                                                      , int _itemCount
                                                                      , double _unitPrice
                                                                      , string _designImagesPath
                                                                      , M_ItemData _itemData
                                                                      , List<M_ItemOptionGroup> _option
                                                                      , BasketItemType _basketItemType = BasketItemType.Order)
        {
            ObservableCollection<M_BasketItem> result = null;
            try
            {
                var optionLabel = CommonFunction.GetOptionLabel(_option);
                var findSameData = _targetBasket is ObservableCollection<M_BasketItem>
                                 ? _targetBasket.Where(r => r.ItemCode.Equals(_itemData.ItemCode)
                                                    && r.AllOptionLabel.GetLanguageData(SupportLanguageType.ko).Replace("[행사]", "").Equals(optionLabel.GetLanguageData(SupportLanguageType.ko))).FirstOrDefault()

                                 : null;
                var itemIndex = 0;
                if (findSameData is M_BasketItem findedItem)
                {
                    itemIndex = findSameData.p_Index;
                    findedItem.Count += _itemCount;
                    //SetItem(findedItem);
                    //수량 증가
                    //m_cSaleMainProc.ExecuteSaleMainProcess(PosKey.MENU_KEY.QTY_PLUS, "", itemIndex.ToString(), "");
                }
                else
                {
                    var newBasketData = _targetBasket is ObservableCollection<M_BasketItem>
                                      ? _targetBasket.ToList()
                                      : new List<M_BasketItem>();
                    //foreach (var aitem in newBasketData)
                    //{
                    //    aitem.Index += 1;
                    //}
                    //var pIdx = 0;
                    //if (newBasketData.Count != 0) pIdx++;
                    itemIndex = newBasketData.Count.Equals(0)
                                  ? 0
                                  : newBasketData.Max(r => r.p_Index) + 1;



                    var newBasketItem = new M_BasketItem
                    {
                        Index = 0,
                        p_Index = itemIndex,
                        ItemType = _basketItemType,
                        ItemCode = _itemData.ItemCode,
                        ItemImage = _itemData.DataParameter.NormalBrush,
                        ItemName = _itemData.BaseTextBlock.LanguageData,
                        AllOptionLabel = optionLabel,
                        Option = _option,
                        Count = _itemCount,
                        BasePrice = _itemData.Price,
                        Price = _unitPrice,
                        ItemCountLabel = new List<M_Language>
                    {
                        new M_Language {Type=SupportLanguageType.ko,LanguageData=@"개"},
                        new M_Language {Type=SupportLanguageType.en,LanguageData=@"EA"}
                    },
                        ItemPriceLabel = new List<M_Language>
                    {
                        new M_Language {Type=SupportLanguageType.ko,LanguageData=@"\"}
                    },
                        MinusNormalBrush = ResourceManager.GetNximagePathAdd("btn_count_minus_n.png", _designImagesPath),
                        MinusDownBrush = ResourceManager.GetNximagePathAdd("btn_count_minus_p.png", _designImagesPath),
                        PlusNormalBrush = ResourceManager.GetNximagePathAdd("btn_count_plus_n.png", _designImagesPath),
                        PlusDownBrush = ResourceManager.GetNximagePathAdd("btn_count_plus_p.png", _designImagesPath)

                    };

                    //SetItem(newBasketItem);
                    //var saleItems = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);

                    //foreach(var aItems in saleItems)
                    //{
                    //    if(((Column.TR_PLU.DATA)aItems).CPI_DC_AMT > 0)
                    //    {
                    //        newBasketItem.Price = newBasketItem.Price - ((Column.TR_PLU.DATA)aItems).CPI_DC_AMT;
                    //    }
                    //}

                    //상품등록 처리(POS)
                    m_cPosStatus.Sale.SaleFlow = PosConst.SALE_FLOW.SALE_WAIT; //판매대기
                    ISalePluItemUs cPluService = (ISalePluItemUs)sManager.InitServiceInstance(ServiceLists.BSV_SALE.DLL, ServiceLists.BSV_SALE.SALE_PLU_ITEM);
                    var sSubStoreNo = m_cPosStatus.Base.StoreNo;                // 점포코드
                    var sItemCode = newBasketItem.ItemCode;                           // 상품코드
                    var sMenuCode = "1" + sSubStoreNo.PadLeft(7, '0') + sItemCode.PadLeft(9, ' ');
                    //bool bRet = m_cSaleMainProc.ExecuteSaleMainProcess(PosKey.MENU_KEY.REGISTER_PLU_ITEM, sInPutValue, "", PosConst.SALE_PLU_INPUT_TYPE.MENUKEY + sMenuCode.Substring(1));
                    bool bRet = m_cSaleMainProc.ExecuteSaleMainProcess(PosKey.MENU_KEY.REGISTER_PLU_ITEM, "", itemIndex.ToString(), PosConst.SALE_PLU_INPUT_TYPE.MENUKEY + sMenuCode.Substring(1));






                    //var nStat = cPluService.SetItemCode(itemIndex.ToString(), PosConst.SALE_PLU_INPUT_TYPE.MENUKEY, m_cPosStatus.Base.StoreNo, newBasketItem.ItemCode, "", newBasketItem.Count.ToString());
                    if (bRet)
                    {
                        itemIndex = 0;
                        var saleItems = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);
                        if (((Column.TR_PLU.DATA)saleItems[itemIndex]).CPI_DC_AMT > 0)
                        {
                            newBasketItem.CampaignPrice = ((Column.TR_PLU.DATA)saleItems[itemIndex]).CPI_DC_AMT;
                            newBasketItem.Price = _itemData.Price - newBasketItem.CampaignPrice;
                            var addOptionLabel = new List<M_Language>
                                                {
                                                    new M_Language {Type=SupportLanguageType.ko,LanguageData=@"[행사]"},
                                                    new M_Language {Type=SupportLanguageType.en,LanguageData=@"[EVENT]"}
                                                };

                            newBasketItem.AllOptionLabel = optionLabel is List<M_Language>
                                          ? Languages.CombineLanguageData(addOptionLabel, optionLabel)
                                          : addOptionLabel;
                        }

                        newBasketData.Insert(0, newBasketItem);

                        DelItem(newBasketItem);
                    }
                    else
                    {
                        CommonLog.ErrorLogWrite(this, "AddItemToBasket()", "Fail !!", string.Format("\nItemCode={0}", newBasketItem.ItemCode));
                    }
                    //if (bRet == true)
                    //    newBasketData.Insert(0, newBasketItem);



                    result = new ObservableCollection<M_BasketItem>(newBasketData);
                }
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "AddItemToBasket()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
                result = null;
            }
            return result;
        }
		
		/// <summary>
        /// 바코드 데이터 초기화
        /// </summary>
        public void LastBarcodeDelete()
        {
            m_cPosStatus.Base.LastRcptBarcodeData = string.Empty;
        }
        
    }
}