using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Data;

using Cosmos.Common;
using Cosmos.CommonManager;
using Cosmos.ServiceProvider;
using Cosmos.UserFrame;

namespace Cosmos.Service
{
    class SchReturnCompany : IDataServiceUs
    {
        #region 변수 선언
        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private PosStatus m_cPosStatus = new PosStatus();                           //기본정보 참조
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        protected IDataCommonUs m_cDataCommon = null;                               // 판매공통 모듈
        protected Column.POS_REQ_SERVER_INTERFACE.DATA m_cCustItem = null;

        private ArrayList aCustItem = null;
        private ArrayList m_sPrintData = null;
        private IPosPrinterUs m_cPrinterUs = null;
        #endregion 변수 선언

        #region 생성자 & 소멸자
        public SchReturnCompany()
        {
            m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
        }
        #endregion 생성자 & 소멸자

        /// <summary>
        /// 본사 반품 내역 조회
        /// </summary>
        /// <param name="aParam"></param>
        /// <returns></returns>
        public object GetData(string[] aParam)
        {
            //Hashtable dtDataInfo = null;
            string sRet = string.Empty;

            if (aParam[0] == "1")
            {
                // 내역조회
                sRet = SearchReturnCompanyList(aParam[1]);
                return sRet;
            }
            else
            {
                // 상세조회
                sRet = SearchReturnCompanyDetail(aParam[1], aParam[2], aParam[3]);
                if (sRet == UserCom.RST_OK)
                    return m_sPrintData;
                else
                    return null;
            }
        }

        /// <summary>
        /// 본사반품 조회 리스트
        /// </summary>
        /// <returns></returns>
        private string SearchReturnCompanyList(string sDateFrom)
        {
            string sRet = UserCom.RST_ERR;

            try
            {
                Hashtable htSendData = new Hashtable();
                Hashtable htRecvData = new Hashtable();

                //INQ_TYPE
                htSendData.Add("INQ_TYPE", ItemConst.IRT_INQ_TYPE.SERVER_INTERFACE_SCH);
                // STOR_CD
                htSendData.Add("STOR_CD", m_cPosStatus.Base.StoreNo);
                // POS_NO
                htSendData.Add("POS_NO", m_cPosStatus.Base.PosNo);
                // STOR_TY
                htSendData.Add("STOR_TY", "10");
                // PRT_DIV
                htSendData.Add("PRT_DIV", ItemConst.IRT_PRT_DIV.RETURN_COMPANY);
                // START_DT
                htSendData.Add("START_DT", sDateFrom);
                // END_DT
                htSendData.Add("END_DT", "");
                // ORD_SEQ
                htSendData.Add("ORD_SEQ", "");
                // ORD_GRP
                htSendData.Add("ORD_GRP", "");
                // DATA_CNT
                htSendData.Add("DATA_CNT", "0");
                // RES_DATA
                htSendData.Add("RES_DATA", "");

                sRet = m_cDataCommon.ExecutePosIrt(ItemConst.COMM_MSG_TYPE.POSIRT, m_cPosStatus.Base.CommSvrIp, (int)m_cPosStatus.Base.BizInqPort, 10000, htSendData, ref htRecvData);
                if (sRet != UserCom.RST_OK)
                {
                    WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0326));
                    sRet = UserCom.RST_ERR;
                    return sRet;
                }

