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

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

namespace Cosmos.Service
{
    class ResendTranToOutside : IDataServiceUs
    {
        #region 변수 선언
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private PosStatus m_cPosStatus = new PosStatus();                           // POS 기본정보 참조        

        private IDatabaseSQL m_cSqlDbService = null;
        private ICalDataIF m_cCalDataIf = null;
        #endregion 변수 선언

        #region  생성자
        public ResendTranToOutside()
        {
            m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보

            m_cSqlDbService = (IDatabaseSQL)sManager.InitServiceInstance(ServiceLists.AGENT_DATABASE.DLL, ServiceLists.AGENT_DATABASE.DATABASE_MSSQL);
            m_cCalDataIf = (ICalDataIF)sManager.InitServiceInstance(ServiceLists.BSV_OPEN_CLOSE.DLL, ServiceLists.BSV_OPEN_CLOSE.CAL_DATA_IF);
        }
        #endregion 생성자

        public string Execute(string[] aParam)
        {
            string sRet = UserCom.RST_ERR;
            try
            {
                string sType = aParam[0].Equals(PosKey.MENU_KEY.EX_RESEND_SALE) == true ? "EX" : "KAC";
                string sStDt = aParam[1];
                string sEndDt = aParam[2];


                //#20180322 휴게소pos매출연동 start,phj
                if (sType.Equals("EX") == true)
                {
                    // 관리메뉴에서 기존 도로공사 재전송 기능을 같이 쓰므로 분기하기 위해서 
                    if (m_cPosStatus.Mst.ETC_IF_DIV == ItemConst.TranInterfaceOutside.IF_KOR_03)
                    {
                        sType = "EX2018";
                    }
                }
                //#20180322 휴게소pos매출연동 end,phj
                
                // SendFlag Reset
                //#20180322 휴게소pos매출연동 start,phj
                //기존
                //int iRet = ResetSendFlag(sStDt, sEndDt);
                //변경
                int iRet = ResetSendFlag(sStDt, sEndDt, sType);
                //#20180322 휴게소pos매출연동 end,phj

                
                if (iRet != UserCom.OK)
                {
                    return UserCom.RST_ERR;
                }
    
                // 지정 일자 마감 재전송
                DateTime dtTarget;
                string sTarget = sStDt;
                while (true)
                {
                    // sTarget 일자로 도로공사 정산데이터 생성
                    sRet = m_cCalDataIf.Execute(new string[] { sType, sTarget });
                    if (sRet != UserCom.RST_OK)
                    {
                        break;
                    }

                    // 정산데이터 생성 일자 + 1 일자가 재전송 종료 일자 보다 크면 종료

                    //#20180322 휴게소pos매출연동 start,phj
                    //기존
                    //DateTime.TryParse(sTarget, out dtTarget);
                    //변경
                    dtTarget = DateTime.ParseExact(sTarget, "yyyyMMdd", null);
                    //#20180322 휴게소pos매출연동 end,phj

                    sTarget = dtTarget.AddDays(1).ToString();
                    if (sTarget.CompareTo(sEndDt) > 0) break;
                }

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

        /// <summary>
        /// 데이터 조회
        /// </summary>
        /// <param name="aParam"></param>
        /// <returns></returns>
        public object GetData(string[] aParam)
        {
            string sQuery = "";

            try
            {
                //#20180322 휴게소pos매출연동 start,phj

                //기존
                /*
                sQuery = " SELECT COUNT(1) AS TOTAL_CNT \n"
                       + "      , SUM(CASE WHEN OUT_SEND_YN = '1' \n"
                       + "                 THEN 1 \n"
                       + "                 ELSE 0 \n"
                       + "            END) AS OK_CNT \n"
                       + "      , SUM(CASE WHEN OUT_SEND_YN = '9' \n"
                       + "                 THEN 1 \n"
                       + "                 ELSE 0 \n"
                       + "            END) AS FAIL_CNT \n"
                       + "   FROM POSLOG..TR_SALE_HEADER \n"
                       + "  WHERE CMP_CD = '" + aParam[0] + "' \n"
                       + "    AND SALE_DT BETWEEN '" + aParam[1] + "' AND '" + aParam[2] + "' \n"
                       + "    AND STOR_CD = '" + aParam[3] + "' \n";                
                */
                //변경
                if (m_cPosStatus.Mst.ETC_IF_DIV == ItemConst.TranInterfaceOutside.IF_KOR_01)
                {
                    sQuery = " SELECT COUNT(1) AS TOTAL_CNT \n"
                           + "      , SUM(CASE WHEN OUT_SEND_YN = '1' \n"
                           + "                 THEN 1 \n"
                           + "                 ELSE 0 \n"
                           + "            END) AS OK_CNT \n"
                           + "      , SUM(CASE WHEN OUT_SEND_YN = '9' \n"
                           + "                 THEN 1 \n"
                           + "                 ELSE 0 \n"
                           + "            END) AS FAIL_CNT \n"
                           + "   FROM POSLOG..TR_SALE_HEADER \n"
                           + "  WHERE CMP_CD = '" + aParam[0] + "' \n"
                           + "    AND SALE_DT BETWEEN '" + aParam[1] + "' AND '" + aParam[2] + "' \n"
                           + "    AND STOR_CD = '" + aParam[3] + "' \n";
                }
                else if (m_cPosStatus.Mst.ETC_IF_DIV == ItemConst.TranInterfaceOutside.IF_KOR_03)
                {
                    sQuery = " SELECT COUNT(1) AS TOTAL_CNT \n"
                           + "      , SUM(CASE WHEN OUT_SEND_YN = '8' \n"
                           + "                 THEN 1 \n"
                           + "                 ELSE 0 \n"
                           + "            END) AS OK_CNT \n"
                           + "      , SUM(CASE WHEN OUT_SEND_YN = '9' \n"
                           + "                 THEN 1 \n"
                           + "                 ELSE 0 \n"
                           + "            END) AS FAIL_CNT \n"
                           + "   FROM POSLOG..TR_SALE_HEADER \n"
                           + "  WHERE CMP_CD = '" + aParam[0] + "' \n"
                           + "    AND SALE_DT BETWEEN '" + aParam[1] + "' AND '" + aParam[2] + "' \n"
                           + "    AND STOR_CD = '" + aParam[3] + "' \n";
                }

                //#20180322 휴게소pos매출연동 end,phj



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

                DataTable dtDataInfo = null;

                m_cSqlDbService.DBSelect(sQuery, out dtDataInfo);

                m_cSqlDbService.Close();

                return dtDataInfo;
            }
            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 null;
        }

        public string SetData(object oParam)
        {
            return UserCom.RST_ERR;
        }

        /// <summary>
        /// 도로공사 매출재전송 위한 전송 Flag Reset
        /// </summary>
        /// <param name="sStartDt"></param>
        /// <param name="sEndDt"></param>
        /// <returns></returns>
        //#20180322 휴게소pos매출연동 start,phj
        //기존
        //private int ResetSendFlag(string sStartDt, string sEndDt)
        //변경
        private int ResetSendFlag(string sStartDt, string sEndDt, string sType)
        //#20180322 휴게소pos매출연동 end,phj
        {
            int iRet = UserCom.NG;
            string sQuery = "";

            try
            {

                //#20180322 휴게소pos매출연동 start,phj

                //기존
                /*
                sQuery = " UPDATE POSLOG..TR_SALE_HEADER \n"
                       + "    SET OUT_SEND_YN = '0' \n"
                       + "  WHERE SALE_DT BETWEEN '" + sStartDt + "' AND '" + sEndDt + "' \n"
                       + "    AND TRAIN_MODE_YN = '0' \n"
                       + "    AND TRADE_KINDPER = '00' \n";
                */
                //변경 
                sQuery = " UPDATE POSLOG..TR_SALE_HEADER \n"
                       //20180404 도로공사 재전송 기능을 제외한 기본 스레드 동작에서는 영업일자 기준으로 동작하지 않도록 수정 start, phj
                       //기존
                       //+ "    SET OUT_SEND_YN = '0' \n"
                       //변경
                       + "    SET OUT_SEND_YN = 'R' \n"
                       //20180404 도로공사 재전송 기능을 제외한 기본 스레드 동작에서는 영업일자 기준으로 동작하지 않도록 수정 end, phj
                       + "  WHERE SALE_DT BETWEEN '" + sStartDt + "' AND '" + sEndDt + "' \n"
                       + "    AND TRAIN_MODE_YN = '0' \n";

                if (sType == "EX2018")
                {
                    sQuery = sQuery + "    AND TRADE_KINDPER IN ('00','20','21','42') \n";
                }
                else
                {
                    sQuery = sQuery + "    AND TRADE_KINDPER = '00' \n";
                }
                //#20180322 휴게소pos매출연동 end,phj



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