using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Newtonsoft.Json;

using Cosmos.UserFrame;
using Cosmos.BaseFrame;
using Cosmos.ServiceProvider;
using Cosmos.Common;
using Cosmos.CommonManager;
using System.Data;
using System.Globalization;

using System.Windows.Forms;

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 해피오더 내역 조회
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Service
{
    class HappyOrderList : IHappyOrderList
    {
        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 INetworkHttp m_cNetworkHttp = null;
        private ISaleCompleteUs m_cRecService = null;
        private ISalePluItemUs m_cPluService = null;                                // 판매 등록 관리
        private IDatabaseSQL m_cSqlDbService = null;
        private IDataCommonUs m_cDataCommon = null;                                 // POS 공통함수 인터페이스

        private static ArrayList m_sPrintData = new ArrayList();

        /// <summary>
        /// 생성자
        /// </summary>
        public HappyOrderList()
        {
            m_cPosStatus = (PosStatus)StateObject.POS;
            m_cTrnStatus = (TranStatus)StateObject.TRAN;

            m_cNetworkHttp = (INetworkHttp)sManager.InitServiceInstance(ServiceLists.AGENT_NETWORK.DLL, ServiceLists.AGENT_NETWORK.NETWORK_HTTP);
            m_cRecService = (ISaleCompleteUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.SALE_COMPLETE);
            m_cPluService = (ISalePluItemUs)sManager.InitServiceInstance(ServiceLists.BSV_SALE.DLL, ServiceLists.BSV_SALE.SALE_PLU_ITEM);
            m_cSqlDbService = (IDatabaseSQL)sManager.InitServiceInstance(ServiceLists.AGENT_DATABASE.DLL, ServiceLists.AGENT_DATABASE.DATABASE_MSSQL);
            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
        }

        /// <summary>
        /// 해피오더 내역조회 데이터 파싱 처리
        /// </summary>
        /// <param name="htData"></param>
        /// <returns></returns>
        public Column.TR_HPORD.HPORD_HEADER ParseHappyOrderList(Hashtable htData)
        {
            Column.TR_HPORD.HPORD_HEADER header = null;

            try
            {
                header = new Column.TR_HPORD.HPORD_HEADER();

                header.OrderNum = htData["orderNum"].ToString();
                header.OrderPgNum = htData["orderPgNum"] == null ? string.Empty : htData["orderPgNum"].ToString();
                header.OwnerName = htData["ownerName"] == null ? string.Empty : htData["ownerName"].ToString();
                header.OrderMoney = htData["orderMoney"] == null ? string.Empty : htData["orderMoney"].ToString();
                
                // 해피포인트 사용 금액 추가(2017.05.17/조충연K)
                //header.PayMoney = htData["payMoney"] == null ? string.Empty : htData["payMoney"].ToString();
                string sPayMoney = htData["payMoney"] == null ? string.Empty : htData["payMoney"].ToString();
                header.HappyUseMoney = htData["happyUseMoney"] == null ? string.Empty : htData["happyUseMoney"].ToString();
                header.PayMoney = Convert.ToString(CmUtil.DoubleAdd(CmUtil.DoubleParse(sPayMoney), CmUtil.DoubleParse(header.HappyUseMoney)));
                
                header.Receiver = htData["receiver"] == null ? string.Empty : htData["receiver"].ToString();
                header.ReceiverHp = htData["receiverHp"] == null ? string.Empty : htData["receiverHp"].ToString();
                header.OrderDate = htData["orderDate"] == null ? string.Empty : htData["orderDate"].ToString();
                header.PayStatus = htData["payStatus"] == null ? string.Empty : htData["payStatus"].ToString();
                if(header.PayStatus == "5")
                {
                    // 현장결제 Flag Set
                    header.FieldPay = "Y";
                }
                else
                {
                    header.FieldPay = "N";
                }
                header.OrderStatus = htData["status"] == null ? string.Empty : htData["status"].ToString();
                header.PickupTime = htData["pickupTime"] == null ? string.Empty : htData["pickupTime"].ToString();
                header.OrderType = htData["type"] == null ? string.Empty : htData["type"].ToString();
                header.CashSupplyPrice = htData["cashReceiptSupplyPrice"] == null ? string.Empty : htData["cashReceiptSupplyPrice"].ToString();
                header.CashSurTax = htData["cashReceiptSurTax"] == null ? string.Empty : htData["cashReceiptSurTax"].ToString();
                header.CustMsg = htData["msg"] == null ? string.Empty : htData["msg"].ToString();
                header.DeliveryName = htData["deliName"] == null ? string.Empty : htData["deliName"].ToString();
                header.DeliveryHp = htData["deliPhone"] == null ? string.Empty : htData["deliPhone"].ToString();
                header.OwnerId = htData["ownerId"] == null ? string.Empty : htData["ownerId"].ToString();              //#10906_[BR] 요기요 해피오더 매출 처리 기능 개발_hs 해피오더 파싱처리
                header.Channel = htData["channel"] == null ? string.Empty : htData["channel"].ToString();              //#11078_[공통] 해피오더 외부채널 표시 방식 변경 적용 요청_hs
                header.ChannelName = htData["channelName"] == null ? string.Empty : htData["channelName"].ToString();  //#11078_[공통] 해피오더 외부채널 표시 방식 변경 적용 요청_hs
                header.DailyCode = htData["dailyCode"] == null ? string.Empty : htData["dailyCode"].ToString();//17.08.22 dkshin SS 해피오더

                //grayber@20180201 해피오더 고객정보 추가 + 원산지 표기 #13780 start
                header.Address1 = htData["address1"] == null ? string.Empty : htData["address1"].ToString();
                header.Address2 = htData["address2"] == null ? string.Empty : htData["address2"].ToString();
                //grayber@20180201 해피오더 고객정보 추가 + 원산지 표기 #13780 end

                //#20180612 해피오더 주문알림 start
                header.immediateOrder = htData["immediateOrder"] == null ? string.Empty : htData["immediateOrder"].ToString();
                //#20180612 해피오더 주문알림 end

                if (header.OrderType != "1")
                {
                    //#17397 해피오더)픽업/배달 잔여 일수 표기 확인 start
                    #region 기존소스
                    /*
                    DateTime dtToday = DateTime.Now;
                    DateTime dtDecisionDay = new DateTime(int.Parse(header.PickupTime.Substring(0, 4)),
                                                          int.Parse(header.PickupTime.Substring(5, 2)),
                                                          int.Parse(header.PickupTime.Substring(8, 2)),
                                                          int.Parse(header.PickupTime.Substring(14, 2)),
                                                          int.Parse(header.PickupTime.Substring(17, 2)),
                                                          0);

                    int iDDay = (int)((dtToday - dtDecisionDay).TotalDays);
                    if (iDDay > 0)
                    {
                        header.DDay = "D+" + string.Format("{0:00}", iDDay);
                    }
                    else if (iDDay == 0)
                    {
                        int iDHOur = (int)(dtToday - dtDecisionDay).TotalHours;
                        if (iDHOur > 0)
                        {
                            header.DDay = "H+" + string.Format("{0:00}", iDHOur);
                        }
                        else if (iDHOur == 0)
                        {
                            header.DDay = "H-" + string.Format("{0:00}", iDHOur);
                        }
                        else
                        {
                            header.DDay = "H" + string.Format("{0:00}", iDHOur);
                        }
                    }
                    else
                    {
                        header.DDay = "D" + string.Format("{0:00}", iDDay);
                    }
                    */
                    #endregion

                    #region 변경소스
                  
                    string StartDate = "";
                    string EndDate = "";
                    StartDate = DateTime.Now.ToString("yyyy-MM-dd");
                    EndDate = header.PickupTime.Substring(0, 4).Trim() + "-" +
                              header.PickupTime.Substring(5, 2).Trim() + "-" +
                              header.PickupTime.Substring(8, 2).Trim() ;
                    DateTime dtStartDate = Convert.ToDateTime(StartDate);
                    DateTime dtEndDate = Convert.ToDateTime(EndDate);
                    TimeSpan dateDiff = dtEndDate - dtStartDate;
                    int diffDay = dateDiff.Days;
                    diffDay = diffDay * -1;

                    string StartTime = "";
                    string EndTime = "";
                    StartTime = DateTime.Now.ToString("HH:mm:ss");
                    EndTime = header.PickupTime.Substring(14, 2).Trim() + ":" +
                              header.PickupTime.Substring(17, 2).Trim() + ":" +
                              "00";
                    DateTime dtStartTime = Convert.ToDateTime(StartTime);
                    DateTime dtEndTime = Convert.ToDateTime(EndTime);
                    TimeSpan TimeDiff = dtEndTime - dtStartTime;
                    int diffHour = TimeDiff.Hours;
                    diffHour = diffHour * -1;

                    if (diffDay > 0)
                    {
                        header.DDay = "D+" + string.Format("{0:00}", diffDay);
                    }
                    else if (diffDay == 0)
                    {
                        if (diffHour > 0)
                        {
                            header.DDay = "H+" + string.Format("{0:00}", diffHour);
                        }
                        else if (diffHour == 0)
                        {
                            header.DDay = "H-" + string.Format("{0:00}", diffHour);
                        }
                        else
                        {
                            header.DDay = "H" + string.Format("{0:00}", diffHour);
                        }
                    }
                    else
                    {
                        header.DDay = "D" + string.Format("{0:00}", diffDay);
                    }
                    
                    #endregion
                    //#17397 해피오더)픽업/배달 잔여 일수 표기 확인 end
                }
                else
                {
                    header.DDay = MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0946);
                }
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

            return header;
        }
        
        //grayber20180201 해피오더 고객정보 추가 + 원산지 표기 #13780 start
        public void  GetHappyOrderNurtitionListDetail(string sOrderNum, string sUrl, string sOrderDt )
        {
            try
            {
                Hashtable htRequest = new Hashtable();
                htRequest.Add("orderNum", sOrderNum);

                Hashtable htResponse = null;
                int iReturn = BaseCom.NG;
                Hashtable[] htOrderNutritionLists = SendReceiveForHappyOrder(new object[] { sUrl, ItemConst.HAPPYORDER_WORK_TYPE.SELECT_PRODUCT_NUTRITION, htRequest }, ref htResponse, ref iReturn);

                //grayber@20180202 [BR]해피오더 고객정보 추가 + 원산지 표기 start - 기존 영양정보 관련 함수로 대체
                //string sTextBuf = string.Empty, sTextCont = string.Empty, sKey = string.Empty;
                //foreach (Hashtable htData in htOrderNutritionLists)
                //{
                //    //sTextBuf = htData["infoType"] == null ? string.Empty : htData["infoType"].ToString();cHappyNurtitionOrderItem.Add(sTextBuf);
                //    //sTextBuf = htData["goodsCode"] == null ? string.Empty : htData["goodsCode"].ToString();cHappyNurtitionOrderItem.Add(sTextBuf);
                //    sTextBuf = "-상품명 : " + (htData["goodsName"] == null ? string.Empty : htData["goodsName"].ToString()); cHappyNurtitionOrderItem.Add(sTextBuf);

                //    for (var nContent = 0; ((htData.Count - 3) / 2) + 1 > nContent; nContent++)
                //    {
                //        sKey = "text" + (nContent + 1).ToString();
                //        sTextBuf = htData[sKey] == null ? string.Empty : htData[sKey].ToString();
                //        sKey = "content" + (nContent + 1).ToString();
                //        sTextCont = htData[sKey] == null ? string.Empty : htData[sKey].ToString();
                //        if (sTextBuf.Equals(string.Empty) != true && sTextCont.Equals(string.Empty) != true)
                //        {
                //            cHappyNurtitionOrderItem.Add(/*"-" +*/ sTextBuf + " : " + sTextCont);
                //        }
                //    }
                //}

                string sMsg = ParseNutritionMsg(htOrderNutritionLists);
                if (sMsg != "")
                {
                    UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                             System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                             System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                             System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                             "OrderNum = " + sOrderNum + ", 영양정보 = " + sMsg);

                    // 영양정보 저장
                    UpdateHappyOrderData(new string[] { "Message", sMsg, sOrderNum, sOrderDt });
                }
                //grayber@20180202 [BR]해피오더 고객정보 추가 + 원산지 표기 end
            }
            catch(Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
            return;
        }
        //grayber20180201 해피오더 고객정보 추가 + 원산지 표기 #13780 end

        /// <summary>
        /// 해피오더 상세내역 조회
        /// </summary>
        /// <param name="sOrderNum"></param>
        /// <param name="sUrl"></param>
        /// <param name="cHappyOrderItem"></param>
        /// <param name="htOrderLists"></param>
        public void GetHappyOrderListDetail(string sOrderNum, string sUrl, ref ArrayList cHappyOrderItem , ref Hashtable[] htOrderLists)
        {
            try
            {
                Hashtable htRequest = new Hashtable();
                htRequest.Add("orderNum", sOrderNum);
                htRequest.Add("deviceType", "POS");

                Hashtable htResponse = null;
                int iReturn = BaseCom.NG;
                htOrderLists = SendReceiveForHappyOrder(new object[] { sUrl, ItemConst.HAPPYORDER_WORK_TYPE.SELECT_ORDER_DETAIL, htRequest }, ref htResponse, ref iReturn);

                //#15746 해피오더 '쇼킹박스' 관련 POS 시스템 개발 요청 start
                //IDataCommonUs m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
                //#15746 해피오더 '쇼킹박스' 관련 POS 시스템 개발 요청 end

                cHappyOrderItem.Clear();

                for (int nLoop = 0; nLoop < htOrderLists.Length; nLoop++)
                {
                    Hashtable htData = htOrderLists[nLoop];

                    Column.TR_HPORD.HPORD_ITEM item = new Column.TR_HPORD.HPORD_ITEM();
                    item.OrderNum = htData["orderSubNum"].ToString();
                    item.OrderSeq = Convert.ToString(cHappyOrderItem.Count + 1);
                    item.GoodsCode = htData["posGoodsCode"].ToString();
                    item.GoodsName = htData["goodsName"].ToString();
                    item.SupplyPrice = htData["supplyPrice"].ToString();
                    // 할인금액은 절대값 처리
                    item.DiscountPrice = Math.Abs(Convert.ToInt64(htData["discountPrice"].ToString())).ToString();
                    item.CashTotSupplyPrice = htData["cashReceiptTotSupplyPrice"].ToString();
                    item.CashTotSurTax = htData["cashReceiptTotSurTax"].ToString();
                    item.Qty = htData["ea"].ToString();
                    item.SalePrice = htData["salePrice"].ToString();
                    item.FlavourFlag = "N";
                    item.FlavourName = "";
                    //17.08.22 dkshin SS 해피오더
                    if (htData["dailyCode"] != null)
                    {
                        item.DailyCode = htData["dailyCode"].ToString();
                    }
                    else
                    {
                        item.DailyCode = "";
                    }

                    cHappyOrderItem.Add(item);

                    Hashtable[] htGoodsOptionList = ParseJsonString(htData["goodsOptionList"].ToString());

                    foreach (Hashtable htGoodsOption in htGoodsOptionList)
                    {
                        Hashtable[] htGoodsOptionGoodsList;
                        string sPosType = htGoodsOption["posType"].ToString();
                        if (int.Parse(sPosType) > 0)
                        {
                            htGoodsOptionGoodsList = ParseJsonString(htGoodsOption["goodsOptionGoodsList"].ToString());

                            foreach (Hashtable htGoodsOptionGoods in htGoodsOptionGoodsList)
                            {
                                Column.TR_HPORD.HPORD_ITEM subItem = new Column.TR_HPORD.HPORD_ITEM();
                                subItem.OrderNum = item.OrderNum;
                                subItem.OrderSeq = htGoodsOptionGoods["goodsOptionSeq"].ToString();
                                subItem.GoodsCode = CmUtil.IsNull((String)htGoodsOptionGoods["posGoodsCode"], "0");
                                subItem.GoodsName = htGoodsOptionGoods["goodsName"].ToString();
                                subItem.SalePrice = htGoodsOptionGoods["salePrice"].ToString();
                                subItem.SupplyPrice = htGoodsOptionGoods["salePrice"].ToString();
                                // 할인금액은 절대값 처리
                                //subItem.DiscountPrice = htGoodsOptionGoods["discountPrice"].ToString();
                                subItem.DiscountPrice = Math.Abs(Convert.ToInt64(htGoodsOptionGoods["discountPrice"].ToString())).ToString();
                                subItem.Qty = htGoodsOptionGoods["ea"].ToString();
                                int iIdx = (subItem.GoodsName).IndexOf(']');
                                StringInfo si = new StringInfo((subItem.GoodsName).Substring(iIdx + 1).Trim());
                                if (si.LengthInTextElements > 3)
                                {
                                    subItem.FlavourName = si.SubstringByTextElements(0, 3);
                                }
                                else
                                {
                                    subItem.FlavourName = si.String;
                                }
                                if (subItem.GoodsCode != "0" && subItem.GoodsCode != "")
                                {
                                    subItem.FlavourFlag = "Y";
                                }

                                cHappyOrderItem.Add(subItem);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
        }

        /// <summary>
        /// 영수증 출력데이터 생성
        /// </summary>
        /// <param name="sPrtHead">출력형태</param>
        /// <param name="sPrtFmt">출력포맷</param>
        /// <param name="sData">Data</param>
        public void AddPrintData(string sPrtHead, string sPrtFmt, string sData)
        {
            try
            {
                string sPrtData = "";
                if (sPrtFmt == PosConst.PRT_FMT.F100)               // 선귿기
                {
                    for (int i = 1; i <= 42; i++) sPrtData += sData;
                }
                else if (sPrtFmt == PosConst.PRT_FMT.F101)          // 왼쪽정렬
                {
                    sPrtData = sData;
                }
                else if (sPrtFmt == PosConst.PRT_FMT.F102)          // 오른쪽 정렬
                {
                    sPrtData = CmUtil.LPadH(sData, 42);
                }
                else if (sPrtFmt == PosConst.PRT_FMT.F103)          // 중앙정렬
                {
                    if (sPrtHead == PosConst.PRT_HDR.PRT_HOR || sPrtHead == PosConst.PRT_HDR.PRT_BIG)
                    {
                        if (CmUtil.LenH(sData) <= 21) sPrtData = CmUtil.LPadH("", 10 - (CmUtil.LenH(sData) / 2)) + sData;
                    }
                    else
                    {
                        if (CmUtil.LenH(sData) <= 42) sPrtData = CmUtil.LPadH("", 21 - (CmUtil.LenH(sData) / 2)) + sData;
                    }
                }
                else
                {
                    sPrtData = sData;
                }

                m_sPrintData.Add(sPrtHead + sPrtData);
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
        }

        /// <summary>
        /// 영수증 출력데이터 생성
        /// </summary>
        /// <param name="sPrtHead"></param>
        /// <param name="sPrtFmt"></param>
        /// <param name="sData1"></param>
        /// <param name="sData2"></param>
        public void AddPrintData(string sPrtHead, string sPrtFmt, string sData1, string sData2)
        {
            try
            {
                string sPrtData = "";
                if (sPrtFmt == PosConst.PRT_FMT.F200)               // 명(31)+금액(11)
                {
                    if (sPrtHead == PosConst.PRT_HDR.PRT_HOR || sPrtHead == PosConst.PRT_HDR.PRT_BIG)
                    {
                        sPrtData = CmUtil.RPadH(sData1, 10) + CmUtil.LPadH(sData2, 11);
                    }
                    else
                    {
                        sPrtData = CmUtil.RPadH(sData1, 31) + CmUtil.LPadH(sData2, 11);
                    }
                }
                if (sPrtFmt == PosConst.PRT_FMT.F201)               // 명(31)+금액(11)
                {
                    if (sPrtHead == PosConst.PRT_HDR.PRT_HOR || sPrtHead == PosConst.PRT_HDR.PRT_BIG)
                    {
                        sPrtData = CmUtil.LPadH(sData1, 10) + CmUtil.LPadH(sData2, 11);
                    }
                    else
                    {
                        sPrtData = CmUtil.LPadH(sData1, 31) + CmUtil.LPadH(sData2, 11);
                    }

                }

                m_sPrintData.Add(sPrtHead + sPrtData);
            }
            catch(Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
        }

        /// <summary>
        /// 영수증 버퍼 초기화
        /// </summary>
        public void PrintBufClear()
        {
            m_sPrintData.Clear();
        }

        /// <summary>
        /// 영수증 버퍼 반환
        /// </summary>
        /// <returns></returns>
        public ArrayList GetPrintBufferData()
        {
            return m_sPrintData;
        }

        /// <summary>
        /// 주방프린터 상품 처리
        /// </summary>
        /// <param name="alHappyOrderItem"></param>
        public void KPSItemProc(string sTradeDiv, ArrayList alHappyOrderItem)
        {
            string sSelQuery = "";
            string sInsQuery = "";
            string sSQL = "";
            int iRet = UserCom.NG;
            int iSeq = 0;
            DataTable dtReturn = null;

            try
            {
                // 주방출력사용 옵션 
                if (PosMstManager.GetPosOption(POS_OPTION.OPT506) != "1") return;

                sSelQuery  = " SELECT ISNULL(MAX(SEQ), 0) + 1 AS NEXT_SEQ ";
                sSelQuery += "   FROM POSMST..MST_KTCH_ORD_MSG ";
                sSelQuery += "  WHERE TRAIN_MODE_YN = '{0}' ";                                                          // Add, 2017.03.06, 주방출력 연습모드 적용
                sSelQuery += "    AND ORD_DIV       = '{1}' ";
                sSelQuery += "    AND FLOOR_CD      = '{2}' ";
                sSelQuery += "    AND TBL_NO        = '{3}' ";


                #region (주석) 복합매장 적용 이전
                //sInsQuery  = " INSERT INTO POSMST..MST_KTCH_ORD_MSG ";
                //sInsQuery += "        ( ORD_DIV, FLOOR_CD, TBL_NO, SEQ, CMP_CD, BRAND_CD, STOR_CD, POS_NO, TRADE_NO, SALE_DT, POS_TYPE, ITEM_CD, ITEM_DIV, SHTCUT_ITEMNM, SALE_QTY, PACK_DIV, SET_MENU_CD ";
                //sInsQuery += "        , ORD_TIME, CANCEL_DIV, SUB_MEMO_DIV, MSG1, MSG2, MSG3, MSG_REG_TIME, ORG_BILL_POSNO, ORG_BILLDT, ORG_BILL_NO ";
                //sInsQuery += "        , SEND_YN, SEND_CONFIRM_DIV, RESEND_YN, FILLER1, FILLER2, FILLER3, FILLER4, FILLER5, UPD_DT, REG_DT ) ";
                //sInsQuery += " VALUES ";
                //sInsQuery += "        ( '{0}', '{1}', '{2}', {3}, '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}', '{11}', '{12}', N'{13}', {14}, '{15}', '{16}' ";
                //sInsQuery += "        , '{17}', '{18}', '{19}', N'{20}', N'{21}', N'{22}', '{23}', '{24}', '{25}', '{26}' ";
                //sInsQuery += "        , '{27}', '{28}', '{29}', '{30}', '{31}', '{32}', '{33}', '{34}', '{35}', '{36}' ) "; 
                #endregion

                #region (주석) 주방출력 연습모드 적용 이전
                //sInsQuery = " INSERT INTO POSMST..MST_KTCH_ORD_MSG ";
                //sInsQuery += "        ( ORD_DIV, FLOOR_CD, TBL_NO, SEQ, CMP_CD, BRAND_CD, STOR_CD, SUB_STOR_CD, POS_NO, TRADE_NO, SALE_DT, POS_TYPE, ITEM_CD, ITEM_DIV, SHTCUT_ITEMNM, SALE_QTY, PACK_DIV, SET_MENU_CD ";
                //sInsQuery += "        , ORD_TIME, CANCEL_DIV, SUB_MEMO_DIV, MSG1, MSG2, MSG3, MSG_REG_TIME, ORG_BILL_POSNO, ORG_BILLDT, ORG_BILL_NO ";
                //sInsQuery += "        , SEND_YN, SEND_CONFIRM_DIV, RESEND_YN, FILLER1, FILLER2, FILLER3, FILLER4, FILLER5, UPD_DT, REG_DT ) ";
                //sInsQuery += " VALUES ";
                //sInsQuery += "        ( '{0}', '{1}', '{2}', {3}, '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}', '{11}', '{12}', '{13}', N'{14}', {15}, '{16}' ";
                //sInsQuery += "        , '{17}', '{18}', '{19}', '{20}', N'{21}', N'{22}', N'{23}', '{24}', '{25}', '{26}' ";
                //sInsQuery += "        , '{27}', '{28}', '{29}', '{30}', '{31}', '{32}', '{33}', '{34}', '{35}', '{36}' , '{37}') "; 
                #endregion

                #region (주석) KPS + KDS 동시사용, 2017.04.26
                //sInsQuery = " INSERT INTO POSMST..MST_KTCH_ORD_MSG ( ";
                //sInsQuery += "          ORD_DIV, FLOOR_CD, TBL_NO, SEQ, CMP_CD, BRAND_CD, STOR_CD, SUB_STOR_CD, POS_NO, TRADE_NO, SALE_DT, POS_TYPE, ITEM_CD, ITEM_DIV, SHTCUT_ITEMNM, SALE_QTY, PACK_DIV, SET_MENU_CD ";
                //sInsQuery += "        , ORD_TIME, CANCEL_DIV, SUB_MEMO_DIV, MSG1, MSG2, MSG3, MSG_REG_TIME, ORG_BILL_POSNO, ORG_BILLDT, ORG_BILL_NO ";
                //sInsQuery += "        , SEND_YN, SEND_CONFIRM_DIV, RESEND_YN, FILLER1, FILLER2, FILLER3, FILLER4, FILLER5, UPD_DT, REG_DT, TRAIN_MODE_YN  ";
                //sInsQuery += "        , KTCH_MSG \n";
                //sInsQuery += "  ) VALUES ";
                //sInsQuery += "        ( '{0}', '{1}', '{2}', {3}, '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}', '{11}', '{12}', '{13}', N'{14}', {15}, '{16}' ";
                //sInsQuery += "        , '{17}', '{18}', '{19}', '{20}', N'{21}', N'{22}', N'{23}', '{24}', '{25}', '{26}' ";
                //sInsQuery += "        , '{27}', '{28}', '{29}', '{30}', '{31}', '{32}', '{33}', '{34}', '{35}', '{36}' , '{37}', '{38}' ";
                //sInsQuery += "        ,N'{39}' \n";
                //sInsQuery += " )";  
                #endregion

                sInsQuery = " INSERT INTO POSMST..MST_KTCH_ORD_MSG ( ";
                sInsQuery += "          ORD_DIV, FLOOR_CD, TBL_NO, SEQ, CMP_CD, BRAND_CD, STOR_CD, SUB_STOR_CD, POS_NO, TRADE_NO, SALE_DT, POS_TYPE, ITEM_CD, ITEM_DIV, SHTCUT_ITEMNM, SALE_QTY, PACK_DIV, SET_MENU_CD ";
                sInsQuery += "        , ORD_TIME, CANCEL_DIV, SUB_MEMO_DIV, MSG1, MSG2, MSG3, MSG_REG_TIME, ORG_BILL_POSNO, ORG_BILLDT, ORG_BILL_NO ";
                sInsQuery += "        , SEND_YN, SEND_CONFIRM_DIV, RESEND_YN, FILLER1, FILLER2, FILLER3, FILLER4, FILLER5, UPD_DT, REG_DT, TRAIN_MODE_YN  ";
                sInsQuery += "        , KTCH_MSG    \n";                                                                // Add, 2017.03.23, 주방메시지
                sInsQuery += "        , ORD_PIC_NM  \n";                                                                // Add, 2017.03.28, 주문담당자
                sInsQuery += "        , ORG_QTY     \n";                                                                // Add, 2017.03.31, 이전주문수량
                sInsQuery += "        , ORD_POS_NO  \n";                                                                // Add, 2017.04.10, 주문포스번호 (서브포스에서도 주방출력 처리)
                sInsQuery += "        , KDS_SEND_YN \n";                                                                // Add, 2017.04.26, KDS 전송여부
                sInsQuery += "  ) VALUES ";
                sInsQuery += "        ( '{0}', '{1}', '{2}', {3}, '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}', '{11}', '{12}', '{13}', N'{14}', {15}, '{16}' ";
                sInsQuery += "        , '{17}', '{18}', '{19}', '{20}', N'{21}', N'{22}', N'{23}', '{24}', '{25}', '{26}' ";
                sInsQuery += "        , '{27}', '{28}', '{29}', '{30}', '{31}', '{32}', '{33}', '{34}', '{35}', '{36}' , '{37}', '{38}' ";
                sInsQuery += "        ,N'{39}' \n";
                sInsQuery += "        ,N'{40}' \n";
                sInsQuery += "        , 0 ";
                sInsQuery += "        , '{41}' \n";
                sInsQuery += "        , '{42}' \n";
                sInsQuery += " )";

                m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource, m_cPosStatus.Base.LocalDbCatalog, m_cPosStatus.Base.LocalDbUserID, m_cPosStatus.Base.LocalDbPassword);

                string sOrgOrderNum = "";

                for (int nLoop = 0; nLoop < alHappyOrderItem.Count; nLoop++)
                {
                    Column.TR_HPORD.HPORD_ITEM item = (Column.TR_HPORD.HPORD_ITEM)alHappyOrderItem[nLoop];

                    // 주문번호
                    string sOrderNum = item.OrderNum;

                    // SEQ 조회는 각 주문번호 별 한 번만 조회 함
                    if(sOrgOrderNum != sOrderNum)
                    {
                        sOrgOrderNum = sOrderNum;
                        sSQL = string.Format(sSelQuery,
                                             m_cPosStatus.Base.TrainingFlag,                                            // Add, 2017.03.06, 주방출력 연습모드 적용
                                             PosConst.ORDER_TYPE.NORMAL,
                                             m_cPosStatus.Base.PosNo,
                                             sOrderNum);
                        dtReturn = null;
                        if(m_cSqlDbService.DBSelect(sSQL, out dtReturn) == UserCom.OK)
                        {
                            iSeq = CmUtil.GetDataRowInt(dtReturn.Rows[0], "NEXT_SEQ");
                        }
                    }

                    // 주방프린트 수동출력 사용자 선택값  (Add, 2017.01.24)
                    var menualOrderValue = string.Empty;
                    var menualMsgRegTime = string.Empty;
                    var menualOrderMemo = string.Empty;
                    if (PosMstManager.GetPosOption(POS_OPTION.OPT425) == "1")
                    {
                        // 장치코드 또는 NOPRINT
                        menualOrderValue = string.IsNullOrWhiteSpace(m_cTrnStatus.Sale.MenualOrderValue)
                                         ? "NOPRINT"
                                         : m_cTrnStatus.Sale.MenualOrderValue;
                    }
                    else if (PosMstManager.GetPosOption(POS_OPTION.OPT425) == "2")
                    {
                        // 선택상품 또는 NOPRINT
                        int idx = m_cTrnStatus.Sale.MenualOrderValue.IndexOf(nLoop.ToString());
                        menualOrderValue = idx < 0 ? "NOPRINT" : "PRINT";

                        // Del, 2017.04.25, 주방메모 출력 (대기번호 입력)
                        // 주방메모 
                        //if (string.IsNullOrWhiteSpace(m_cTrnStatus.Sale.MenualOrderMemo) == false)
                        //{
                        //    menualOrderMemo = m_cTrnStatus.Sale.MenualOrderMemo;
                        //    menualMsgRegTime = DateTime.Now.ToString("HHmmss");
                        //}
                    }

                    // Add, 2017.04.25, 주방메모 출력 (대기번호 입력)
                    if (string.IsNullOrWhiteSpace(m_cTrnStatus.Sale.MenualOrderMemo) == false)
                    {
                        menualOrderMemo = m_cTrnStatus.Sale.MenualOrderMemo;
                        menualMsgRegTime = DateTime.Now.ToString("HHmmss");
                    }

                    // 기타주문구분       1:후불일반판매, 2:해피오더
                    string etcOrderFlag = "2";

                    //17.08.22 dkshin SS 해피오더
                    //해피오더 HEADER 데이터 중 'dailyCode' 값은 대기번호 . KDS 로 전송시 같이 전송해야 함.(MST_KTCH_ORD_MSG.TBL_NO)
                    string sOrderTime;
                    string sPosNo = m_cTrnStatus.Head.PosNo;
                    if (PosMstManager.GetPosOption(POS_OPTION.OPT048) != "0" || PosMstManager.GetPosOption(POS_OPTION.OPT049) == "1")
                    {
                        sOrderNum = item.DailyCode;
                        sOrderTime = item.PickupTime;
                        sOrderTime = sOrderTime.Substring(5, 5) + " " + sOrderTime.Substring(14, 5);//ex) 03-29 17:30
                    }
                    else
                        sOrderTime = DateTime.Now.ToString("HHmmss");

                    if (PosMstManager.GetPosOption(POS_OPTION.OPT048) != "0")//SS 해피오더 백그라운드 사용 시 해당 포스 번호 설정
                    {
                        sPosNo = PosMstManager.GetPosOption(POS_OPTION.OPT048);
                    }

                    sSQL = string.Format(sInsQuery,
                                         PosConst.ORDER_TYPE.NORMAL,                                                    // ORD_DIV
                                         //17.08.22 dkshin SS 해피오더
                                         //m_cTrnStatus.Head.PosNo,                                                       // FLOOR_CD(해피오더일 경우 POS번호)
                                         sPosNo,

                                         sOrderNum,                                                                     // TBL_NO(해피오더일 경우 주문번호)
                                         iSeq++,                                                                        // SEQ
                                         m_cTrnStatus.Head.CmpCd,                                                       // CMP_CD
                                         m_cPosStatus.Base.BrandCd,                                                     // BRAND_CD
                                         m_cTrnStatus.Head.StoreCd,                                                     // STOR_CD

                                         m_cTrnStatus.Head.StoreCd,                                                     // SUB_STOR_CD              // ADD, 2017.02.06

                                         m_cTrnStatus.Head.PosNo,                                                       // POS_NO
                                         sOrderNum,                                                                     // TRADE_NO
                                         m_cTrnStatus.Head.SaleDate,                                                    // SALE_DT
                                         m_cPosStatus.Base.PosType,                                                     // POS유형(0:선불, 1:후불)
                                         item.GoodsCode,                                                                // ITEM_CD
                                         ItemConst.PLU_ITEM_DIV.NORMAL,                                                 // ITEM_DIV
                                         item.GoodsName,                                                                // SHTCUT_ITEMNM
                                         item.Qty,                                                                      // SALE_QTY
                                         "0",                                                                           // PACK_DIV
                                         "",                                                                            // SET_MENU_CD
                                         //"",                                                                          // ORD_TIME
                                         //17.08.22 dkshin SS 해피오더
                                         //DateTime.Now.ToString("HHmmss"),
                                         sOrderTime,

                                         sTradeDiv,                                                                     // CANCEL_DIV
                                         "0",                                                                           // SUB_MEMO_DIV

                                         string.Empty,                                                                  // MSG1
                                         string.Empty,                                                                  // MSG2
                                         string.Empty,                                                                  // MSG3
                                         "",                                                                            // MSG_REG_TIME

                                         "",                                                                            // ORG_BILL_POSNO
                                         "",                                                                            // ORG_BILLDT
                                         "",                                                                            // ORG_BILL_NO
                                         "0",                                                                           // SEND_YN
                                         "0",                                                                           // SEND_CONFIRM_DIV
                                         "0",                                                                           // RESEND_YN
                                         menualOrderValue,                                                              // FILLER1
                                         etcOrderFlag,                                                                  // FILLER2
                                         "",                                                                            // FILLER3
                                         "",                                                                            // FILLER4
                                         "",                                                                            // FILLER5
                                         DateTime.Now.ToString("yyyyMMddHHmmss"),                                       // UPD_DT
                                         DateTime.Now.ToString("yyyyMMddHHmmss"),                                       // REG_DT
                                         m_cPosStatus.Base.TrainingFlag,                                                // Add, 2017.03.06, 주방출력 연습모드 적용
                                         ConvertDBStr(menualOrderMemo),                                                 // Add, 2017.03.21
                                         ConvertDBStr(m_cTrnStatus.Head.OrderPicNm),                                    // Add, 2017.03.28, 주문담당자
                                         m_cPosStatus.Base.PosNo,                                                       // Add, 2017.04.10, 주문포스번호 (서브포스에서도 주방출력 처리)
                                         "0"                                                                            // Add, 2017.04.26, KDS 전송여부 
                                         );
                    if(m_cSqlDbService.DBExecuteNonQuery(new string[] { sSQL }) != UserCom.OK)
                    {
                        return;
                    }
                }
                m_cSqlDbService.Close();
            }
            catch (Exception ex)
            {
                m_cSqlDbService.Close();
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
        }

        private string ConvertDBStr(string str)
        {
            return str.Replace("'", "''");
        }

        /// <summary>
        /// 해피오더 데이터 조회
        /// </summary>
        /// <param name="sOrderNum"></param>
        /// <returns></returns>
        public DataTable GetHappyOrderData(string sOrderNum, string sOrderDt)
        {
            int iRet = UserCom.NG;
            string sQuery = "";
            DataTable dtReturn = null;
            try
            {
                //#17141 [해피오더]배달영수증 주소 추가 start
                //기존
                //sQuery  = " SELECT ORD_STS, PRT_YN, NUTRITION_MSG ";
                //변경
                sQuery = " SELECT ORD_STS, PRT_YN, NUTRITION_MSG, FILLER5 ";
                //#17141 [해피오더]배달영수증 주소 추가 end
                sQuery += "   FROM POSMST..MST_HPORD ";
                sQuery += "  WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' ";
                sQuery += "    AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "' ";
                sQuery += "    AND ORD_DT = '" + sOrderDt +"' ";
                sQuery += "    AND ORD_NO = '" + sOrderNum + "' ";

                m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource, m_cPosStatus.Base.LocalDbCatalog, m_cPosStatus.Base.LocalDbUserID, m_cPosStatus.Base.LocalDbPassword);

                iRet = m_cSqlDbService.DBSelect(sQuery, out dtReturn);

                m_cSqlDbService.Close();
            }
            catch (Exception ex)
            {
                m_cSqlDbService.Close();
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

            return dtReturn;
        }

        /// <summary>
        /// 해피오더 오늘 픽업/배달 주문서출력 건 조회
        /// </summary>
        /// <param name="sOrderNum"></param>
        /// <returns></returns>
        public DataTable GetTodayHappyOrder()
        {
            int iRet = UserCom.NG;
            string sQuery = "";
            DataTable dtReturn = null;

            try
            {
                sQuery  = " SELECT ORD_NO ";
                sQuery += "   FROM POSMST..MST_HPORD ";
                sQuery += "  WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' ";
                sQuery += "    AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "' ";
                sQuery += "    AND ORD_STS IN ('" + ItemConst.HAPPYORDER_STATUS.ORDER_REG + "') ";
                sQuery += "    AND PRT_YN = '0' ";

                m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource, m_cPosStatus.Base.LocalDbCatalog, m_cPosStatus.Base.LocalDbUserID, m_cPosStatus.Base.LocalDbPassword);

                iRet = m_cSqlDbService.DBSelect(sQuery, out dtReturn);

                m_cSqlDbService.Close();

            }
            catch (Exception ex)
            {
                m_cSqlDbService.Close();
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

            return dtReturn;
        }

        /// <summary>
        /// 해피오더 데이터 갱신
        /// </summary>
        /// <param name="aParam"></param>
        /// <returns></returns>
        public int UpdateHappyOrderData(string[] aParam)
        {
            int iRet = UserCom.NG;
            string sUpdQuery = "";

            try
            {
                sUpdQuery  = " UPDATE POSMST..MST_HPORD ";
                if(aParam[0] == "PRINT")
                {
                    sUpdQuery += "SET PRT_YN = '" + aParam[1] + "' ";
                }
                else
                {
                    //sUpdQuery += "SET NUTRITION_MSG = REPLACE('" + aParam[1] + "', CHAR(10), CHAR(13) + CHAR(10))";
                    sUpdQuery += "SET NUTRITION_MSG = '" + aParam[1] + "' ";
                }
                sUpdQuery += "      , UPD_DT = '" + DateTime.Now.ToString("yyyyMMddHHmmss") + "' ";
                sUpdQuery += "  WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' ";
                sUpdQuery += "    AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "' ";
                sUpdQuery += "    AND ORD_DT = '" + aParam[3] + "' ";
                sUpdQuery += "    AND ORD_NO = '" + aParam[2] + "' ";
                
                m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource, m_cPosStatus.Base.LocalDbCatalog, m_cPosStatus.Base.LocalDbUserID, m_cPosStatus.Base.LocalDbPassword);

                iRet = m_cSqlDbService.DBExecuteNonQuery(new string[] { sUpdQuery }, true);
                
                m_cSqlDbService.Close();
            }
            catch (Exception ex)
            {
                m_cSqlDbService.Close();
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

            return iRet;
        }

        /// <summary>
        /// 해피오더 데이터 삭제
        /// </summary>
        /// <param name="sOrderNum"></param>
        /// <returns></returns>
        public int DeleteHappyOrderData(string sOrderNum, string sOrderDt)
        {
            int iRet = UserCom.NG;
            string[] sQuery = new string[2];

            try
            {
                sQuery[0]  = " DELETE FROM POSMST..MST_HPORD \n"
                           + "  WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' \n"
                           + "    AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "' \n"
                           + "    AND ORD_DT = '" + sOrderDt + "' \n"
                           + "    AND ORD_NO = '" + sOrderNum + "' \n";

                sQuery[1] = " DELETE FROM POSMST..MST_KTCH_ORD_MSG \n"
                          + "  WHERE ORD_DIV = '" + PosConst.ORDER_TYPE.NORMAL + "' \n"
                          + "    AND FLOOR_CD = '" + m_cPosStatus.Base.PosNo + "' \n"
                          + "    AND TBL_NO = '" + sOrderNum + "' \n"
                          + "    AND TRAIN_MODE_YN = '" + m_cPosStatus.Base.TrainingFlag + "' \n";

                m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource, m_cPosStatus.Base.LocalDbCatalog, m_cPosStatus.Base.LocalDbUserID, m_cPosStatus.Base.LocalDbPassword);

                iRet = m_cSqlDbService.DBExecuteNonQuery(sQuery, true);

                m_cSqlDbService.Close();
            }
            catch (Exception ex)
            {
                m_cSqlDbService.Close();
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

            return iRet;
        }

        //17.08.22 dkshin SS 해피오더
        /// <summary>
        /// 해피오더 데이터 삭제 MST_HPORD
        /// </summary>
        /// <param name="sOrderNum"></param>
        /// <returns></returns>
        public int DeleteSSHappyOrderData(string sOrderNum, string sOrderDt)
        {
            int iRet = UserCom.NG;
            string sQuery = "";

            try
            {
                sQuery = " DELETE FROM POSMST..MST_HPORD \n"
                           + "  WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "' \n"
                           + "    AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "' \n"
                           + "    AND ORD_DT = '" + sOrderDt + "' \n"
                           + "    AND ORD_NO = '" + sOrderNum + "' \n";

                m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource, m_cPosStatus.Base.LocalDbCatalog, m_cPosStatus.Base.LocalDbUserID, m_cPosStatus.Base.LocalDbPassword);

                iRet = m_cSqlDbService.DBExecuteNonQuery(sQuery);

                m_cSqlDbService.Close();
            }
            catch (Exception ex)
            {
                m_cSqlDbService.Close();
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

            return iRet;
        }

        //17.08.22 dkshin SS 해피오더
        /// <summary>
        /// 해피오더 데이터 삭제 MST_KTCH_ORD_MSG
        /// </summary>
        /// <param name="sOrderNum"></param>
        /// <returns></returns>
        public int DeleteSSHappyOrderMSG(string sOrderNum)
        {
            int iRet = UserCom.NG;
            string sQuery = "";

            try
            {
                sQuery = " DELETE FROM POSMST..MST_KTCH_ORD_MSG \n"
                          + "  WHERE ORD_DIV = '" + PosConst.ORDER_TYPE.NORMAL + "' \n"
                          + "    AND FLOOR_CD = '" + m_cPosStatus.Base.PosNo + "' \n"
                          + "    AND TBL_NO = '" + sOrderNum + "' \n"
                          + "    AND TRAIN_MODE_YN = '" + m_cPosStatus.Base.TrainingFlag + "' \n";

                m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource, m_cPosStatus.Base.LocalDbCatalog, m_cPosStatus.Base.LocalDbUserID, m_cPosStatus.Base.LocalDbPassword);

                iRet = m_cSqlDbService.DBExecuteNonQuery(sQuery);

                m_cSqlDbService.Close();
            }
            catch (Exception ex)
            {
                m_cSqlDbService.Close();
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

            return iRet;
        }

        /// <summary>
        /// 해피오더 데이터 저장
        /// </summary>
        /// <param name="header"></param>
        /// <returns></returns>
        public int SaveHappyOrderData(Column.TR_HPORD.HPORD_HEADER header)
        {
            int iRet = UserCom.NG;
            //string sInsQuery = "";
            //string sUpdQuery = "";
            string sQuery = "";
            string sSQL = "";

            //#17141 [해피오더]배달영수증 주소 추가 start
            string sReceiver = "";
            string sReceiverHP = "";
            string sReceiverAddress = "";
            string sOrderDate = "";
            string sOrderStatus = "";
            string orderNum = "";
            string DeliveryInfo = "";
            if (header != null)
            {
                if (header.OrderType == "4" || header.OrderType == "5")
                {
                    sReceiver = header.Receiver.Trim();
                    sReceiverHP = header.ReceiverHp.Trim();
                    sReceiverAddress = header.Address1.Trim() + " " + header.Address2.Trim();
                    
                    //#17533 해피오더)영수증/주문서 전화번호 항목 추가 start
                    //기존
                    //DeliveryInfo = sReceiver.Trim() + "#~" + sReceiverAddress.Trim() + "#~";
                    //변경
                    DeliveryInfo = sReceiver.Trim() + "#~" + sReceiverAddress.Trim() + "#~" + sReceiverHP.Trim() + "#~";
                    //#17533 해피오더)영수증/주문서 전화번호 항목 추가 end
                }
                
                orderNum = header.OrderNum;
                if (PosMstManager.GetPosOption(POS_OPTION.OPT048) != "0" || PosMstManager.GetPosOption(POS_OPTION.OPT049) == "1")
                {
                    orderNum = header.DailyCode;
                }
                sOrderDate = header.OrderDate.Substring(0, 10).Replace("-", "");
                sOrderStatus = header.OrderStatus;
            }
            //#17141 [해피오더]배달영수증 주소 추가 end

            try
            {
                //sInsQuery  = " INSERT INTO POSMST..MST_HPORD ";
                //sInsQuery += "        ( CMP_CD, STOR_CD, ORD_NO, ORD_STS, PRT_YN ";
                //sInsQuery += "        , NUTRITION_MSG, FILLER1, FILLER2, FILLER3, FILLER4 ";
                //sInsQuery += "        , FILLER5, UPD_DT, REG_DT ) ";
                //sInsQuery += " VALUES ";
                //sInsQuery += "        ( '{0}', '{1}', '{2}', '{3}', '{4}' ";
                //sInsQuery += "        , '{5}', '{6}', '{7}', '{8}', '{9}' ";
                //sInsQuery += "        , '{10}', '{11}' ,'{12}' ) ";

                //sUpdQuery  = " UPDATE POSMST..MST_HPORD ";
                //sUpdQuery += "    SET ORD_STS = '{0}' ";
                //sUpdQuery += "      , UPD_DT = '" + DateTime.Now.ToString("yyyyMMddHHmmss") + "' ";
                //sUpdQuery += "  WHERE CMP_CD = '{1}' ";
                //sUpdQuery += "    AND STOR_CD = '{2}' ";
                //sUpdQuery += "    AND ORD_NO = '{3}' ";

                sQuery  = "UPDATE POSMST..MST_HPORD ";
                sQuery += "   SET ORD_STS = '{0}' ";
                sQuery += "     , UPD_DT = '" + DateTime.Now.ToString("yyyyMMddHHmmss") + "' ";
                sQuery += " WHERE CMP_CD = '{1}' ";
                sQuery += "   AND STOR_CD = '{2}' ";
                sQuery += "   AND ORD_NO = '{3}' ";
                sQuery += "IF @@ROWCOUNT = 0 ";
                sQuery += "INSERT INTO POSMST..MST_HPORD ";
                sQuery += "       ( CMP_CD, STOR_CD, ORD_DT, ORD_NO, ORD_STS ";
                sQuery += "       , PRT_YN, NUTRITION_MSG, FILLER1, FILLER2, FILLER3 ";
                sQuery += "       , FILLER4, FILLER5, UPD_DT, REG_DT ) ";
                sQuery += "VALUES ";
                sQuery += "       ( '{4}', '{5}', '{6}', '{7}', '{8}' ";
                sQuery += "       , '{9}', '{10}', '{11}', '{12}', '{13}' ";
                sQuery += "       , '{14}', '{15}' ,'{16}', '{17}' ) ";

                m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource, m_cPosStatus.Base.LocalDbCatalog, m_cPosStatus.Base.LocalDbUserID, m_cPosStatus.Base.LocalDbPassword);

                //sSQL = string.Format(sUpdQuery,
                //                         header.OrderStatus,
                //                         m_cPosStatus.Base.CmpCd,
                //                         m_cPosStatus.Base.StoreNo,
                //                         header.OrderNum);
                //iRet = m_cSqlDbService.DBExecuteNonQuery(new string[] { sSQL }, true);                
                
                //if(iRet != UserCom.OK)
                //{
                //    sSQL = string.Format(sInsQuery,
                //                     m_cPosStatus.Base.CmpCd,
                //                     m_cPosStatus.Base.StoreNo,
                //                     header.OrderNum,
                //                     header.OrderStatus,
                //                     "0",
                //                     "",
                //                     "", "", "", "", "",
                //                     DateTime.Now.ToString("yyyyMMddHHmmss"),
                //                     DateTime.Now.ToString("yyyyMMddHHmmss"));
                //    iRet = m_cSqlDbService.DBExecuteNonQuery(new string[] { sSQL }, true);
                //}
                //17.08.22 dkshin SS 해피오더 - dailyCode값 대기번호가 TBL_NO으로 저장되므로 ORDER_NO에 대기번호 저장


                //#17141 [해피오더]배달영수증 주소 추가 start
                //기존
                /*
                string orderNum = header.OrderNum;
                if (PosMstManager.GetPosOption(POS_OPTION.OPT048) != "0" || PosMstManager.GetPosOption(POS_OPTION.OPT049) == "1")
                {
                    orderNum = header.DailyCode;
                }
                sSQL = string.Format(sQuery,
                                     header.OrderStatus,
                                     m_cPosStatus.Base.CmpCd,
                                     m_cPosStatus.Base.StoreNo,
                                     //17.08.22 dkshin SS 해피오더
                                     //header.OrderNum,
                                     orderNum,

                                     m_cPosStatus.Base.CmpCd,
                                     m_cPosStatus.Base.StoreNo,
                                     header.OrderDate.Substring(0, 10).Replace("-", ""),
                                     //17.08.22 dkshin SS 해피오더
                                     //header.OrderNum,
                                     orderNum,

                                     header.OrderStatus,
                                     "0",
                                     "",
                                     "", "", "", "", "",
                                     DateTime.Now.ToString("yyyyMMddHHmmss"),
                                     DateTime.Now.ToString("yyyyMMddHHmmss"));
                */
                //변경
                sSQL = string.Format(sQuery,
                                     header.OrderStatus,
                                     m_cPosStatus.Base.CmpCd,
                                     m_cPosStatus.Base.StoreNo,
                                     orderNum,

                                     m_cPosStatus.Base.CmpCd,
                                     m_cPosStatus.Base.StoreNo,
                                     sOrderDate,
                                     orderNum,

                                     sOrderStatus,
                                     "0",
                                     "",
                                     "", "", "", "",
                                     DeliveryInfo,
                                     DateTime.Now.ToString("yyyyMMddHHmmss"),
                                     DateTime.Now.ToString("yyyyMMddHHmmss"));
                //#17141 [해피오더]배달영수증 주소 추가 end


                iRet = m_cSqlDbService.DBExecuteNonQuery(new string[] { sSQL }, true);         

                m_cSqlDbService.Close();
            }
            catch(Exception ex)
            {
                m_cSqlDbService.Close();
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

            return iRet;
        }

        /// <summary>
        /// 영양상태 정보 파싱 처리
        /// </summary>
        /// <param name="htNutritionMsgs"></param>
        /// <returns></returns>
        public string ParseNutritionMsg(Hashtable[] htNutritionMsgs)
        {
            StringBuilder sbPrintMsg = new StringBuilder();
            string LF = "\r\n";
            try
            {
                //grayber@20180202 [BR]해피오더 고객정보 추가 + 원산지 표기 start - [BR] 영양정보 분기 처리
                if (m_cPosStatus.Mst.CorpDiv.Equals(ItemConst.CORP_DIV.BR) == true)
                {
                    foreach (Hashtable htMsg in htNutritionMsgs)
                    {
                        // 상품명
                        sbPrintMsg.Append("-상품명 : " + htMsg["goodsName"].ToString());
                        sbPrintMsg.Append(LF);

                        // 영양정보 #1 ~ #15
                        for (int nLoop = 1; nLoop < 16; nLoop++)
                        {
                            if (htMsg["text" + nLoop.ToString()] != null)
                            {
                                sbPrintMsg.Append("-"+htMsg["text" + nLoop.ToString()].ToString());
                                sbPrintMsg.Append(" : ");
                                if (htMsg["content" + nLoop.ToString()] != null)
                                {
                                    sbPrintMsg.Append(htMsg["content" + nLoop.ToString()].ToString());
                                }
                                sbPrintMsg.Append(LF);
                            }
                        }
                        sbPrintMsg.Append(LF);
                    }
                }
                else
                {
                    foreach (Hashtable htMsg in htNutritionMsgs)
                    {
                        // 상품명
                        sbPrintMsg.Append(htMsg["goodsName"].ToString());
                        sbPrintMsg.Append(LF);

                        // infoType 
                        sbPrintMsg.Append(htMsg["infoType"].ToString());
                        sbPrintMsg.Append(LF);

                        // 영양정보 #1 ~ #15
                        for (int nLoop = 1; nLoop < 16; nLoop++)
                        {
                            if (htMsg["text" + nLoop.ToString()] != null)
                            {
                                if (nLoop > 1) sbPrintMsg.Append("/");
                                sbPrintMsg.Append(htMsg["text" + nLoop.ToString()].ToString());
                                sbPrintMsg.Append(" - ");
                                if (htMsg["content" + nLoop.ToString()] != null)
                                {
                                    sbPrintMsg.Append(htMsg["content" + nLoop.ToString()].ToString());
                                }
                            }
                        }
                        sbPrintMsg.Append(LF);
                    }
                }
                //grayber@20180202 [BR]해피오더 고객정보 추가 + 원산지 표기 end
            }
            catch(Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

            return sbPrintMsg.ToString();
        }

        /// <summary>
        /// 해피오더 Http 통신
        /// </summary>
        /// <param name="aParam"></param>
        /// <returns></returns>
        public Hashtable[] SendReceiveForHappyOrder(object[] aParam, ref Hashtable htResponse, ref int iReturn)
        {
            string sUrl;
            string sWorkType;
            Hashtable htRequest;
            Hashtable[] htReturn = null;
            int iRet = BaseCom.NG;

            try
            {
                sUrl = (string)aParam[0];
                sWorkType = (string)aParam[1];
                htRequest = (Hashtable)aParam[2];

                htResponse = null;
                string sResp = string.Empty;
                if ((iRet = m_cNetworkHttp.HttpJsonPOST_SendReceive(sUrl, sWorkType, htRequest, ref htResponse, ref sResp)) == BaseCom.OK)
                {
                    htReturn = JsonConvert.DeserializeObject<Hashtable[]>(sResp);
                }

                iReturn = iRet;
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

            return htReturn;
        }


        //#16366 해피오더 당월누적주문내역 + 당일 해피오더주문 상세내역 자동 출력기능 start
        public Hashtable SendReceiveForHappyOrder2(object[] aParam, ref Hashtable htResponse, ref int iReturn)
        {
            string sUrl;
            string sWorkType;
            Hashtable htRequest;
            Hashtable htReturn = null;
            int iRet = BaseCom.NG;

            try
            {
                sUrl = (string)aParam[0];
                sWorkType = (string)aParam[1];
                htRequest = (Hashtable)aParam[2];

                htResponse = null;
                string sResp = string.Empty;
                if ((iRet = m_cNetworkHttp.HttpJsonPOST_SendReceive(sUrl, sWorkType, htRequest, ref htResponse, ref sResp)) == BaseCom.OK)
                {
                    htReturn = JsonConvert.DeserializeObject<Hashtable>(sResp);
                }

                iReturn = iRet;
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

            return htReturn;
        }
        //#16366 해피오더 당월누적주문내역 + 당일 해피오더주문 상세내역 자동 출력기능 end

        /// <summary>
        /// JSon string parsing
        /// </summary>
        /// <param name="sJsonString"></param>
        /// <returns></returns>
        public Hashtable[] ParseJsonString(string sJsonString)
        {
            Hashtable[] htReturn = null;
            try
            {
                htReturn = JsonConvert.DeserializeObject<Hashtable[]>(sJsonString);
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

            return htReturn;
        }

        /// <summary>
        /// 주문서 출력
        /// </summary>
        /// <param name="sPrtGubun"> D: 당일, M: 당월</param>
        /// <param name="bHPOAutoPrintYN"> true: 자동출력, false: 자동미출력</param>
        /// <returns></returns>
        //#16366 해피오더 당월누적주문내역 + 당일 해피오더주문 상세내역 자동 출력기능 start
        //기존
        //public bool PrintOrderSheet()
        //변경
        public bool PrintOrderSheet(string sPrtGubun, bool bHPOAutoPrintYN)
        //#16366 해피오더 당월누적주문내역 + 당일 해피오더주문 상세내역 자동 출력기능 end
        {
            bool bReturn = false;
            try
            {
                string[] arPrintData = (string[])m_sPrintData.ToArray(typeof(string));
                //bReturn = m_cPrinterUs.ReceiptPrinter(arPrintData);

                //#16366 해피오더 당월누적주문내역 + 당일 해피오더주문 상세내역 자동 출력기능 start
                //기존
                //bReturn = m_cRecService.PosPrint(arPrintData);
                //변경
                bReturn = m_cRecService.PosPrint(arPrintData, bHPOAutoPrintYN, sPrtGubun);
                //#16366 해피오더 당월누적주문내역 + 당일 해피오더주문 상세내역 자동 출력기능 end
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
            return bReturn;
        }

        public bool PrintWeightLabel(ArrayList alOrderItem)
        {
            bool bReturn = false;
            string sGoodsName = string.Empty;
            string sOrderNum = string.Empty;
            string sWeight = string.Empty;
            string sContent1 = string.Empty;
            string sContent2 = string.Empty;
            string sStoreName = string.Empty;
            string sOrderDT = string.Empty;
            string sPackDT = string.Empty;
            try
            {
                foreach(Column.TR_HPORD.HPORD_ITEM item in alOrderItem)
                {
                    if(item.FlavourFlag == "N")
                    {
                        sGoodsName = item.GoodsName;
                        sOrderNum = item.OrderNum;
                    }
                    else
                    {

                    }
                }
            }
            catch(Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

            return bReturn;
        }

        #region 상품정보조회 IRT 처리
        /// <summary>
        /// 상품정보 조회 IRT 처리
        /// </summary>
        /// <param name="sCmpCd"></param>
        /// <param name="sStoreCd"></param>
        /// <param name="sItemCd"></param>
        /// <param name="htRecvData"></param>
        /// <returns></returns>
        private string ExecItemInfoIrt(string sCmpCd, string sStoreCd, string sItemCd, ref Hashtable htRecvData)
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                Hashtable htReqData = new Hashtable();

                htReqData.Add(Column.IQ_POS_ITEMINFO.DATA.INQ_TYPE, ItemConst.IRT_INQ_TYPE.POS_ITEMINFO_REQ);
                htReqData.Add(Column.IQ_POS_ITEMINFO.DATA.CMP_CD, sCmpCd);
                htReqData.Add(Column.IQ_POS_ITEMINFO.DATA.STOR_CD, sStoreCd);
                htReqData.Add(Column.IQ_POS_ITEMINFO.DATA.ITEM_CD, sItemCd);
                htReqData.Add(Column.IQ_POS_ITEMINFO.DATA.ITEM_DATA, "");
                htReqData.Add(Column.IQ_POS_ITEMINFO.DATA.RES_CD, "");

                return m_cDataCommon.ExecutePosIrt(ItemConst.COMM_MSG_TYPE.POSIRT, m_cPosStatus.Base.CommSvrIp, (int)m_cPosStatus.Base.PayInqPort, 10000, htReqData, ref htRecvData, false);
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

            return sRet;
        }
        #endregion

        #region 상품마스터 등록 처리
        private bool RegisterItemInfoToMst(string aItemInfo)
        {
            string sQuery = string.Empty;
            string sInsQuery = string.Empty;

            IDatabaseSQL cDatabaseSql = null;

            string[] aParams = aItemInfo.Split('|');

            try
            {
                sInsQuery += "UPDATE POSMST..MST_ITEM ";
                sInsQuery += "   SET L_CLSS = '{4}', M_CLSS = '{5}', S_CLSS = '{6}', FLAVOUR_DIV = '{7}', FLAVOUR_QTY = {8} ";
                sInsQuery += "     , FLAVOUR_STOCK = {9}, SHTCUT_ITEMNM = N'{10}', ITEM_NM = N'{11}', TAKE_IN_SALE_AMT = {12}, TAKE_OUT_SALE_AMT = {13} ";
                sInsQuery += "     , IF_MENU1 = '{14}', IF_MENU2 = '{15}', OPEN_ITEM_DIV = '{16}', DISPO_ITEM_DIV = '{17}', SUB_SET_MNG_TYPE = '{18}' ";
                sInsQuery += "     , ITEM_TAX_AMT_DIV = '{19}', TAKE_IN_VAT_CD = '{20}', TAKE_OUT_VAT_CD = '{21}', ITEM_COST = {22} ";
                sInsQuery += "     , SALE_PRMT_YN = '{23}', SALE_NOQ = {24}, FREE_GIFT_YN = '{25}', DC_PRMT_YN = '{26}', ACCUM_PRMT_YN = '{27}' ";
                sInsQuery += "     , SVC_FEE_TRGT_YN = '{28}', BTN_ITEM_IMG = '{29}', NEW_ITEM_START_DT = '{30}', NEW_ITEM_FNSH_DT = '{31}', ITEM_TYPE = '{32}' ";
                sInsQuery += "     , TIME_BAR_CD_YN = '{33}', DISTBT_EXPIRE_NOD = '{34}', ALCOHOL_ITEM_TYPE = '{35}', SALE_START_DT = '{36}', SALE_FNSH_DT = '{37}' ";
                sInsQuery += "     , COOP_CARD_DC_NOADM_YN = '{38}', CAKE_EXCHNG_CPN_USE_POSS_YN = '{39}', ITEM_INFO = N'{40}', CALORY_INFO = N'{41}', SALE_IMG_FILE_NM = '{42}' ";
                sInsQuery += "     , FILLER1 = '{43}', FILLER2 = '{44}', FILLER3 = '{45}', FILLER4 = '{46}', FILLER5 = '{47}' ";
                sInsQuery += "     , USE_YN = '{48}', UPD_DT = '{49}' ";
                sInsQuery += " WHERE CMP_CD = '{0}' ";
                sInsQuery += "   AND STOR_CD = '{1}' ";
                sInsQuery += "   AND SUB_STOR_CD = '{2}' ";
                sInsQuery += "   AND ITEM_CD = '{3}' ";
                sInsQuery += "IF @@ROWCOUNT = 0 ";
                sInsQuery += "INSERT INTO POSMST..MST_ITEM ";
                sInsQuery += "       ( CMP_CD, STOR_CD, SUB_STOR_CD, ITEM_CD, L_CLSS ";
                sInsQuery += "       , M_CLSS, S_CLSS, FLAVOUR_DIV, FLAVOUR_QTY, FLAVOUR_STOCK ";
                sInsQuery += "       , SHTCUT_ITEMNM, ITEM_NM, TAKE_IN_SALE_AMT, TAKE_OUT_SALE_AMT, IF_MENU1 ";
                sInsQuery += "       , IF_MENU2, OPEN_ITEM_DIV, DISPO_ITEM_DIV, SUB_SET_MNG_TYPE, ITEM_TAX_AMT_DIV ";
                sInsQuery += "       , TAKE_IN_VAT_CD, TAKE_OUT_VAT_CD, ITEM_COST, SALE_PRMT_YN, SALE_NOQ ";
                sInsQuery += "       , FREE_GIFT_YN, DC_PRMT_YN, ACCUM_PRMT_YN, SVC_FEE_TRGT_YN, BTN_ITEM_IMG ";
                sInsQuery += "       , NEW_ITEM_START_DT, NEW_ITEM_FNSH_DT, ITEM_TYPE, TIME_BAR_CD_YN, DISTBT_EXPIRE_NOD ";
                sInsQuery += "       , ALCOHOL_ITEM_TYPE, SALE_START_DT, SALE_FNSH_DT, COOP_CARD_DC_NOADM_YN, CAKE_EXCHNG_CPN_USE_POSS_YN ";
                sInsQuery += "       , ITEM_INFO, CALORY_INFO, SALE_IMG_FILE_NM, FILLER1, FILLER2 ";
                sInsQuery += "       , FILLER3, FILLER4, FILLER5, USE_YN, REG_DT ) ";
                sInsQuery += "VALUES ";
                sInsQuery += "       ( '{0}', '{1}', '{2}', '{3}', '{4}' ";
                sInsQuery += "       , '{5}', '{6}', '{7}', {8}, {9} ";
                sInsQuery += "       , N'{10}', N'{11}', {12}, {13}, '{14}' ";
                sInsQuery += "       , '{15}', '{16}', '{17}', '{18}', '{19}' ";
                sInsQuery += "       , '{20}', '{21}', {22}, '{23}', {24} ";
                sInsQuery += "       , '{25}', '{26}', '{27}', '{28}', '{29}' ";
                sInsQuery += "       , '{30}', '{31}', '{32}', '{33}', '{34}' ";
                sInsQuery += "       , '{35}', '{36}', '{37}', '{38}', '{39}' ";
                sInsQuery += "       , N'{40}', N'{41}', '{42}', '{43}', '{44}' ";
                sInsQuery += "       , '{45}', '{46}', '{47}', '{48}', '{49}' ) ";
                
                sQuery = string.Format( sInsQuery
                                      , aParams[0], m_cPosStatus.Base.StoreNo, aParams[2], aParams[3], aParams[4]
                                      , aParams[5], aParams[6], aParams[7], aParams[8], aParams[9]
                                      , aParams[10], aParams[11], aParams[12], aParams[13], aParams[14]
                                      , aParams[15], aParams[16], aParams[17], aParams[18], aParams[19]
                                      , aParams[20], aParams[21], aParams[22], aParams[23], aParams[24]
                                      , aParams[25], aParams[26], aParams[27], aParams[28], aParams[29]
                                      , aParams[30], aParams[31], aParams[32], aParams[33], aParams[34]
                                      , aParams[35], aParams[36], aParams[37], aParams[38], aParams[39]
                                      , aParams[40], aParams[41], aParams[42], aParams[43], aParams[44]
                                      , aParams[45], aParams[46], aParams[47], aParams[48], DateTime.Now.ToString("yyyyMMddHHmmsss"));
                
                cDatabaseSql = (IDatabaseSQL)sManager.InitServiceInstance(ServiceLists.AGENT_DATABASE.DLL, ServiceLists.AGENT_DATABASE.DATABASE_MSSQL);
                
                // DB Connect
                cDatabaseSql.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource
                                                  , m_cPosStatus.Base.LocalDbCatalog
                                                  , m_cPosStatus.Base.LocalDbUserID
                                                  , m_cPosStatus.Base.LocalDbPassword);

                if (cDatabaseSql.DBExecuteNonQuery(sQuery) != UserCom.OK)
                {
                    UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                            UserCom.WARNING_LEVEL,
                                            System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                            System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                            sQuery);
                    return false;
                }
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);

                return false;
            }
            finally
            {
                cDatabaseSql.Close();
            }

            return true;
        }
        #endregion

        #region 상품TRAN 생성
        private string MakeTranItemUsingMST(DataTable dtItemData, Column.TR_HPORD.HPORD_HEADER hpordHeader, Column.TR_HPORD.HPORD_ITEM hpordItem)
        {
            string sReturn = UserCom.RST_ERR;
            double nTotDcAmt = 0;

            try
            {
                ArrayList aSaleItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);

                // 상품 정보 생성
                Column.TR_PLU.DATA cPluItem = new Column.TR_PLU.DATA();

                DataRow drPlu = dtItemData.Rows[0];
                
                //20171215_판매불가 체크 제외_hs
                //해피오더 상품 매출 처리중 판매불가 상품 체크 제외
                //if (CmUtil.LongParse(CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.SALE_START_DT)) > CmUtil.LongParse(m_cPosStatus.Base.SaleDate)
                //    || CmUtil.LongParse(CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.SALE_FNSH_DT)) < CmUtil.LongParse(m_cPosStatus.Base.SaleDate))
                //{
                //    WinManager.ErrorMessage(POS_MESSAGE.ERROR.MSG_0011);            // 판매 불가 상품 입니다
                //    return sReturn;
                //}


                //#20180903 해피오더 매출 생성 시 tr_sale_detail에 구분자 추가 start
                cPluItem.HPO_REG_YN = "1";
                //#20180903 해피오더 매출 생성 시 tr_sale_detail에 구분자 추가 end

                cPluItem.SUB_SHOP_CD = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.SUB_STOR_CD);
                cPluItem.ITEM_PLU_CD = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.ITEM_CD);

                if (PosMstManager.GetPosOption(POS_OPTION.OPT005) == "0")
                {
                    cPluItem.SALE_PRC = CmUtil.GetDataRowDouble(drPlu, PosMst.MST_ITEM.DATA.TAKE_OUT_SALE_AMT);
                    cPluItem.TAXRATE_CD = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.TAKE_OUT_VAT_CD);
                }
                else
                {
                    cPluItem.SALE_PRC = CmUtil.GetDataRowDouble(drPlu, PosMst.MST_ITEM.DATA.TAKE_IN_SALE_AMT);
                    cPluItem.TAXRATE_CD = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.TAKE_IN_VAT_CD);
                }

                cPluItem.ITEM_TAKE_IN_VAT_CD = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.TAKE_IN_VAT_CD);
                cPluItem.ITEM_TAKE_OUT_VAT_CD = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.TAKE_OUT_VAT_CD);


                cPluItem.FLAVOUR_DIV = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.FLAVOUR_DIV) == "" ? ItemConst.PLU_FLAVOUR_DIV.NORMAL : CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.FLAVOUR_DIV);
                cPluItem.FLAVOUR_QTY = CmUtil.GetDataRowLong(drPlu, PosMst.MST_ITEM.DATA.FLAVOUR_QTY);
                cPluItem.FLAVOUR_STOCK = CmUtil.GetDataRowDouble(drPlu, PosMst.MST_ITEM.DATA.FLAVOUR_STOCK);
                cPluItem.ITEM_TAX_DIV = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.ITEM_TAX_AMT_DIV);

                cPluItem.NOTAX_DIV = PosConst.ITEM_NOTAX_DIV.NO;

                cPluItem.SUB_SET_MNG_TYPE = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.SUB_SET_MNG_TYPE);
                cPluItem.ITEM_NAME = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.SHTCUT_ITEMNM);

                cPluItem.FREE_GIFT_YN = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.FREE_GIFT_YN);
                cPluItem.DC_PRMT_YN = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.DC_PRMT_YN);
                cPluItem.ACCUM_PRMT_YN = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.ACCUM_PRMT_YN);
                cPluItem.SVC_FEE_TRGT_YN = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.SVC_FEE_TRGT_YN);
                cPluItem.COOP_CARD_DC_NOADM_YN = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.COOP_CARD_DC_NOADM_YN);
                cPluItem.L_CLSS = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.L_CLSS);
                cPluItem.M_CLSS = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.M_CLSS);
                cPluItem.S_CLSS = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.S_CLSS);

                cPluItem.CANCEL_DIV = PosConst.CANCEL_DIV.NORMAL;
                cPluItem.ITEM_BRAND_CD = m_cPosStatus.Base.BrandCd;
                cPluItem.ITEM_DIV = ItemConst.PLU_ITEM_DIV.NORMAL;
                cPluItem.SUB_SET_MNG_TYPE = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.SUB_SET_MNG_TYPE);

                if (cPluItem.FLAVOUR_DIV == ItemConst.PLU_FLAVOUR_DIV.FLAVOUR)
                {
                    // 플레이버
                    cPluItem.ITEM_NAME = ">" + CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.SHTCUT_ITEMNM);
                }
                else
                {
                    cPluItem.ITEM_NAME = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.SHTCUT_ITEMNM);
                }
                cPluItem.SALE_QTY = long.Parse(CmUtil.IsNull(hpordItem.Qty, "0"));
                cPluItem.SALE_PRC = double.Parse(hpordItem.SupplyPrice.Trim() == "" ? "0" : hpordItem.SupplyPrice.Trim());
                cPluItem.SALE_AMT = CmUtil.DoubleMultiplication(cPluItem.SALE_QTY, cPluItem.SALE_PRC);

                cPluItem.TAX_AMT_INCLUDE_YN = m_cPosStatus.Mst.TaxAmtIncludeYn;
                if (double.Parse(CmUtil.IsNull(hpordItem.CashTotSurTax, "0")) > 0)
                {
                    cPluItem.ITEM_TAX_DIV = "1";
                    cPluItem.APPLY_TAX_AMT = double.Parse(hpordItem.CashTotSurTax);
                }
                else
                {
                    cPluItem.ITEM_TAX_DIV = "0";
                    cPluItem.APPLY_TAX_AMT = 0;
                }

                //cPluItem.ETC_DC_AMT = double.Parse(CmUtil.IsNull(hpordItem.DiscountPrice, "0"));
                cPluItem.ETC_DC_AMT = CmUtil.DoubleMultiplication(cPluItem.SALE_QTY, double.Parse(CmUtil.IsNull(hpordItem.DiscountPrice, "0")));
                if (cPluItem.ETC_DC_AMT > 0)
                {
                    if (hpordHeader.OrderType.Equals("6"))
                    {
                        // 사전예약일 경우 사전예약할인으로 기타할인구분 설정(2017.04.11)
                        cPluItem.ETC_DC_DIV = ItemConst.PLU_ETC_DC_TYPE.DC_PRE_RESERVED;
                    }
                    else
                    {
                        // 그 이외는 해피오더할인으로 기타할인구분 설정
                        cPluItem.ETC_DC_DIV = ItemConst.PLU_ETC_DC_TYPE.DC_HPORD;
                    }
                }
                else
                {
                    cPluItem.ETC_DC_DIV = ItemConst.PLU_ETC_DC_TYPE.NORMAL;
                }

                cPluItem.EXCEP_DC_DIV = "0000";
                cPluItem.EXCEP_DC_AMT = 0;

                cPluItem.SVC_FEE_AMT = 0;
                cPluItem.SVC_FEE_VAT = 0;
                cPluItem.DC_DIV = ItemConst.PLU_DC_DIV.NORMAL;
                cPluItem.DC_RATE = 0;
                cPluItem.ITEM_DC_AMT = 0;
                cPluItem.SUM_DC_AMT = 0;
                cPluItem.CPI_DC_AMT = 0;
                cPluItem.COOP_CARD_DC_AMT = 0;
                cPluItem.POINT_DC_AMT = 0;
                cPluItem.CPN_DC_AMT = 0;
                cPluItem.EMP_DC_AMT = 0;
                cPluItem.SET_DC_AMT = 0;
                cPluItem.SET_DC_GROUP_CD = 0;

                nTotDcAmt = CmUtil.DoubleAdd(nTotDcAmt, cPluItem.ITEM_DC_AMT);              // 단품 할인 금액
                nTotDcAmt = CmUtil.DoubleAdd(nTotDcAmt, cPluItem.SUM_DC_AMT);               // 소계 할인 금액
                nTotDcAmt = CmUtil.DoubleAdd(nTotDcAmt, cPluItem.CPI_DC_AMT);               // 행사 할인 금액
                nTotDcAmt = CmUtil.DoubleAdd(nTotDcAmt, cPluItem.COOP_CARD_DC_AMT);         // 제휴카드 할인 금액
                nTotDcAmt = CmUtil.DoubleAdd(nTotDcAmt, cPluItem.POINT_DC_AMT);             // 포인트 할인 금액
                nTotDcAmt = CmUtil.DoubleAdd(nTotDcAmt, cPluItem.CPN_DC_AMT);               // 쿠폰 할인 금액
                nTotDcAmt = CmUtil.DoubleAdd(nTotDcAmt, cPluItem.EMP_DC_AMT);               // 직원 할인 금액
                nTotDcAmt = CmUtil.DoubleAdd(nTotDcAmt, cPluItem.SET_DC_AMT);               // 세트 할인 금액
                nTotDcAmt = CmUtil.DoubleAdd(nTotDcAmt, cPluItem.ETC_DC_AMT);               // 기타 할인 금액

                nTotDcAmt = CmUtil.DoubleAdd(nTotDcAmt, cPluItem.EXCEP_DC_AMT);             // 예외 할인 금액
                
                cPluItem.TOT_DC_AMT = nTotDcAmt;

                cPluItem.BILL_AMT = CmUtil.DoubleSubtraction(cPluItem.SALE_AMT, cPluItem.TOT_DC_AMT);  // 영수금액

                cPluItem.ITEM_INPUT_DIV = "0";
                cPluItem.ITEM_BAR_CD = hpordItem.Barcode;

                aSaleItem.Add(cPluItem);

                sReturn = UserCom.RST_OK;
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

            return sReturn;
        }

        private string MakeTranItemUsingHPORD(Column.TR_HPORD.HPORD_HEADER hpordHeader, Column.TR_HPORD.HPORD_ITEM hpordItem)
        {
            string sReturn = UserCom.RST_ERR;
            double nTotDcAmt = 0;

            try
            {
                if (hpordItem.GoodsCode == null || hpordItem.GoodsCode == "0") return sReturn;

                ArrayList aSaleItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);

                // 상품 정보 생성
                Column.TR_PLU.DATA cPluItem = new Column.TR_PLU.DATA();

                //#20180903 해피오더 매출 생성 시 tr_sale_detail에 구분자 추가 start
                cPluItem.HPO_REG_YN = "1";
                //#20180903 해피오더 매출 생성 시 tr_sale_detail에 구분자 추가 end

                cPluItem.CANCEL_DIV = PosConst.CANCEL_DIV.NORMAL;
                cPluItem.ITEM_PLU_CD = hpordItem.GoodsCode;
                cPluItem.ITEM_BRAND_CD = m_cPosStatus.Base.BrandCd;
                cPluItem.SUB_SHOP_CD = m_cPosStatus.Base.StoreNo;
                cPluItem.ITEM_DIV = ItemConst.PLU_ITEM_DIV.NORMAL;
                cPluItem.SUB_SET_MNG_TYPE = PosConst.MST_SUB_SET_MNG_TYPE.NORMAL;

                if (CmUtil.StringNullEmpty(hpordItem.FlavourFlag).Equals("N") == false)
                {
                    cPluItem.ITEM_NAME = " >" + hpordItem.GoodsName;
                    cPluItem.FLAVOUR_DIV = ItemConst.PLU_FLAVOUR_DIV.FLAVOUR;
                }
                else
                {
                    cPluItem.ITEM_NAME = hpordItem.GoodsName;
                    cPluItem.FLAVOUR_DIV = ItemConst.PLU_FLAVOUR_DIV.NORMAL;
                }
                cPluItem.SALE_QTY = long.Parse(CmUtil.IsNull(hpordItem.Qty, "0"));
                cPluItem.SALE_PRC = double.Parse(hpordItem.SupplyPrice.Trim() == "" ? "0" : hpordItem.SupplyPrice.Trim());
                cPluItem.SALE_AMT = CmUtil.DoubleMultiplication(cPluItem.SALE_QTY, cPluItem.SALE_PRC);

                //cPluItem.TAX_AMT_INCLUDE_YN = "1";
                cPluItem.TAX_AMT_INCLUDE_YN = m_cPosStatus.Mst.TaxAmtIncludeYn;
                if (double.Parse(CmUtil.IsNull(hpordItem.CashTotSurTax, "0")) > 0)
                {
                    cPluItem.ITEM_TAX_DIV = "1";
                    cPluItem.APPLY_TAX_AMT = double.Parse(hpordItem.CashTotSurTax);
                }
                else
                {
                    cPluItem.ITEM_TAX_DIV = "0";
                    cPluItem.APPLY_TAX_AMT = 0;
                }

                cPluItem.NOTAX_DIV = PosConst.ITEM_NOTAX_DIV.NO;

                //cPluItem.ETC_DC_AMT = double.Parse(CmUtil.IsNull(hpordItem.DiscountPrice, "0"));
                cPluItem.ETC_DC_AMT = CmUtil.DoubleMultiplication(cPluItem.SALE_QTY, double.Parse(CmUtil.IsNull(hpordItem.DiscountPrice, "0")));
                if (cPluItem.ETC_DC_AMT > 0)
                {
                    if (hpordHeader.OrderType.Equals("6"))
                    {
                        // 사전예약일 경우 사전예약할인으로 기타할인구분 설정(2017.04.11)
                        cPluItem.ETC_DC_DIV = ItemConst.PLU_ETC_DC_TYPE.DC_PRE_RESERVED;
                    }
                    else
                    {
                        // 그 이외는 해피오더할인으로 기타할인구분 설정
                        cPluItem.ETC_DC_DIV = ItemConst.PLU_ETC_DC_TYPE.DC_HPORD;
                    }
                }
                else
                {
                    cPluItem.ETC_DC_DIV = ItemConst.PLU_ETC_DC_TYPE.NORMAL;
                }

                cPluItem.EXCEP_DC_DIV = "0000";
                cPluItem.EXCEP_DC_AMT = 0;

                cPluItem.SVC_FEE_AMT = 0;
                cPluItem.SVC_FEE_VAT = 0;
                cPluItem.DC_DIV = ItemConst.PLU_DC_DIV.NORMAL;
                cPluItem.DC_RATE = 0;
                cPluItem.ITEM_DC_AMT = 0;
                cPluItem.SUM_DC_AMT = 0;
                cPluItem.CPI_DC_AMT = 0;
                //cPluItem.COOP_CARD_DC_DIV = 
                cPluItem.COOP_CARD_DC_AMT = 0;
                //cPluItem.POINT_DC_DIV
                cPluItem.POINT_DC_AMT = 0;
                //cPluItem.CPN_DC_DIV
                cPluItem.CPN_DC_AMT = 0;
                //cPluItem.EMP_DC_DIVEC
                cPluItem.EMP_DC_AMT = 0;
                cPluItem.SET_DC_AMT = 0;
                cPluItem.SET_DC_GROUP_CD = 0;

                nTotDcAmt = CmUtil.DoubleAdd(nTotDcAmt, cPluItem.ITEM_DC_AMT);              // 단품 할인 금액
                nTotDcAmt = CmUtil.DoubleAdd(nTotDcAmt, cPluItem.SUM_DC_AMT);               // 소계 할인 금액
                nTotDcAmt = CmUtil.DoubleAdd(nTotDcAmt, cPluItem.CPI_DC_AMT);               // 행사 할인 금액
                nTotDcAmt = CmUtil.DoubleAdd(nTotDcAmt, cPluItem.COOP_CARD_DC_AMT);         // 제휴카드 할인 금액
                nTotDcAmt = CmUtil.DoubleAdd(nTotDcAmt, cPluItem.POINT_DC_AMT);             // 포인트 할인 금액
                nTotDcAmt = CmUtil.DoubleAdd(nTotDcAmt, cPluItem.CPN_DC_AMT);               // 쿠폰 할인 금액
                nTotDcAmt = CmUtil.DoubleAdd(nTotDcAmt, cPluItem.EMP_DC_AMT);               // 직원 할인 금액
                nTotDcAmt = CmUtil.DoubleAdd(nTotDcAmt, cPluItem.SET_DC_AMT);               // 세트 할인 금액
                nTotDcAmt = CmUtil.DoubleAdd(nTotDcAmt, cPluItem.ETC_DC_AMT);               // 기타 할인 금액

                nTotDcAmt = CmUtil.DoubleAdd(nTotDcAmt, cPluItem.EXCEP_DC_AMT);             // 예외 할인 금액


                cPluItem.TOT_DC_AMT = nTotDcAmt;

                cPluItem.BILL_AMT = CmUtil.DoubleSubtraction(cPluItem.SALE_AMT, cPluItem.TOT_DC_AMT);  // 영수금액

                cPluItem.ITEM_INPUT_DIV = "0";
                cPluItem.ITEM_BAR_CD = hpordItem.Barcode;
                    

                aSaleItem.Add(cPluItem);

                sReturn = UserCom.RST_OK;
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

            return sReturn;
        }

        //#15746 해피오더 '쇼킹박스' 관련 POS 시스템 개발 요청 start
        //기존
        //public string MakeTranItem(Column.TR_HPORD.HPORD_HEADER cHeader, ArrayList aItem)
        //변경
        public string MakeTranItem(Column.TR_HPORD.HPORD_HEADER cHeader, ArrayList aItem, Hashtable htReadingBarCodeInfo)
        //#15746 해피오더 '쇼킹박스' 관련 POS 시스템 개발 요청 end
        {
            string sReturn = UserCom.RST_ERR;
            try
            {
                //#15746 해피오더 '쇼킹박스' 관련 POS 시스템 개발 요청 start
                bool bLandomBoxSetting = false;
                //#15746 해피오더 '쇼킹박스' 관련 POS 시스템 개발 요청 end

                ArrayList aSaleItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);

                foreach(Column.TR_HPORD.HPORD_ITEM item in aItem)
                {
                    // 상품 마스터 조회
                    DataTable dtDataInfo = m_cDataCommon.SearchItemCode(m_cPosStatus.Base.StoreNo, item.GoodsCode, "");
                    if(dtDataInfo == null || dtDataInfo.Rows.Count == 0)
                    {                        
                        // 서버 상품 조회
                        Hashtable htRecvData = new Hashtable();

                        ExecItemInfoIrt(m_cPosStatus.Base.CmpCd, m_cPosStatus.Base.StoreNo, item.GoodsCode, ref htRecvData);

                        if(htRecvData == null || htRecvData.Count == 0)
                        {
                            UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                                 System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                                 System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                                 System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                                 "Make tran data using HAPPY ORDER");
                            // 해피오더 아이템 정보로 트란데이터 생성
                            MakeTranItemUsingHPORD(cHeader, item);
                        }
                        else
                        {
                            if(htRecvData[Column.IQ_POS_ITEMINFO.DATA.RES_CD].ToString() == "00")
                            {
                                string sItemInfo = htRecvData[Column.IQ_POS_ITEMINFO.DATA.ITEM_DATA].ToString();

                                if(RegisterItemInfoToMst(sItemInfo) == false)
                                {
                                    UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                                         System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                                         System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                                         System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                                         "Make tran data using HAPPY ORDER");
                                    // 해피오더 아이템 정보로 트란데이터 생성
                                    MakeTranItemUsingHPORD(cHeader, item);
                                }
                                else
                                {
                                    // 상품 마스터 정보로 트란데이터 생성
                                    dtDataInfo = m_cDataCommon.SearchItemCode(m_cPosStatus.Base.StoreNo, item.GoodsCode, "");
                                    if (dtDataInfo != null && dtDataInfo.Rows.Count > 0)
                                    {
                                        UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                                             System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                                             System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                                             System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                                             "Make tran data using MST_ITEM table");
                                        MakeTranItemUsingMST(dtDataInfo, cHeader, item);
                                    }
                                    else
                                    {
                                        UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                                             System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                                             System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                                             System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                                             "Make tran data using HAPPY ORDER");
                                        // 해피오더 아이템 정보로 트란데이터 생성
                                        MakeTranItemUsingHPORD(cHeader, item);
                                    }
                                }
                            }
                            else
                            {
                                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                                     "Make tran data using HAPPY ORDER");
                                // 해피오더 아이템 정보로 트란데이터 생성
                                MakeTranItemUsingHPORD(cHeader, item);
                            }
                        }
                    }
                    else
                    {
                        UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                             System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                             System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                             System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                             "Make tran data using MST_ITEM table");
                        // 상품 마스터 정보로 트란데이터 생성
                        MakeTranItemUsingMST(dtDataInfo, cHeader, item);
                    }

                    //#15746 해피오더 '쇼킹박스' 관련 POS 시스템 개발 요청 start
                    if (htReadingBarCodeInfo != null && bLandomBoxSetting == false)
                    {
                        if (htReadingBarCodeInfo.Count > 0)
                        {
                            if (item.OrderNum == htReadingBarCodeInfo["HPORDER_NO"].ToString() &&
                                item.GoodsCode == htReadingBarCodeInfo["ITEM_CD"].ToString())
                            {

                                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                                     "Make HappOrder LandomBox Item ▶" +
                                                     "  OrderNum : " + htReadingBarCodeInfo["HPORDER_NO"].ToString() +
                                                     " ,ItemCode : " + htReadingBarCodeInfo["ITEM_CD"].ToString() +
                                                     " ,BarCodeNo : " + htReadingBarCodeInfo["BARCODE_NO"].ToString() +
                                                     " ,SaleDt : " + htReadingBarCodeInfo["SALE_DT"].ToString() +
                                                     " ,RegNo : " + htReadingBarCodeInfo["REG_NO"].ToString() +
                                                     " ,PosNo : " + htReadingBarCodeInfo["POS_NO"].ToString());

                                bool bRet = LoadLocalTrDetail(htReadingBarCodeInfo["SALE_DT"].ToString(),
                                                              htReadingBarCodeInfo["POS_NO"].ToString(),
                                                              htReadingBarCodeInfo["REG_NO"].ToString(),
                                                              htReadingBarCodeInfo["ITEM_CD"].ToString(),
                                                              htReadingBarCodeInfo["BARCODE_NO"].ToString());

                                bLandomBoxSetting = true;
                            }
                        }
                    }
                    //#15746 해피오더 '쇼킹박스' 관련 POS 시스템 개발 요청 end
                }

                // 상품 판매가 계산
                // 해피오더는 캠페인 태우지 않음(20170601)
                //m_cPluService.ItemAmountExeccute(true, true);
                m_cPluService.ItemAmountExeccute(false, true);

                sReturn = UserCom.RST_OK;
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

            return sReturn;
        }
        #endregion 상품TRAN 생성

        //#20171215, 해피오더 주문리스트 조회 시 해피오더 테이블 데이터 삭제 후 저장하도록 수정 Start
        /// <summary>
        /// 해피오더 데이터 전체 삭제
        /// </summary>
        /// <returns></returns>
        public int DeleteHappyOrderAllData()
        {
            int iRet = UserCom.NG;
            string sQuery = "";

            try
            {
                sQuery = "TRUNCATE TABLE POSMST..MST_HPORD \n";

                m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource, m_cPosStatus.Base.LocalDbCatalog, m_cPosStatus.Base.LocalDbUserID, m_cPosStatus.Base.LocalDbPassword);

                iRet = m_cSqlDbService.DBExecuteNonQuery(sQuery);

                m_cSqlDbService.Close();
            }
            catch (Exception ex)
            {
                m_cSqlDbService.Close();
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

            return iRet;
        }
        //#20171215, 해피오더 주문리스트 조회 시 해피오더 테이블 데이터 삭제 후 저장하도록 수정 End


        //#15746 해피오더 '쇼킹박스' 관련 POS 시스템 개발 요청 start

        #region LoadLocalTrDetail
        private bool LoadLocalTrDetail(string sSaleDate, string sPosNo, string sTradeNo, string sItemCd, string sBarcodeNo)
        {
            bool bRet = false;

            try
            {
                string sQuery = "";

                sQuery += " SELECT '#~' + '" + ItemConst.IRT_TRAN_TYPE.TranDetail + "' + '|' + '000000' + '|' + CONVERT(VARCHAR, ISNULL(SEQ, 0)) + '|' + ISNULL(ORD_TIME, '') + '|' + ISNULL(FLOOR_CD, '') + '|' + ISNULL(TBL_NO, '') + '|' + ";
                sQuery += " ISNULL(SUB_SHOP_CD, '') + '|' + ISNULL(ITEM_PLU_CD, '') + '|' + ISNULL(ITEM_DIV, '') + '|' + CONVERT(VARCHAR, ISNULL(SALE_QTY, 0)) + '|' + CONVERT(VARCHAR, ISNULL(SALE_PRC, 0)) + '|' + ";
                sQuery += " CONVERT(VARCHAR, ISNULL(SALE_AMT, 0)) + '|' + ISNULL(FLAVOUR_DIV, '') + '|' + CONVERT(VARCHAR, ISNULL(FLAVOUR_WEIGHT, 0)) + '|' + ISNULL(ITEM_INPUT_DIV, '') + '|' + ISNULL(ITEM_BAR_CD, '') + '|' + ";
                sQuery += " ISNULL(TAKE_IN_OUT_DIV, '') + '|' + ISNULL(ITEM_TAX_DIV, '') + '|' + ISNULL(TAX_AMT_INCLUDE_YN, '') + '|' + ISNULL(TAXRATE_CD, '') + '|' + CONVERT(VARCHAR, ISNULL(APPLY_TAX_AMT, 0)) + '|' + CONVERT(VARCHAR, ISNULL(SVC_FEE_AMT, 0)) + '|' + CONVERT(VARCHAR, ISNULL(SVC_FEE_VAT, 0)) + '|' + ";
                sQuery += " ISNULL(SVC_TAXREATE_CD, '') + '|' + CONVERT(VARCHAR, ISNULL(BILL_AMT, 0)) + '|' + ISNULL(NONSALES_RSN_CD, '') + '|' + ISNULL(DC_DIV, '') + '|' + ISNULL(DC_TYPE, '') + '|' + CONVERT(VARCHAR, ISNULL(DC_RATE, 0)) + '|' + CONVERT(VARCHAR, ISNULL(ITEM_DC_AMT, 0)) + '|' + ";
                sQuery += " CONVERT(VARCHAR, ISNULL(SUM_DC_AMT, 0)) + '|' + CONVERT(VARCHAR, ISNULL(CPI_DC_QTY, 0)) + '|' + CONVERT(VARCHAR, ISNULL(CPI_DC_AMT, 0)) + '|' + ISNULL(COOP_CARD_DC_DIV, '') + '|' + CONVERT(VARCHAR, ISNULL(COOP_CARD_DC_AMT, 0)) + '|' + ISNULL(POINT_DC_DIV, '') + '|' + CONVERT(VARCHAR, ISNULL(POINT_DC_AMT, 0)) + '|' + ";
                sQuery += " ISNULL(CPN_DC_DIV, '') + '|' + CONVERT(VARCHAR, ISNULL(CPN_DC_AMT, 0)) + '|' + ISNULL(EMP_DC_DIV, '') + '|' + CONVERT(VARCHAR, ISNULL(EMP_DC_AMT, 0)) + '|' + CONVERT(VARCHAR, ISNULL(SET_DC_AMT, 0)) + '|' + ISNULL(ETC_DC_DIV, '') + '|' + CONVERT(VARCHAR, ISNULL(ETC_DC_AMT, 0)) + '|' + ";
                sQuery += " ISNULL(EXCEP_DC_DIV, '') + '|' + CONVERT(VARCHAR, ISNULL(EXCEP_DC_AMT, 0)) + '|' + ISNULL(PACK_DIV, '') + '|' + ISNULL(SET_MENU_CD, '') + '|' + ISNULL(SUBPRC_MENU_KEY_DIV, '') + '|' + ";
                sQuery += " ISNULL(CPI_PRESENT_DIV, '') + '|' + CONVERT(VARCHAR, ISNULL(BILLSPR_NO, 0)) + '|' + ISNULL(SALE_GIFT_NO, '') + '|' + ISNULL(CPN_NO, '') + '|' + ISNULL(SLACK_FIELD, '') + '|' + ISNULL(DISPO_ITEM_DIV, '') + '|' + ISNULL(CANCEL_DIV, '')  + '|' + ISNULL(NOTAX_DIV, '0') AS TR_DETAIL";


                sQuery += "   FROM POSLOG..ETC_SALE_DETAIL ";
                sQuery += "  WHERE CMP_CD  = '" + m_cPosStatus.Base.CmpCd + "'";
                sQuery += "    AND SALE_DT = '" + sSaleDate + "'";
                sQuery += "    AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "'";
                sQuery += "    AND POS_NO  = '" + sPosNo + "'";
                sQuery += "    AND REG_NO  = '" + sTradeNo + "'";
                sQuery += "    AND CANCEL_DIV = '" + ItemConst.PAY_CANCEL_DIV.NORMAL + "'";

                m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource, m_cPosStatus.Base.LocalDbCatalog, m_cPosStatus.Base.LocalDbUserID, m_cPosStatus.Base.LocalDbPassword);

                DataTable dtTrDetail = null;

                if (m_cSqlDbService.DBSelect(sQuery, out dtTrDetail) == UserCom.OK)
                {
                    if (dtTrDetail != null && dtTrDetail.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dtTrDetail.Rows)
                        {
                            if (TranParserToDetail(dr[0].ToString(), sItemCd, sBarcodeNo) == false) return bRet;
                        }
                    }
                }

                bRet = true;
            }
            catch (Exception ex)
            {
                m_cSqlDbService.Close();

                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }

            return bRet;
        }
        #endregion

        //#15746 해피오더 '쇼킹박스' 관련 POS 시스템 개발 요청 end

        //#15746 해피오더 '쇼킹박스' 관련 POS 시스템 개발 요청 start

        #region TranParserToDetail
        private bool TranParserToDetail(string sTrData, string sItemCd, string sBarcodeNo)
        {
            try
            {
                string[] aTrData = sTrData.Split('|');

                ArrayList m_alTrPluItem = (ArrayList)StateObject.GetItemObject(Column.TR_PLU.ITEM);

                Column.TR_PLU.DATA cSaleItem = new Column.TR_PLU.DATA();

                cSaleItem.ORD_TIME = aTrData[Column.TR_PLU.SEQ.ORD_TIME];
                cSaleItem.FLOOR_CD = aTrData[Column.TR_PLU.SEQ.FLOOR_CD];
                cSaleItem.TBL_NO = aTrData[Column.TR_PLU.SEQ.TBL_NO];
                cSaleItem.SUB_SHOP_CD = aTrData[Column.TR_PLU.SEQ.SUB_SHOP_CD];
                cSaleItem.ITEM_PLU_CD = aTrData[Column.TR_PLU.SEQ.ITEM_PLU_CD];
                cSaleItem.ITEM_DIV = "3"; // aTrData[Column.TR_PLU.SEQ.ITEM_DIV];
                cSaleItem.SALE_QTY = CmUtil.LongParse(aTrData[Column.TR_PLU.SEQ.SALE_QTY]);
                cSaleItem.SALE_PRC = 0; // CmUtil.DoubleParse(aTrData[Column.TR_PLU.SEQ.SALE_PRC]);
                cSaleItem.SALE_AMT = 0; //CmUtil.DoubleParse(aTrData[Column.TR_PLU.SEQ.SALE_AMT]);
                cSaleItem.FLAVOUR_DIV = aTrData[Column.TR_PLU.SEQ.FLAVOUR_DIV];
                cSaleItem.FLAVOUR_STOCK = CmUtil.DoubleParse(aTrData[Column.TR_PLU.SEQ.FLAVOUR_STOCK]);
                cSaleItem.ITEM_INPUT_DIV = aTrData[Column.TR_PLU.SEQ.ITEM_INPUT_DIV];
                cSaleItem.ITEM_BAR_CD = aTrData[Column.TR_PLU.SEQ.ITEM_BAR_CD];
                cSaleItem.TAKE_IN_OUT_DIV = aTrData[Column.TR_PLU.SEQ.TAKE_IN_OUT_DIV];
                cSaleItem.ITEM_TAX_DIV = aTrData[Column.TR_PLU.SEQ.ITEM_TAX_DIV];
                cSaleItem.TAX_AMT_INCLUDE_YN = aTrData[Column.TR_PLU.SEQ.TAX_AMT_INCLUDE_YN];
                cSaleItem.TAXRATE_CD = aTrData[Column.TR_PLU.SEQ.TAXRATE_CD];
                cSaleItem.APPLY_TAX_AMT = 0; // CmUtil.DoubleParse(aTrData[Column.TR_PLU.SEQ.APPLY_TAX_AMT]);
                cSaleItem.SVC_FEE_AMT = 0; // CmUtil.DoubleParse(aTrData[Column.TR_PLU.SEQ.SVC_FEE_AMT]);
                cSaleItem.SVC_FEE_VAT = 0; //CmUtil.DoubleParse(aTrData[Column.TR_PLU.SEQ.SVC_FEE_VAT]);
                cSaleItem.SVC_TAXREATE_CD = aTrData[Column.TR_PLU.SEQ.SVC_TAXREATE_CD];
                cSaleItem.BILL_AMT = 0; //CmUtil.DoubleParse(aTrData[Column.TR_PLU.SEQ.BILL_AMT]);
                cSaleItem.NONSALES_RSN_CD = aTrData[Column.TR_PLU.SEQ.NONSALES_RSN_CD];
                cSaleItem.DC_DIV = ItemConst.PLU_DC_DIV.NORMAL; // aTrData[Column.TR_PLU.SEQ.DC_DIV];
                cSaleItem.DC_TYPE = "0"; //aTrData[Column.TR_PLU.SEQ.DC_TYPE];
                cSaleItem.DC_RATE = 0; //CmUtil.DoubleParse(aTrData[Column.TR_PLU.SEQ.DC_RATE]);
                cSaleItem.ITEM_DC_AMT = 0; //CmUtil.DoubleParse(aTrData[Column.TR_PLU.SEQ.ITEM_DC_AMT]);
                cSaleItem.SUM_DC_AMT = 0; //CmUtil.DoubleParse(aTrData[Column.TR_PLU.SEQ.SUM_DC_AMT]);
                cSaleItem.CPI_DC_QTY = 0; //CmUtil.LongParse(aTrData[Column.TR_PLU.SEQ.CPI_DC_QTY]);
                cSaleItem.CPI_DC_AMT = 0; //CmUtil.DoubleParse(aTrData[Column.TR_PLU.SEQ.CPI_DC_AMT]);
                cSaleItem.COOP_CARD_DC_DIV = "0"; //aTrData[Column.TR_PLU.SEQ.COOP_CARD_DC_DIV];
                cSaleItem.COOP_CARD_DC_AMT = 0; //CmUtil.DoubleParse(aTrData[Column.TR_PLU.SEQ.COOP_CARD_DC_AMT]);
                cSaleItem.POINT_DC_DIV = "0"; //aTrData[Column.TR_PLU.SEQ.POINT_DC_DIV];
                cSaleItem.POINT_DC_AMT = 0; //CmUtil.DoubleParse(aTrData[Column.TR_PLU.SEQ.POINT_DC_AMT]);
                cSaleItem.CPN_DC_DIV = "0"; //aTrData[Column.TR_PLU.SEQ.CPN_DC_DIV];
                cSaleItem.CPN_DC_AMT = 0; //CmUtil.DoubleParse(aTrData[Column.TR_PLU.SEQ.CPN_DC_AMT]);
                cSaleItem.EMP_DC_DIV = "0"; //aTrData[Column.TR_PLU.SEQ.EMP_DC_DIV];
                cSaleItem.EMP_DC_AMT = 0; //CmUtil.DoubleParse(aTrData[Column.TR_PLU.SEQ.EMP_DC_AMT]);
                cSaleItem.SET_DC_AMT = 0; //CmUtil.DoubleParse(aTrData[Column.TR_PLU.SEQ.SET_DC_AMT]);
                cSaleItem.ETC_DC_DIV = ItemConst.PLU_ETC_DC_TYPE.NORMAL; //aTrData[Column.TR_PLU.SEQ.ETC_DC_DIV];
                cSaleItem.ETC_DC_AMT = 0; //CmUtil.DoubleParse(aTrData[Column.TR_PLU.SEQ.ETC_DC_AMT]);
                cSaleItem.EXCEP_DC_DIV = "0000"; //aTrData[Column.TR_PLU.SEQ.EXCEP_DC_DIV];
                cSaleItem.EXCEP_DC_AMT = 0; //CmUtil.DoubleParse(aTrData[Column.TR_PLU.SEQ.EXCEP_DC_AMT]);
                cSaleItem.PACK_DIV = aTrData[Column.TR_PLU.SEQ.PACK_DIV];
                cSaleItem.SET_MENU_CD = sItemCd;// aTrData[Column.TR_PLU.SEQ.SET_MENU_CD];
                cSaleItem.SUBPRC_MENU_KEY_DIV = "1"; // aTrData[Column.TR_PLU.SEQ.SUBPRC_MENU_KEY_DIV];
                cSaleItem.CPI_PRESENT_DIV = aTrData[Column.TR_PLU.SEQ.CPI_PRESENT_DIV];
                cSaleItem.BILLSPR_NO = CmUtil.LongParse(aTrData[Column.TR_PLU.SEQ.BILLSPR_NO]);
                cSaleItem.SALE_GIFT_NO = aTrData[Column.TR_PLU.SEQ.SALE_GIFT_NO];
                cSaleItem.CPN_NO = aTrData[Column.TR_PLU.SEQ.CPN_NO];
                cSaleItem.DISPO_ITEM_DIV = aTrData[Column.TR_PLU.SEQ.DISPO_ITEM_DIV];

                cSaleItem.CANCEL_DIV = aTrData[Column.TR_PLU.SEQ.CANCEL_DIV];
                if (cSaleItem.CANCEL_DIV == PosConst.CANCEL_DIV.CANCEL_SUBTOT)
                {
                    cSaleItem.CANCEL_DIV = PosConst.CANCEL_DIV.CANCEL;
                }
                cSaleItem.NOTAX_DIV = aTrData[Column.TR_PLU.SEQ.NOTAX_DIV];

                cSaleItem.ORDER_OK_FLAG = PosConst.PLU_ORDER_OK_FLAG.ORDER_ING;

                cSaleItem.SLACK_FIELD = aTrData[Column.TR_PLU.SEQ.SLACK_FIELD];         // 선불카드권종(2017.06.27)

                // 상품 마스터 조회 후 마스터 항목 설정
                SetTrDetailToMst(cSaleItem.SUB_SHOP_CD, cSaleItem.ITEM_PLU_CD, ref cSaleItem);

                cSaleItem.SLACK_FIELD = sBarcodeNo.Trim();

                //#20180903 해피오더 매출 생성 시 tr_sale_detail에 구분자 추가 start
                cSaleItem.HPO_REG_YN = "1";
                //#20180903 해피오더 매출 생성 시 tr_sale_detail에 구분자 추가 end

                //m_cDataService.UpdatePluItemAmount(cSaleItem);

                m_alTrPluItem.Add(cSaleItem);                    // 등록 처리

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

        //#15746 해피오더 '쇼킹박스' 관련 POS 시스템 개발 요청 end

        //#15746 해피오더 '쇼킹박스' 관련 POS 시스템 개발 요청 start

        #region SetTrDetailToMst
        private void SetTrDetailToMst(string sSubStoreCode, string sItemCdoe, ref Column.TR_PLU.DATA cPluItem)
        {
            try
            {
                // 상품 마스터 조회
                DataTable dtDataInfo = m_cDataCommon.SeletItemMstToItemCode(sSubStoreCode, sItemCdoe);
                if (dtDataInfo != null && dtDataInfo.Rows.Count > 0)
                {
                    DataRow drPlu = dtDataInfo.Rows[0];

                    cPluItem.SUB_SET_MNG_TYPE = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.SUB_SET_MNG_TYPE);

                    cPluItem.ITEM_NAME = ">>" + CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.SHTCUT_ITEMNM);

                    cPluItem.CANCEL_DIV_MAIN = "0";
                    cPluItem.FREE_GIFT_YN = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.FREE_GIFT_YN);
                    cPluItem.DC_PRMT_YN = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.DC_PRMT_YN);

                    cPluItem.ACCUM_PRMT_YN = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.ACCUM_PRMT_YN);
                    cPluItem.SVC_FEE_TRGT_YN = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.SVC_FEE_TRGT_YN);
                    cPluItem.COOP_CARD_DC_NOADM_YN = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.COOP_CARD_DC_NOADM_YN);

                    cPluItem.L_CLSS = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.L_CLSS);
                    cPluItem.M_CLSS = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.M_CLSS);
                    cPluItem.S_CLSS = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.S_CLSS);

                    cPluItem.OPEN_ITEM_DIV = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.OPEN_ITEM_DIV); //MoonSeokWoo 2017.09.11

                    cPluItem.ITEM_TAKE_IN_VAT_CD = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.TAKE_IN_VAT_CD);
                    cPluItem.ITEM_TAKE_OUT_VAT_CD = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.TAKE_OUT_VAT_CD);

                    cPluItem.ITEM_INFO = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.ITEM_INFO); // 영양성분 
                    cPluItem.ITEM_EXPLN = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.ITEM_EXPLN); // 상품설명 
                    cPluItem.ALLERGY = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.ALLERGY); // 알레르기성분 
                    cPluItem.PLACE_ORIGIN = CmUtil.GetDataRowStr(drPlu, PosMst.MST_ITEM.DATA.PLACE_ORIGIN); // 원산지

                    cPluItem.TAX_RATE = m_cDataCommon.ItemTaxRate(cPluItem.TAXRATE_CD);
                }
                else if (cPluItem.ITEM_DIV == ItemConst.PLU_ITEM_DIV.OPT_MENU && cPluItem.SUBPRC_MENU_KEY_DIV == "1")
                {

                    dtDataInfo = m_cDataCommon.SeletSubPrcMenu(sSubStoreCode, sItemCdoe);

                    if (dtDataInfo != null && dtDataInfo.Rows.Count > 0)
                    {
                        DataRow drPlu = dtDataInfo.Rows[0];

                        cPluItem.ITEM_NAME = ">>" + CmUtil.GetDataRowStr(drPlu, PosMst.MST_SUBPRC_MENU_GRP.DATA.LABEL_NM);
                    }
                }

            }
            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

        //#15746 해피오더 '쇼킹박스' 관련 POS 시스템 개발 요청 end



        //#15945 해피오더 자동주문 상세기능 start

        #region HappyOrder_AutomaticShipmentLog
        public void HappyOrder_AutomaticShipmentLog(Column.TR_HPORD.HPORD_HEADER HPORD_HEADER, string HPORD_TOBESTATUS, string HPORD_CLOUDRES)
        {
            string sQuery = "";
            string sSQL = "";
            try
            {
                //#20180914 해피오더 자동출하 로그 추가 start
                UserLog.WriteLogFile(UserCom.LOG_IOS,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "자동출하데이터저장 start");
                //#20180914 해피오더 자동출하 로그 추가 end

                try
                {
                    // 주문 취소 시 
                    // 해당 해피오더 건이 '주문접수 -> 상품준비' 변경한 데이터 존재 시 인서트하고 
                    // 아니면 인서트 하지 않는다.
                    if (HPORD_TOBESTATUS == ItemConst.HAPPYORDER_STATUS.ORDER_CANCEL)
                    {
                        sQuery = "SELECT * ";
                        sQuery += "  FROM POSLOG..TR_AUTOMATICSHIPMENT_LOG ";
                        sQuery += " WHERE CMP_CD = '{0}' AND SALE_DT = '{1}' AND STOR_CD = '{2}'";
                        sQuery += "   AND POS_NO = '{3}' AND ORDER_NO = '{4}' AND STATUS = " + ItemConst.HAPPYORDER_STATUS.PRODUCT_READY + "";

                        sQuery += "IF @@ROWCOUNT <> 0";
                    }

                    // 주문접수 -> 상품준비 시 인서트
                    else
                    {
                        sQuery = "SELECT * ";
                        sQuery += "  FROM POSLOG..TR_AUTOMATICSHIPMENT_LOG ";
                        sQuery += " WHERE CMP_CD = '{0}' AND SALE_DT = '{1}' AND STOR_CD = '{2}'";
                        sQuery += "   AND POS_NO = '{3}' AND ORDER_NO = '{4}' AND STATUS = {5}";

                        sQuery += "IF @@ROWCOUNT = 0";
                    }

                    sQuery += "INSERT INTO POSLOG..TR_AUTOMATICSHIPMENT_LOG(CMP_CD,SALE_DT,STOR_CD,POS_NO,";
                    sQuery += "                                             ORDER_NO,STATUS,PRE_STATUS,ORDER_TYPE,";
                    sQuery += "                                             CLOUD_RES,GUBUN,CASHIER_ID,SEND_YN,";
                    sQuery += "                                             UPD_DATE,REG_DATE)";
                    sQuery += "VALUES ( '{0}' ,  '{1}' ,  '{2}' ,  '{3}', ";
                    sQuery += "         '{4}' ,   {5}  ,   {6}  ,  '{7}', ";
                    sQuery += "          {8}  ,  '{9}' , '{10}' , '{11}', ";
                    sQuery += "        '{12}' , '{13}' ) ";


                    m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource,
                                                          m_cPosStatus.Base.LocalDbCatalog,
                                                          m_cPosStatus.Base.LocalDbUserID,
                                                          m_cPosStatus.Base.LocalDbPassword);


                    sSQL = string.Format(sQuery,
                                         m_cPosStatus.Base.CmpCd,
                                         m_cPosStatus.Base.SaleDate,
                                         m_cPosStatus.Base.StoreNo,
                                         m_cPosStatus.Base.PosNo,
                                         HPORD_HEADER.OrderNum,
                                         HPORD_TOBESTATUS,
                                         HPORD_HEADER.OrderStatus,
                                         HPORD_HEADER.OrderType,
                                         HPORD_CLOUDRES,
                                         "P",
                                         m_cPosStatus.Base.CashierNo,
                                         "0",
                                         "",
                                         DateTime.Now.ToString("yyyyMMddHHmmss"));

                    m_cSqlDbService.DBExecuteNonQuery(new string[] { sSQL }, true);


                    //#20180914 해피오더 자동출하 로그 추가 start
                    UserLog.WriteLogFile(UserCom.LOG_IOS,
                                         System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                         System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                         System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                         "자동출하데이터저장 end" + "[" + sSQL + "]");
                    //#20180914 해피오더 자동출하 로그 추가 end
                }
                catch (Exception ex)
                {
                    UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                         System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                         System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                         System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                         ex.Message + "[" + sSQL + "]");
                }
            }
            finally
            {
                m_cSqlDbService.Close();
            }
        }
        #endregion

        //#15945 해피오더 자동주문 상세기능 end

        //#17143 [해피오더]자동 주문 처리 개선 start
        #region 기존소스 HappyOrder_AutomaticShipmentItemCheck
        /*
        //#15945 해피오더 자동주문 상세기능 start
        #region HappyOrder_AutomaticShipmentItemCheck
        public bool HappyOrder_AutomaticShipmentItemCheck(ArrayList HappyOrderItem, string HappyOrderStatus, out bool DivYN)
        {
            bool bRet = false;
            bool bDivYN = false;
            try
            {
                //#16401 해피오더)주문내역 바코드 리딩 시 자동 완료처리 start
                string sOrderNum = "";
                //#16401 해피오더)주문내역 바코드 리딩 시 자동 완료처리 end

                bool bX = false;
                bool bY = false;

                for (int nLoop = 0; nLoop < HappyOrderItem.Count; nLoop++)
                {
                    Column.TR_HPORD.HPORD_ITEM item = (Column.TR_HPORD.HPORD_ITEM)HappyOrderItem[nLoop];

                    DataTable dtData = m_cDataCommon.AutomaticShipmentItemCheck(m_cPosStatus.Base.SubShopNo, item.GoodsCode);

                    sOrderNum = item.OrderNum;

                    string sAutomaticShipmentItem = "";
                    if (dtData != null && dtData.Rows.Count > 0)
                    {
                        DataRow dr = dtData.Rows[0];
                        sAutomaticShipmentItem = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM.DATA.ITEM_PROD_TYPE_YN);
                    }

                    // Y: 제조상품, N:완제상품, 공백:기타 
                    if (sAutomaticShipmentItem == "N")
                    {
                        bX = true;
                    }
                    else if (sAutomaticShipmentItem == "Y")
                    {
                        bY = true;
                    }
                }

                //#16401 해피오더)주문내역 바코드 리딩 시 자동 완료처리 start
                UserLog.WriteLogFile(UserCom.LOG_IOS,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "[자동 완료처리 주문번호 :" + sOrderNum + "] ");
                //#16401 해피오더)주문내역 바코드 리딩 시 자동 완료처리 end

                //#20180914 해피오더 자동출하 로그 추가 start
                UserLog.WriteLogFile(UserCom.LOG_IOS,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "X 자동출하조건체크 :" + bX.ToString() + "Y 자동출하조건체크 :" + bY.ToString());
                //#20180914 해피오더 자동출하 로그 추가 end

                string sMsg = "";

                if (bX == true)
                {
                    if (bY == true)
                    {
                        // 완제품 + 이 외의 제품이 존재할 때
                        sMsg = MessageManager.GetGuideMessage(POS_MESSAGE.GUIDE.MSG_0019);

                    }
                    else
                    {
                        // 완제품만 존재할 때 
                        sMsg = MessageManager.GetGuideMessage(POS_MESSAGE.GUIDE.MSG_0018);
                    }

                    //#20180914 해피오더 자동출하 로그 추가 start
                    UserLog.WriteLogFile(UserCom.LOG_IOS,
                                         System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                         System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                         System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                         "자동출하안내팝업 :" + sMsg.Trim());
                    //#20180914 해피오더 자동출하 로그 추가 end

                    //해피오더 자동출하 건 
                    //#15945 해피오더 자동주문 상세기능 start - 20180820
                    //기존
                    //bRet = WinManager.AutomaticShipmentQuestionMessage(sMsg, HappyOrderStatus);
                    //변경
                    DialogResult dRet = WinManager.AutomaticShipmentQuestionMessage(sMsg, HappyOrderStatus);

                    if (dRet == DialogResult.Yes)
                    {
                        //예
                        bRet = true;
                        bDivYN = true;
                    }
                    else if (dRet == DialogResult.No)
                    {
                        //아니오
                        bRet = false;
                        bDivYN = true;
                    }
                    else
                    {
                        //닫기
                        bRet = false;
                        bDivYN = false;
                    }
                    //#15945 해피오더 자동주문 상세기능 end - 20180820
                }
                else
                {
                    // 점포제조제품만 존재
                    if (m_cPosStatus.Mst.CorpDiv == ItemConst.CORP_DIV.PC)
                    {
                        sMsg = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0591);
                    }
                    else
                    {
                        sMsg = string.Format(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0482), HappyOrderStatus);
                    }

                    //#20180914 해피오더 자동출하 로그 추가 start
                    UserLog.WriteLogFile(UserCom.LOG_IOS,
                                         System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                         System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                         System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                         "자동출하안내팝업 :" + sMsg.Trim());
                    //#20180914 해피오더 자동출하 로그 추가 end

                    // 해피오더 일반주문 건 
                    bDivYN = false;
                    bRet = WinManager.QuestionMessage(sMsg, HappyOrderStatus);
                }

                //#20180914 해피오더 자동출하 로그 추가 start
                UserLog.WriteLogFile(UserCom.LOG_IOS,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "자동출하저장여부 :" + bDivYN.ToString() + "(true: 저장/ false:미저장)");
                //#20180914 해피오더 자동출하 로그 추가 end

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

                DivYN = bDivYN;
            }
            return bRet;
        }
        #endregion
        //#15945 해피오더 자동주문 상세기능 end
        */
        #endregion

        #region 변경소스 HappyOrder_AutomaticShipmentItemCheck
        
        public bool HappyOrder_AutomaticShipmentItemCheck(ArrayList HappyOrderItem, string HappyOrderStatus, string OrderData, string PickupData, out bool AutomaticShipment)
        {
            bool bAnswer = false; // 고객 동의 여부 
            bool bAutomaticShipment = false; // 자동출하여부 

            try
            {
                
                bool bX = false;
                bool bY = false;
                bool bSecondTarget = false; // true 2차대상상품건 --> 제한상품체크해야함.
                bool bLimitedItemCheck = true; // true 제한상품만있음 --> 자동주문처리안함.
                bool bDataCheck = true; // true 데이터체크, false 데이터체크안함

                string sOrderNum = "";
                string sOrderData = OrderData; // 해피오더 주문일자
                string sPickupData = PickupData; // 해피오더 픽업일자 

                //#17143 [해피오더]자동 주문 처리 개선 start 20181106
                string sNowData = "";
                //#17143 [해피오더]자동 주문 처리 개선 end 20181106

                sOrderData = OrderData.Substring(0, 4) + OrderData.Substring(5, 2) + OrderData.Substring(8, 2);
                sPickupData = PickupData.Substring(0, 4) + PickupData.Substring(5, 2) + PickupData.Substring(8, 2);
                
                //#17143 [해피오더]자동 주문 처리 개선 start 20181106
                sNowData = DateTime.Now.ToString("yyyyMMdd");
                //#17143 [해피오더]자동 주문 처리 개선 end 20181106

                UserLog.WriteLogFile(UserCom.LOG_IOS,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     //#17143 [해피오더]자동 주문 처리 개선 start 20181106
                                     //기존
                                     //"픽업일자 :" + sPickupData + "주문일자 :" + sOrderData + "시스템일자 :" + sNowData);
                                     //변경
                                     "픽업일자 :" + sPickupData + "주문일자 :" + sOrderData + "시스템일자 :" + sNowData);
                                     //#17143 [해피오더]자동 주문 처리 개선 end 20181106
                
                //#17143 [해피오더]자동 주문 처리 개선 start 20181106
                //기존
                //if (sOrderData == sPickupData || int.Parse(sOrderData) > int.Parse(sPickupData))
                //변경
                if (int.Parse(sPickupData) <= int.Parse(sNowData))
                //#17143 [해피오더]자동 주문 처리 개선 end 20181106
                {
                    // 주문일자, 픽업일자가 같은 건이거나
                    // 픽업일자보다 주문일자가 더 크면 자동주문처리 안함.
                    bDataCheck = false;
                }
                else
                {
                    // 주문일자,픽업일자 차이가 1일이면 2차대상상품 건, 2일이면 1차대상상품 건으로 간주.
                    // 2차대상상품 건이면 제한상품인지 체크한다.  (mst_item의 EXE_HPORD : y 대상상품제외, n 대상상품제외아님)
                    // bSecondTarget이 true : 2차대상상품, false : 1차대상상품

                    //날짜의 차이 구하기
                    int iDayTerm = 0;

                    //#17143 [해피오더]자동 주문 처리 개선 start 20181106
                    //기존
                    /*
                    DateTime dt_OrderData = DateTime.Parse(OrderData);
                    DateTime dt_PickupData = DateTime.Parse(PickupData);
                    TimeSpan TS = dt_PickupData - dt_OrderData;
                    iDayTerm = TS.Days;
                    */
                    //변경

                    //#17143 [해피오더]자동 주문 처리 개선 start 20181106, 20181108
                    sNowData = sNowData.Substring(0, 4) + "-" + sNowData.Substring(4, 2) + "-" + sNowData.Substring(6, 2);
                    //#17143 [해피오더]자동 주문 처리 개선 end 20181106, 20181108

                    DateTime dt_NowData = DateTime.Parse(sNowData);
                    DateTime dt_PickupData = DateTime.Parse(PickupData);
                    TimeSpan TS = dt_PickupData - dt_NowData;
                    iDayTerm = TS.Days;
                    //#17143 [해피오더]자동 주문 처리 개선 end 20181106

                    if (Math.Abs(iDayTerm) == 1) { bSecondTarget = true; }

                    for (int nLoop = 0; nLoop < HappyOrderItem.Count; nLoop++)
                    {
                        Column.TR_HPORD.HPORD_ITEM item = (Column.TR_HPORD.HPORD_ITEM)HappyOrderItem[nLoop];

                        DataTable dtData = m_cDataCommon.AutomaticShipmentItemCheck(m_cPosStatus.Base.SubShopNo, item.GoodsCode);

                        sOrderNum = item.OrderNum;

                        string sAutomaticShipmentItem = "";
                        string sAutomaticShipmentLimitItem = "";

                        if (dtData == null || dtData.Rows.Count == 0)
                        {
                            UserLog.WriteLogFile(UserCom.LOG_IOS,
                                                 System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                                 System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                                 System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                                 "MST_ITEM 없는 데이터 --> 상품코드 :" + item.GoodsCode + " , 상품명 :" + item.GoodsName + " , 주문번호 :" + item.OrderNum);

                            continue;
                        }

                        DataRow dr = dtData.Rows[0];
                        sAutomaticShipmentItem = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM.DATA.ITEM_PROD_TYPE_YN);
                        sAutomaticShipmentLimitItem = CmUtil.GetDataRowStr(dr, PosMst.MST_ITEM.DATA.EXE_HPORD);

                        // Y: 제조상품, N:완제상품, 공백:기타 
                        if (sAutomaticShipmentItem == "N")
                        {
                            bX = true;
                        }
                        else
                        {
                            bY = true;
                        }

                        // Y: 제한상품, N: 제한상품아님
                        if (sAutomaticShipmentLimitItem != "Y")
                        {
                            bLimitedItemCheck = false;
                        }
                    }
                }

                UserLog.WriteLogFile(UserCom.LOG_IOS,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "자동출하 데이터체크 :" + bDataCheck.ToString() + " --> true 주문일자와 픽업일자 다르고, 주문일자가 픽업일자보다 이 전일때");
                UserLog.WriteLogFile(UserCom.LOG_IOS,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "자동출하 주문번호 :" + sOrderNum);
                UserLog.WriteLogFile(UserCom.LOG_IOS,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "자동출하 2차대상상품여부 :" + bSecondTarget.ToString() + " --> true 주문일자와 픽업일자가 차이가 하루일 때");
                UserLog.WriteLogFile(UserCom.LOG_IOS,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "자동출하 제한상품묶음여부 :" + bLimitedItemCheck.ToString() + " --> true 제한상품만있음, 자동주문처리안함");
                UserLog.WriteLogFile(UserCom.LOG_IOS,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "자동출하 조건체크 X:" + bX.ToString() + ", Y:" + bY.ToString());

                string sMsg = "";

                if (bX == true &&   // 완제품 존재여부 
                    (bSecondTarget == false || bLimitedItemCheck == false) &&  // bSecondTarget 픽업일자, 주문일자 차이가 하루인지 체크. bLimitedItemCheck 2차대상제한상품만 있는지 체크.
                    (bDataCheck == true)) // 픽업일자가 주문일자보다 클때 true             
                {

                    //#17651 해피오더)자동주문 시 표시문구 변경 start
                    //기존
                    /*
                    if (bY == true)
                    {
                        // 완제품 + 이 외의 제품이 존재할 때
                        sMsg = MessageManager.GetGuideMessage(POS_MESSAGE.GUIDE.MSG_0019);

                    }
                    else
                    {
                        // 완제품만 존재할 때 
                        sMsg = MessageManager.GetGuideMessage(POS_MESSAGE.GUIDE.MSG_0018);
                    }
                    */
                    //변경
                    string sCommCode = "";
                    string sStartDate = "";// 시작일자
                    string sEndDate = "";// 종료일자
                    string sDisplayMsgCode = "";// 디스플레이코드
                    string sDisplayMsgType = "";// 디스플레이타입

                    if (bY == true)
                    {
                        // 완제품 + 이 외의 제품이 존재할 때
                        sCommCode = "1";

                    }
                    else
                    {
                        // 완제품만 존재할 때 
                        sCommCode = "2";
                    }

                    DataTable dtData = m_cDataCommon.SeletCommonCode(PosConst.COMMON_CODE_GROUP.T0043, sCommCode);
                    if (dtData != null && dtData.Rows.Count > 0)
                    {
                        DataRow dr = dtData.Rows[0];
                        sStartDate = CmUtil.GetDataRowStr(dr, PosMst.MST_COMMON.DATA.CHAR_VAL_TITLE_VAL_01);
                        sEndDate = CmUtil.GetDataRowStr(dr, PosMst.MST_COMMON.DATA.CHAR_VAL_TITLE_VAL_02);
                        sDisplayMsgCode = CmUtil.GetDataRowStr(dr, PosMst.MST_COMMON.DATA.CHAR_VAL_TITLE_VAL_03);
                        sDisplayMsgType = CmUtil.GetDataRowStr(dr, PosMst.MST_COMMON.DATA.CHAR_VAL_TITLE_VAL_04);
                    }

                    sNowData = sNowData.Substring(0, 4) + sNowData.Substring(5, 2) + sNowData.Substring(8, 2);

                    if ((sStartDate != "" && sEndDate != "" && sDisplayMsgCode != "" && sDisplayMsgType != "") &&
                        (int.Parse(sStartDate) <= int.Parse(sNowData) && int.Parse(sNowData) <= int.Parse(sEndDate)))
                    {
                        if (sDisplayMsgType == "1")
                        {
                            sMsg = MessageManager.GetLabelMessage(sDisplayMsgCode);
                        }
                        else if (sDisplayMsgType == "2")
                        {
                            sMsg = MessageManager.GetErrorMessage(sDisplayMsgCode);
                        }
                        else if (sDisplayMsgType == "3")
                        {
                            sMsg = MessageManager.GetGuideMessage(sDisplayMsgCode);
                        }
                        else if (sDisplayMsgType == "4")
                        {
                            sMsg = MessageManager.GetPrintMessage(sDisplayMsgCode);
                        }
                        else if (sDisplayMsgType == "5")
                        {
                            sMsg = MessageManager.GetExactMessage(sDisplayMsgCode);
                        }
                    }
                    else
                    {
                        if (bY == true)
                        {
                            // 완제품 + 이 외의 제품이 존재할 때
                            sMsg = MessageManager.GetGuideMessage(POS_MESSAGE.GUIDE.MSG_0019);

                        }
                        else
                        {
                            // 완제품만 존재할 때 
                            sMsg = MessageManager.GetGuideMessage(POS_MESSAGE.GUIDE.MSG_0018);
                        }
                    }
                    //#17651 해피오더)자동주문 시 표시문구 변경 end
                    


                    DialogResult dRet = WinManager.AutomaticShipmentQuestionMessage(sMsg, HappyOrderStatus);
                    if (dRet == DialogResult.Yes)
                    {
                        //예
                        bAnswer = true;
                        bAutomaticShipment = true;
                    }
                    else if (dRet == DialogResult.No)
                    {
                        //아니오
                        bAnswer = false;
                        bAutomaticShipment = true;
                    }
                    else
                    {
                        //닫기
                        bAnswer = false;
                        bAutomaticShipment = false;
                    }
                }
                else
                {
                    // 점포제조제품만 존재
                    if (m_cPosStatus.Mst.CorpDiv == ItemConst.CORP_DIV.PC)
                    {
                        sMsg = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0591);
                    }
                    else
                    {
                        sMsg = string.Format(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0482), HappyOrderStatus);
                    }

                    // 해피오더 일반주문 건 
                    bAutomaticShipment = false;
                    bAnswer = WinManager.QuestionMessage(sMsg, HappyOrderStatus);
                }

                AutomaticShipment = bAutomaticShipment;

                UserLog.WriteLogFile(UserCom.LOG_IOS,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",
                                     "자동출하 저장여부 :" + bAutomaticShipment.ToString() + "(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);
                bAnswer = false;
                AutomaticShipment = false;
            }
            return bAnswer;
        }
       
        #endregion
        //#17143 [해피오더]자동 주문 처리 개선 end

        //#16366 해피오더 당월누적주문내역 + 당일 해피오더주문 상세내역 자동 출력기능 start
        #region 당월누적주문내역 API 통신

        public bool HappyOrderToMonthPrint(bool bHPOAutoPrintYN)
        {
            // 당월 누계 건 출력
            bool bRet = false;
            try
            {
                //API 통신
                string sVanCD = PosMstManager.GetMstPayDc(ItemConst.TR_ITEM_ID.ORDER_ITEM, ItemConst.TR_ITEM_ID.ORDER.HAPPYORDER_PAY, PosMst.MST_PAY_DC.DATA.APPR_VEND_CD);// 해피오더 승인업체 코드 조회
                string sHappyOrderURL = PosMstManager.GetMstVan(sVanCD, PosMst.MST_VAN.DATA.IP);// 해피오더 승인 URL 조회

                if (sHappyOrderURL == "") return bRet;

                Hashtable htRequest = null;
                htRequest = new Hashtable();
                htRequest.Clear();
                Hashtable htResponse = null;
                htResponse = new Hashtable();
                htResponse.Clear();

                htRequest.Add("storeCode", m_cPosStatus.Base.StoreNo);

                int iReturn = BaseCom.NG;

                Hashtable m_htOrder = null;
                m_htOrder = SendReceiveForHappyOrder2(new object[] { sHappyOrderURL, ItemConst.HAPPYORDER_WORK_TYPE.SELECT_MONTH_COUNT, htRequest }, ref htResponse, ref iReturn);

                if (iReturn != BaseCom.OK) { return bRet; }
                if (m_htOrder == null || m_htOrder.Count <= 0) return bRet;
                if (htResponse == null || htResponse.ContainsKey("status") == false)
                {
                    UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                        System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                        System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                        "당월누계 데이터 조회, 실패");

                    //WinManager.ConfirmMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0005));
                    bRet = false;
                }

                if (htResponse["status"].ToString().Equals("200") == false)
                {
                    UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                        System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                        System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                        "당월누계 데이터 조회, 실패 :" + htResponse["message"].ToString());

                    //WinManager.ConfirmMessage(htResponse["message"].ToString());
                    bRet = false;
                }
                else
                {
                    UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                        System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                        System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                        "당월누계 데이터 조회, 성공");

                    //WinManager.ConfirmMessage(string.Format(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0487), "당월누계 데이터 조회"));
                    bRet = true;
                }

                if (bRet == true)
                {
                    //영수증 출력
                    bRet = HappyOrderToMonthPrintSheet(m_htOrder, bHPOAutoPrintYN);
                }
            }
            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 당월누적주문내역 영수증 출력
        
        /// <summary>
        /// 당월 누계 건 영수증 포맷 
        /// </summary>
        private bool HappyOrderToMonthPrintSheet(Hashtable htHappyOrderMonthPrt, bool bHPOAutoPrintYN)
        {
            bool bRet = false;
            try
            {
                if (htHappyOrderMonthPrt == null || htHappyOrderMonthPrt.Count <= 0) { return bRet; }

                Column.TR_HPORD.HPORD_MONTHPRT HappyOrderMonthPrt = new Column.TR_HPORD.HPORD_MONTHPRT();
                HappyOrderMonthPrt.pickupOrderCnt = htHappyOrderMonthPrt["pickupOrderCnt"] == null ? string.Empty : htHappyOrderMonthPrt["pickupOrderCnt"].ToString(); // 픽업) 취소 주문은 제외한 주문 카운트
                HappyOrderMonthPrt.pickupSalePriceTot = htHappyOrderMonthPrt["pickupSalePriceTot"] == null ? string.Empty : htHappyOrderMonthPrt["pickupSalePriceTot"].ToString(); // 픽업) 상품 할인 금액을 포함한 실판매가 합계
                HappyOrderMonthPrt.pickupOrgPriceTot = htHappyOrderMonthPrt["pickupOrgPriceTot"] == null ? string.Empty : htHappyOrderMonthPrt["pickupOrgPriceTot"].ToString(); // 픽업) 상품 할인 금액을 제외한 원가 합계
                HappyOrderMonthPrt.deliveryOrderCnt = htHappyOrderMonthPrt["deliveryOrderCnt"] == null ? string.Empty : htHappyOrderMonthPrt["deliveryOrderCnt"].ToString(); // 배달) 취소 주문은 제외한 주문 카운트
                HappyOrderMonthPrt.deliverySalePriceTot = htHappyOrderMonthPrt["deliverySalePriceTot"] == null ? string.Empty : htHappyOrderMonthPrt["deliverySalePriceTot"].ToString(); // 배달) 상품 할인 금액을 포함한 실판매가 합계
                HappyOrderMonthPrt.deliveryOrgPriceTot = htHappyOrderMonthPrt["deliveryOrgPriceTot"] == null ? string.Empty : htHappyOrderMonthPrt["deliveryOrgPriceTot"].ToString(); ; // 배달) 상품 할인 금액을 제외한 원가 합계


                PrintBufClear();
                AddPrintData(PosConst.PRT_HDR.PRT_VER, PosConst.PRT_FMT.F103, m_cPosStatus.Mst.StorName + " 해피오더 주문내역");
                AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, "");
                AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, "발행일자 :" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, "당월누계");
                AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, "1) 픽업 :" + string.Format("주문 {0}건", HappyOrderMonthPrt.pickupOrderCnt) + string.Format(", 매출 {0}원", HappyOrderMonthPrt.pickupSalePriceTot));
                AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, "2) 배달 :" + string.Format("주문 {0}건", HappyOrderMonthPrt.deliveryOrderCnt) + string.Format(", 매출 {0}원", HappyOrderMonthPrt.deliverySalePriceTot));
                AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, "-");

                ArrayList alPrintData = null;
                alPrintData = GetPrintBufferData();

                bRet = PrintOrderSheet("M", bHPOAutoPrintYN);
            }
            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 해피오더 당일픽업 API 통신
        
        /// <summary>
        /// 해피오더 오늘 픽업/배달 주문서출력 처리
        /// </summary>
        public bool HappyOrderTodayPrint(bool bHPOAutoPrintYN)
        {
            bool bRet = false;
            try
            {
                string sVanCD = "";
                string sHappyOrderUrl = "";
                sVanCD = PosMstManager.GetMstPayDc(ItemConst.TR_ITEM_ID.ORDER_ITEM, ItemConst.TR_ITEM_ID.ORDER.HAPPYORDER_PAY, PosMst.MST_PAY_DC.DATA.APPR_VEND_CD); // 승인업체 코드 조회
                sHappyOrderUrl = PosMstManager.GetMstVan(sVanCD, PosMst.MST_VAN.DATA.IP); // 승인 URL 조회

                //====================================================================
                Hashtable htRequest = null;
                htRequest = new Hashtable();
                htRequest.Clear();

                if (bHPOAutoPrintYN == true)
                {
                    htRequest.Add("storeCode", m_cPosStatus.Base.StoreNo);
                    htRequest.Add("status", ItemConst.HAPPYORDER_STATUS.ORDER_REG);
                    htRequest.Add("deviceType", "POS");
                    htRequest.Add("orderDate", DateTime.Now.ToString("yyyyMMdd"));
                    //htRequest.Add("orderDate", "20180619");
                }
                else
                {
                    htRequest.Add("storeCode", m_cPosStatus.Base.StoreNo);
                    htRequest.Add("status", ItemConst.HAPPYORDER_STATUS.ORDER_REG);
                    htRequest.Add("deviceType", "POS");
                }
                //====================================================================
                int iReturn = BaseCom.NG;

                Hashtable htResponse = null;
                htResponse = new Hashtable();
                htResponse.Clear();

                Hashtable[] htOrderLists = null;
                htOrderLists = SendReceiveForHappyOrder(new object[] { sHappyOrderUrl, ItemConst.HAPPYORDER_WORK_TYPE.SELECT_ORDER_LIST, htRequest }, ref htResponse, ref iReturn);

                //====================================================================
                ArrayList cHappyOrderHeader = null;
                cHappyOrderHeader = new ArrayList();
                cHappyOrderHeader.Clear();
                if (htOrderLists != null && htOrderLists.Length > 0)
                {
                    foreach (Hashtable htData in htOrderLists)
                    {
                        // 해피오더 주문 리스트 조회 및 저장
                        Column.TR_HPORD.HPORD_HEADER header = null;
                        header = ParseHappyOrderList(htData);
                        cHappyOrderHeader.Add(header);
                    }
                }

                //====================================================================
                bool bValue = false;
                string sMessage = "";
                if (cHappyOrderHeader == null || cHappyOrderHeader.Count <= 0)
                {
                    sMessage = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0513); // 오늘 픽업/배달 주문서 출력 건 없을 경우 안내 POP-UP
                    bValue = false;
                }
                else
                {
                    sMessage = MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0514); // 접수된 주문에 대한 안내 POP-UP
                    bValue = true;
                }
                // bHPOAutoPrintYN (true: 해피오더 당일픽업 건 영수증 자동출력기능, false: 해피오더 당일픽업 건 영수증 자동 미출력 기능)
                // 해피오더 당일픽업 자동 영수증 출력 기능일 때 메세지 팝업 띄우지 않는다.
                if (bHPOAutoPrintYN == false)
                {
                    WinManager.ConfirmMessage(sMessage);
                }

                if (bValue == true)
                {
                    int iTotalCnt = cHappyOrderHeader.Count;
                    int iCompletedCnt = 0;

                    // 주문번호 별 Loop
                    for (int nLoop = 0; nLoop < cHappyOrderHeader.Count; nLoop++)
                    {
                        bool bReturn = false;

                        ArrayList cHappyOrderItem = new ArrayList();

                        Hashtable[] htOrderDetails = null;

                        Column.TR_HPORD.HPORD_HEADER header = (Column.TR_HPORD.HPORD_HEADER)cHappyOrderHeader[nLoop];
                        string sOrderNum = header.OrderNum;

                        GetHappyOrderListDetail(sOrderNum, sHappyOrderUrl, ref cHappyOrderItem, ref htOrderDetails); // 해피오더 주문 상세 조회

                        bReturn = HappyOrderTodayPrintSheet(sOrderNum, bHPOAutoPrintYN, ref cHappyOrderHeader, ref cHappyOrderItem);

                        if (bHPOAutoPrintYN == true)
                        {
                            System.Threading.Thread.Sleep(3000);
                        }
                        else
                        {
                            //#17141 [해피오더]배달영수증 주소 추가 start
                            //기존
                            //System.Threading.Thread.Sleep(1000);
                            //변경
                            System.Threading.Thread.Sleep(3000);
                            //#17141 [해피오더]배달영수증 주소 추가 end
                        }
                        
                        if (bReturn == true) { iCompletedCnt++; }
                    }

                    bRet = true;

                    if (bRet == true && bHPOAutoPrintYN == false)
                    {
                        WinManager.ConfirmMessage(string.Format(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0515), iTotalCnt, iCompletedCnt, (iTotalCnt - iCompletedCnt)));
                    }
                }
            }
            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 해피오더 당일픽업 주문서출력 처리
       
        /// <summary>
        /// 해피오더 오늘 픽업/배달 주문서 출력
        /// </summary>
        /// <param name="sOrderNum"></param>
        /// <param name="cHappyOrderHeader"></param>
        /// <param name="cHappyOrderItem"></param>
        /// <returns></returns>
        private bool HappyOrderTodayPrintSheet(string sOrderNum, bool bHPOAutoPrintYN, ref ArrayList cHappyOrderHeader, ref ArrayList cHappyOrderItem)
        {
            bool bReturn = false;
            try
            {
                PrintBufClear();

                if (bHPOAutoPrintYN == true)
                {
                    AddPrintData(PosConst.PRT_HDR.PRT_VER, PosConst.PRT_FMT.F103, "[ 해피오더 제품부착용 ]");
                }
                else
                {
                    AddPrintData(PosConst.PRT_HDR.PRT_VER, PosConst.PRT_FMT.F103, "[ 해피오더 주문내역 ]");
                }

                AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, " ");


                Column.TR_HPORD.HPORD_HEADER header;

                for (int i = 0; i < cHappyOrderHeader.Count; i++)
                {
                    if (((Column.TR_HPORD.HPORD_HEADER)cHappyOrderHeader[i]).OrderNum != sOrderNum)
                    {
                        continue;
                    }

                    header = (Column.TR_HPORD.HPORD_HEADER)cHappyOrderHeader[i];

                    if (header.OrderStatus == ItemConst.HAPPYORDER_STATUS.PICKUP_COMPLETED)
                    {
                        AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F103, "[ 픽업 완료 ]");
                        AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, " ");
                    }
                    if (header.OrderStatus == ItemConst.HAPPYORDER_STATUS.ORDER_CANCEL)
                    {
                        AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F103, "[ 주문 취소 ]");
                        AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, " ");
                    }

                    AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, " 픽업시간 : " + header.PickupTime);
                    AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, " 주문번호 : " + header.OrderNum);
                    AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, " 주문일시 : " + header.OrderDate);
                    AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, " 연 락 처 : " + header.ReceiverHp);
                    AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, "-");
                    AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, "   ITEM                     QTY        AMT");
                    AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, "-");

                    //#17332 해피오더)주문서에 상세금액 추가 start
                    
                    int iTotPrice = 0;//총매출액
                    int iTotDiscountPrice = 0;//총할인금액
                    int iOrderPrice = 0;//총합계금액(매출액-할인금액)
                    int iPayPrice = 0;//총받은금액(결제금액)

                    iPayPrice = int.Parse(header.PayMoney);
                    
                    //#17332 해피오더)주문서에 상세금액 추가 end

                    for (int nLoop = 0; nLoop < cHappyOrderItem.Count; nLoop++)
                    {
                        Column.TR_HPORD.HPORD_ITEM item = (Column.TR_HPORD.HPORD_ITEM)cHappyOrderItem[nLoop];
                        int itemPrice = 0;
                        int itemQty = 0;
                        int itemDiscountPrice = 0;

                        itemPrice = int.Parse(item.SupplyPrice.Trim() == "" ? "0" : item.SupplyPrice.Trim());
                        itemQty = int.Parse(item.Qty.Trim() == "" ? "0" : item.Qty.Trim());
                        itemDiscountPrice = int.Parse(item.DiscountPrice.Trim() == "" ? "0" : item.DiscountPrice.Trim());

                        //#17332 해피오더)주문서에 상세금액 추가 start
                        
                        iTotPrice += itemPrice * itemQty;//총매출금액
                        iTotDiscountPrice += itemDiscountPrice * itemQty;//총할인금액
                        iOrderPrice += (itemPrice * itemQty) - (itemDiscountPrice * itemQty);//총합계금액
                        
                        //#17332 해피오더)주문서에 상세금액 추가 end

                        if (CmUtil.StringNullEmpty(item.FlavourFlag).Equals("N") == false)
                        {
                            //#15485 PB 강남일원 - 제품명이 길어 짤리는 증상 수정 요청 start
                            // 기존
                            //if (PosMstManager.GetPosOption(POS_OPTION.OPT414) == "2")
                            // 변경
                            if (PosMstManager.GetPosOption(POS_OPTION.OPT433) == "2")
                            //#15485 PB 강남일원 - 제품명이 길어 짤리는 증상 수정 요청 end
                            {
                                AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, " >" + CmUtil.RPadH(item.GoodsName, 40));

                                AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, CmUtil.RPadH("", 27) +
                                             CmUtil.LPadH(item.Qty, 4) +
                                             CmUtil.LPadH(CmUtil.GetToMoney(Convert.ToString((itemPrice - itemDiscountPrice) * itemQty)), 11));
                            }
                            else
                            {
                                AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101,
                                             " >" + CmUtil.RPadH(item.GoodsName, 25) +
                                             CmUtil.LPadH(item.Qty, 4) +
                                             CmUtil.LPadH(CmUtil.GetToMoney(Convert.ToString((itemPrice - itemDiscountPrice) * itemQty)), 11));
                            }
                        }
                        else
                        {
                            //#15485 PB 강남일원 - 제품명이 길어 짤리는 증상 수정 요청 start
                            // 기존
                            //if (PosMstManager.GetPosOption(POS_OPTION.OPT414) == "2")
                            // 변경
                            if (PosMstManager.GetPosOption(POS_OPTION.OPT433) == "2")
                            //#15485 PB 강남일원 - 제품명이 길어 짤리는 증상 수정 요청 end
                            {
                                AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, CmUtil.RPadH(item.GoodsName, 42));

                                AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, CmUtil.RPadH("", 27) +
                                             CmUtil.LPadH(item.Qty, 4) +
                                             CmUtil.LPadH(CmUtil.GetToMoney(Convert.ToString((itemPrice - itemDiscountPrice) * itemQty)), 11));
                            }
                            else
                            {
                                AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101,
                                             CmUtil.RPadH(item.GoodsName, 27) +
                                             CmUtil.LPadH(item.Qty, 4) +
                                             CmUtil.LPadH(CmUtil.GetToMoney(Convert.ToString((itemPrice - itemDiscountPrice) * itemQty)), 11));
                            }
                        }
                    }




                    //#17332 해피오더)주문서에 상세금액 추가 start

                    #region 기존소스
                    /*
                    AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, "-");
                    AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, " 합계금액                      " + CmUtil.LPadH(CmUtil.GetToMoney(header.PayMoney), 11));
                    AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, " ");
                    */
                    #endregion 기존소스

                    #region 변경소스
                   
                    AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, "-");
                    AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, " 총매출액                      " + CmUtil.LPadH(CmUtil.GetToMoney(iTotPrice.ToString()), 11));
                    AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, " 할인금액                      " + CmUtil.LPadH(CmUtil.GetToMoney(iTotDiscountPrice.ToString()), 11));
                    AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, " 합계금액                      " + CmUtil.LPadH(CmUtil.GetToMoney(iOrderPrice.ToString()), 11));
                    AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, " 받은금액                      " + CmUtil.LPadH(CmUtil.GetToMoney(iPayPrice.ToString()), 11));
                    AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, " ");
                    
                    #endregion 변경소스

                    //#17332 해피오더)주문서에 상세금액 추가 end 

                    if (header.CustMsg != string.Empty)
                    {
                        AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, "************** 고객요청사항 **************");
                        AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, header.CustMsg);
                        AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, "*");
                    }

                    //#17141 [해피오더]배달영수증 주소 추가 start
                    if (header.OrderType == "5" || header.OrderType == "4")
                    {
                        string sVanCD = PosMstManager.GetMstPayDc(ItemConst.TR_ITEM_ID.ORDER_ITEM, ItemConst.TR_ITEM_ID.ORDER.HAPPYORDER_PAY, PosMst.MST_PAY_DC.DATA.APPR_VEND_CD); // 해피오더 승인업체 코드 조회
                        string sHappyOrderURL = PosMstManager.GetMstVan(sVanCD, PosMst.MST_VAN.DATA.IP); // 해피오더 승인 URL 조회 
                        
                        Hashtable htRequestForNutrition = new Hashtable();
                        htRequestForNutrition.Clear();
                        htRequestForNutrition.Add("orderNum", header.OrderNum);

                        int iReturn = BaseCom.NG;
                        Hashtable htResponse = null;
                        Hashtable[] aResponse = null; 
                        aResponse = SendReceiveForHappyOrder(new object[] { sHappyOrderURL, ItemConst.HAPPYORDER_WORK_TYPE.SELECT_PRODUCT_NUTRITION, htRequestForNutrition }, ref htResponse, ref iReturn);
                        if (aResponse != null && aResponse.Length > 0)
                        {
                            string sMsg = ParseNutritionMsg(aResponse);
                            if (sMsg != "")
                            {
                                AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, "-");
                                AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, sMsg);
                                AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, "-");
                            }
                        }

                        AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, " [배송지 정보]");
                        string sRecviver = string.Format("{0}{1}{2}", CmUtil.LeftH(header.Receiver, 2), ((header.Receiver.Length > 2) ? new string('*', header.Receiver.Length - 2) : "*"), CmUtil.RightH(header.Receiver, 2));
                        string sRecviverAddress = header.Address1 + " " + ((header.Address2.Trim() == string.Empty) ? string.Empty : header.Address2);
                        //#17533 해피오더)영수증/주문서 전화번호 항목 추가 start
                        string sReceiverHp = header.ReceiverHp.Trim();
                        //#17533 해피오더)영수증/주문서 전화번호 항목 추가 end

                        AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, " " + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1189) + " : " + sRecviver);
                        //#17533 해피오더)영수증/주문서 전화번호 항목 추가 start
                        AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, " " + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0952) + " : " + sReceiverHp);
                        //#17533 해피오더)영수증/주문서 전화번호 항목 추가 end

                        //#17533 해피오더)영수증/주문서 전화번호 항목 추가 start
                        //기존
                        //AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, " " + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_1087) + " : " + sRecviverAddress);
                        //#17533 해피오더)영수증/주문서 전화번호 항목 추가 end
                        
                        AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, "-");
                    }
                    //#17141 [해피오더]배달영수증 주소 추가 end

                    AddPrintData(PosConst.PRT_HDR.PRT_BAR, "", "999"+header.OrderNum);
                    AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, " ");

                    ArrayList alPrintData = GetPrintBufferData();

                    // 주문서 출력
                    bReturn = PrintOrderSheet("D", bHPOAutoPrintYN);

                    if (bReturn == true)
                    {
                        if (bHPOAutoPrintYN == false)
                        {
                            // 해당 주문의 주문서 출력여부 Update
                            UpdateHappyOrderData(new string[] { "PRINT", "1", header.OrderNum, header.OrderDate.Substring(0, 10).Replace("-", "") });
                        }
                    }

                    System.Threading.Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR,
                                     System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,      // Project Name (프로젝트명)
                                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." +  // Class Name (Class Name (클래스명))
                                     System.Reflection.MethodBase.GetCurrentMethod().Name + "()",                // Function Name (Function Name (함수명))
                                     ex.Message);
            }
            return bReturn;
        }
        
        #endregion
        //#16366 해피오더 당월누적주문내역 + 당일 해피오더주문 상세내역 자동 출력기능 end
    }
}