                if (htRecvData["DATA_CNT"].ToString() != "0")
                {
                    return htRecvData["RES_DATA"].ToString();
                }
                else
                {
                    WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0302));
                    sRet = UserCom.RST_ERR;
                    return sRet;
                }
            }
            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 sRet;
        }

        /// <summary>
        /// 행사 주문 취합 내역 조회 상세(출력메세지)
        /// </summary>
        /// <returns></returns>
        private string SearchReturnCompanyDetail(string sDiv, string sDivNm, string sDateFrom)
        {
            string sRet = UserCom.RST_ERR;

            string[] sCol = null;
            string[] sRow = null;

            try
            {
                Hashtable htSendData = new Hashtable();
                Hashtable htRecvData = new Hashtable();

                m_sPrintData = new ArrayList();

                //INQ_TYPE
                htSendData.Add("INQ_TYPE", ItemConst.IRT_INQ_TYPE.SERVER_INTERFACE_SCH);
                // STOR_CD
                htSendData.Add("STOR_CD", m_cPosStatus.Base.StoreNo);
                // POS_NO
                htSendData.Add("POS_NO", m_cPosStatus.Base.PosNo);
                // STOR_TY
                htSendData.Add("STOR_TY", "10");
                // PRT_DIV
                htSendData.Add("PRT_DIV", ItemConst.IRT_PRT_DIV.RETURN_COMPANY_DETAIL);
                // START_DT
                htSendData.Add("START_DT", sDateFrom);
                // END_DT
                htSendData.Add("END_DT", sDateFrom);
                // ORD_SEQ
                htSendData.Add("ORD_SEQ", "");
                // ORD_GRP
                htSendData.Add("ORD_GRP", sDiv);
                // DATA_CNT
                htSendData.Add("DATA_CNT", "0");
                // RES_DATA
                htSendData.Add("RES_DATA", "");

                sRet = m_cDataCommon.ExecutePosIrt(ItemConst.COMM_MSG_TYPE.POSIRT, m_cPosStatus.Base.CommSvrIp, (int)m_cPosStatus.Base.BizInqPort, 10000, htSendData, ref htRecvData);
                if (sRet != UserCom.RST_OK)
                {
                    WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0326));
                    return sRet;
                }

                if (htRecvData["DATA_CNT"].ToString() != "0")
                {
                    if (htRecvData.Count > 0)
                    {
                        sCol = htRecvData["RES_DATA"].ToString().Split(new string[] { "#~" }, StringSplitOptions.RemoveEmptyEntries);

                        aCustItem = (ArrayList)StateObject.GetItemObject(Column.POS_REQ_SERVER_INTERFACE.ITEM);

                        aCustItem.Clear();

                        for (int i = 0; i < sCol.Count(); i++)
                        {
                            m_cCustItem = new Column.POS_REQ_SERVER_INTERFACE.DATA();

                            sRow = sCol[i].Split('|');

                            m_cCustItem.FIELD_01 = sRow[0];
                            m_cCustItem.FIELD_02 = sRow[1];
                            m_cCustItem.FIELD_03 = sRow[2];
                            m_cCustItem.FIELD_04 = sRow[3];

                            if (sRow.Length > 4)
                                m_cCustItem.FIELD_05 = sRow[4];

                            aCustItem.Add(m_cCustItem);
                        }

                        sRet = DisplayEventDetail(sDateFrom, sDivNm);

                        return sRet;
                    }

                }
                else
                {
                    WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0302));
                    sRet = UserCom.RST_ERR;
                    return sRet;
                }

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

        private string DisplayEventDetail(string sDateFrom, string sDivNm)
        {
            string sRet = UserCom.RST_ERR;

            string sPrintData = string.Empty;
            string sPrtDate = string.Empty;

            try
            {
                if (sDateFrom != "" && sDateFrom.Length >= 8)
                {
                    sPrtDate = sDateFrom.Substring(0, 4) + "." + sDateFrom.Substring(4, 2) + "." + sDateFrom.Substring(6, 2);
                }

                // 프린트 헤더
                AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F103, new string[] { string.Format(MessageManager.GetPrintMessage(POS_MESSAGE.PRINT.MSG_0127), sDivNm) });
                AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F103, new string[] { "[ " + MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0075) + MessageManager.GetPrintMessage(POS_MESSAGE.PRINT.MSG_0113) + " ]   " + sPrtDate });
                //AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, new string[] { "-" });
                //AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F300, new string[] { MessageManager.GetPrintMessage(POS_MESSAGE.PRINT.MSG_0128), MessageManager.GetPrintMessage(POS_MESSAGE.PRINT.MSG_0129), MessageManager.GetPrintMessage(POS_MESSAGE.PRINT.MSG_0130) });
                //AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, new string[] { "-" });

                for (int iRow = 0; iRow < aCustItem.Count; iRow++)
                {
                    Column.POS_REQ_SERVER_INTERFACE.DATA cCustItem = (Column.POS_REQ_SERVER_INTERFACE.DATA)aCustItem[iRow];
                    if (iRow == 0)
                    {
                        AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, new string[] { "=" });
                        AddPrintData(PosConst.PRT_HDR.PRT_NOR, "", new string[] { cCustItem.FIELD_02, cCustItem.FIELD_03, cCustItem.FIELD_04 });
                        AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, new string[] { "=" });
                    }
                    else
                    {
                        if (iRow == aCustItem.Count - 1)
                        {
                            AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, new string[] { "=" });
                        }
                        AddPrintData(PosConst.PRT_HDR.PRT_NOR, "", new string[] { cCustItem.FIELD_02, m_cPosStatus.Global.NumericTOCurrency(CmUtil.DoubleParse(cCustItem.FIELD_03)), 
                            m_cPosStatus.Global.NumericTOCurrency(CmUtil.DoubleParse(cCustItem.FIELD_04)) });
                        //AddPrintData(PosConst.PRT_HDR.PRT_NOR, "", new string[] { cCustItem.FIELD_01, cCustItem.FIELD_02, cCustItem.FIELD_03, 
                        //cCustItem.FIELD_04, m_cPosStatus.Global.NumericTOCurrency(Convert.ToDouble(cCustItem.FIELD_05))});
                        if (iRow == aCustItem.Count - 1)
                        {
                            AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, new string[] { "=" });
                        }

                        if (iRow != aCustItem.Count - 1 && cCustItem.FIELD_05.Trim().Length > 0)
                        {
                            AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F101, new string[] { cCustItem.FIELD_05 });
                        }

                    }

                    
                }


                //for (int iRow = 1; iRow < aCustItem.Count; iRow++)
                //{
                //    Column.POS_REQ_SERVER_INTERFACE.DATA cCustItem = (Column.POS_REQ_SERVER_INTERFACE.DATA)aCustItem[iRow];

                //    AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F300, new string[] { cCustItem.FIELD_02, m_cPosStatus.Global.NumericTOCurrency(Convert.ToDouble(cCustItem.FIELD_03)), m_cPosStatus.Global.NumericTOCurrency(Convert.ToDouble(cCustItem.FIELD_04)) });
                //}

                //AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F100, new string[] { "-" });
                AddPrintData(PosConst.PRT_HDR.PRT_NOR, PosConst.PRT_FMT.F103, new string[] { "** " + MessageManager.GetPrintMessage(POS_MESSAGE.PRINT.MSG_0072) + " : " + DateTime.Now.ToString("yyyyMMddHHmmss") + " **" });

                sRet = UserCom.RST_OK;

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

        #region 영수증 출력데이터 생성
        /// <summary>
        /// 영수증 출력데이터 생성
        /// </summary>
        /// <param name="sPrtHead">출력형태</param>
        /// <param name="sPrtFmt">출력포맷</param>
        /// <param name="sData">Data</param>
        private void AddPrintData(string sPrtHead, string sPrtFmt, string[] aData)
        {
            try
            {
                string sPrtData = "";

                if (sPrtFmt == PosConst.PRT_FMT.F100)               // 선귿기
                {
                    for (int i = 1; i <= 42; i++) sPrtData += aData[0];
                }

                else if (sPrtFmt == PosConst.PRT_FMT.F101)          // 왼쪽정렬
                {
                    sPrtData = aData[0];
                }
                else if (sPrtFmt == PosConst.PRT_FMT.F102)          // 오른쪽 정렬
                {
                    sPrtData = CmUtil.LPadH(aData[0], 42);
                }
                else if (sPrtFmt == PosConst.PRT_FMT.F103)          // 중앙정렬
                {
                    if (sPrtHead == PosConst.PRT_HDR.PRT_HOR || sPrtHead == PosConst.PRT_HDR.PRT_BIG)
                    {
                        if (CmUtil.LenH(aData[0]) <= 21) sPrtData = CmUtil.LPadH("", 10 - (CmUtil.LenH(aData[0]) / 2)) + aData[0];
                    }
                    else
                    {
                        if (CmUtil.LenH(aData[0]) <= 42) sPrtData = CmUtil.LPadH("", 21 - (CmUtil.LenH(aData[0]) / 2)) + aData[0];
                    }
                }
                else
                {
                    switch (aData.Length)
                    {
                        case 5:
                            sPrtData = CmUtil.RPadH(aData[0].ToString(), 13) + CmUtil.LPadH(aData[1].ToString(), 5) + CmUtil.LPadH(aData[2].ToString(), 5) + CmUtil.RPadH(aData[3].ToString(), 5) + CmUtil.LPadH(aData[4].ToString(), 14);
                            break;
                        case 4:
                            sPrtData = CmUtil.RPadH(aData[0].ToString(), 12) + CmUtil.RPadH(aData[1].ToString(), 12) + CmUtil.LPadH(aData[2].ToString(), 7) + CmUtil.LPadH(aData[3].ToString(), 11);
                            break;
                        case 3:
                            sPrtData = CmUtil.RPadH(aData[0].ToString(), 22) + CmUtil.LPadH(aData[1].ToString(), 7) + CmUtil.LPadH(aData[2].ToString(), 12);
                            break;
                        default:
                            sPrtData = aData[0].ToString();
                            break;
                    }
                }
                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);
            }
        }
        #endregion 

        public string SetData(object oParam)
        {
            string bReturn = UserCom.RST_ERR;
            try
            {
                ArrayList alPrintData = (ArrayList)oParam;

                string[] arPrintData = (string[])alPrintData.ToArray(typeof(string));

                m_cPrinterUs.ReceiptPrinter(arPrintData);
            }
            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 string Execute(string[] aParam)
        {
            throw new NotImplementedException();
        }
    }
}
