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

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

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 직원방문등록
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Service
{
    class EtcInEmp : IDataServiceUs
    {
        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private PosStatus m_cPosStatus = new PosStatus();                           //기본정보 참조
        private DeviceStatus m_cDevStatus = new DeviceStatus();                     // 디바이스 관리
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        private ISvr2Tran m_cSvr2Tran = null;                                       // 서버시간 동기화
        private IDatabaseSQL m_cSqlDbService = null;                                // 데이터베이스 관리

        

        public EtcInEmp()
        {
            m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
            //m_cTrnStatus = (TranStatus)StateObject.TRAN;    // POS 거래정보
            m_cDevStatus = (DeviceStatus)StateObject.DEVICE;


            m_cSqlDbService = (IDatabaseSQL)sManager.InitServiceInstance(ServiceLists.AGENT_DATABASE.DLL, ServiceLists.AGENT_DATABASE.DATABASE_MSSQL);
            m_cSvr2Tran = (ISvr2Tran)sManager.InitServiceInstance(ServiceLists.BSV_SALE.DLL, ServiceLists.BSV_SALE.SVR2TRAN);

        }


        /// <summary>
        /// 직원방문등록 조회
        /// </summary>
        /// <returns></returns>
        public object GetData(string[] aParam)
        {

            string sQuery = "";
            DataTable dt = null;

            try
            {

                if (aParam[0] == "List")
                {
                    sQuery += " SELECT ";
                    sQuery += "        MNG_CARD_NO";
                    sQuery += "      , SUBSTRING(VISIT_START_HOUR,9,2) +':'+SUBSTRING(VISIT_START_HOUR,11,2) +':'+SUBSTRING(VISIT_START_HOUR,13,2) ";
                    sQuery += "      , SUBSTRING(VISIT_FNSH_HOUR,9,2) +':'+SUBSTRING(VISIT_FNSH_HOUR,11,2) +':'+SUBSTRING(VISIT_FNSH_HOUR,13,2) ";
                    //#20170828 직원방문등록 시 고객센터전화요망 팝업 쿼리문에 VISIT_DT 필드가 없음 start
                    //#20170829 직원방문등록에 방문시간 표시 날짜로 되어 쿼리 순서 변경
                    sQuery += "      , VISIT_DT";
                    //#20170828 직원방문등록 시 고객센터전화요망 팝업 쿼리문에 VISIT_DT 필드가 없음 end
                    sQuery += " FROM POSLOG..TR_STORE_VISIT ";
                    sQuery += " WHERE CMP_CD   = '" + m_cPosStatus.Base.CmpCd + "'";
                    sQuery += "   AND VISIT_DT = '" + aParam[1] + "'";
                    sQuery += "   AND STOR_CD  = '" + m_cPosStatus.Base.StoreNo + "'";
                    sQuery += "   AND POS_NO   = '" + m_cPosStatus.Base.PosNo + "'";

                    if (aParam[2] != "")
                    {
                        sQuery += "   AND MNG_CARD_NO   = '" + aParam[2] + "'";
                    }

                    sQuery += "  ORDER BY UPD_DATE DESC ";
                }
                else if (aParam[0] == "Time")
                {
                    sQuery = string.Format(" SELECT DATEDIFF(SECOND,CONVERT(DATETIME,'{0}'),GETDATE()) AS IGAP", aParam[1]);
                }


                if (sQuery != "")
                {
                    int iRet = m_cSqlDbService.DBSelect(sQuery, out dt);

                    if (iRet == 1) return dt;
                }

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

        /// <summary>
        /// 없음!
        /// </summary>
        /// <param name="oParam"></param>
        /// <returns></returns>
        public string SetData(object oParam)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 직원 방문 및 제조기사 등록 저장
        /// </summary>
        /// <param name="aParam"></param>
        /// <returns></returns>
        public string Execute(string[] aParam)
        {
            string sQuery = "";
            string sRet = UserCom.RST_ERR;
            string sVisitDate = "";
            string sCardNo = "";
            string sInputData = "";


            try
            {

                aParam[0] = aParam[0].Replace("\n", "");


                if (InputDataCheck(aParam[0], ref sCardNo, ref aParam[3]) == true)
                {
                    if (sCardNo != "")
                        aParam[0] = sCardNo;


                    if (aParam[0].Length > 16)
                        aParam[0] = CmUtil.MidH(aParam[0], 0, 16);

                }
                else
                {
                    return sRet;
                }

                //#20171103 제조기사 출/퇴근조건 수정 start,phj
                //기존
                /*
                //DateTime.Now.ToString("yyyyMMdd")
                //00 ~ 05시 사이면 이전 일자 체크
                int iTime = CmUtil.IntParse(DateTime.Now.ToString("HHmm"));
                if (iTime >= 0 && iTime <= 500)
                {

                    //이전일자
                    DataTable dt = (DataTable)GetData(new string[] { "List", DateTime.Now.AddDays(-1).ToString("yyyyMMdd"), aParam[0] });

                    if (dt == null || dt.Rows.Count == 0)
                    {
                        sVisitDate = DateTime.Now.ToString("yyyyMMdd");
                    }
                    else
                    {
                        sVisitDate = dt.Rows[0]["VISIT_DT"].ToString();
                    }
                }
                else
                {
                    sVisitDate = DateTime.Now.ToString("yyyyMMdd");
                }
                */
                //변경
                //출근찍고, 퇴근안찍고, 다음 날 출근 시 퇴근처리 됨.
                //날짜가 다르면 출근 처리하도록 수정.
                sVisitDate = DateTime.Now.ToString("yyyyMMdd");
                //#20171103 제조기사 출/퇴근조건 수정 end,phj 


                //0:관리 카드 번호, 1:방문시간, 2:종료시간, 3:MSR구분, 4: 원바코드 번호

                string sRegDateTime = DateTime.Now.ToString("yyyyMMddHHmmss");

                sQuery = " UPDATE POSLOG.dbo.TR_STORE_VISIT SET  ";
                sQuery += " VISIT_FNSH_HOUR = '{6}' , SEND_YN = '0', UPD_DATE = '{13}' ";
                sQuery += " WHERE CMP_CD      = '{0}'";
                sQuery += "   AND STOR_CD     = '{1}'";
                sQuery += "   AND VISIT_DT    = '{2}'";
                sQuery += "   AND POS_NO      = '{3}'";
                sQuery += "   AND MNG_CARD_NO = '{4}'";
                sQuery += "   AND VISIT_FNSH_HOUR = '' ";
                sQuery += " IF @@ROWCOUNT = 0 ";
                sQuery += "  BEGIN ";
                sQuery += " INSERT INTO POSLOG.dbo.TR_STORE_VISIT( ";
                sQuery += "        CMP_CD ,STOR_CD ,VISIT_DT ,POS_NO ,MNG_CARD_NO ,VISIT_START_HOUR ,VISIT_FNSH_HOUR ,VISIT_USER_ID ,JOB_TYPE ,PCSMM_SEND_YN ";
                sQuery += "       ,MSR_DIV ,ORG_BAR_CD_NO ,SEND_YN ,REG_DATE ,UPD_DATE ";
                sQuery += " ) VALUES ( '{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '', '{7}', '{8}' , '{9}', ";
                sQuery += " '{10}','{11}', '{12}', '{13}', '{14}' )";
                sQuery += "  END ";

                sQuery = string.Format(sQuery
                    , m_cPosStatus.Base.CmpCd           // CMP_CD
                    , m_cPosStatus.Base.StoreNo         // STOR_CD

                    // Mod, 2017.08.30, VISIT_DT 조회오류 수정
                    //, DateTime.Now.ToString("yyyyMMdd") // SALE_DT
                    , sVisitDate                        // SALE_DT

                    , m_cPosStatus.Base.PosNo           // POS_NO
                    , aParam[0]                         // MNG_CARD_NO
                    , aParam[1]                         // VISIT_START_HOUR
                    , aParam[2]                         // VISIT_FNSH_HOUR
                    , ""                                // VISIT_USER_ID
                    , ""                                // JOB_TYPE
                    , "0"                               // PCSMM_SEND_YN
                    , aParam[3]                         // MSR_DIV
                    , aParam[4]                         // ORG_BAR_CD_NO
                    , "0"                               // SEND_YN
                    , sRegDateTime                      // REG_DATE
                    , sRegDateTime                      // UPD_DATE
                    );

                if (m_cSqlDbService.DBExecuteNonQuery(new string[] { sQuery }) == UserCom.OK) return 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;
        }


        /// <summary>
        /// 입력 번호 체크
        /// </summary>
        /// <param name="sInData"></param>
        /// <param name="sCard"></param>
        /// <param name="sInType"></param>
        /// <returns></returns>
        private bool InputDataCheck(string sInData, ref string sCard, ref string sInType)
        {
            bool bRet = false;
            int iDefualtLen = 0;
            int iDefualtGap = 0;
            string sAddNum = "";

            try
            {

                SetServerSysDateTime();

                if (m_cDevStatus.Msr.STX != "" && sInData.StartsWith(m_cDevStatus.Msr.STX)) sInData = sInData.Substring(1);
                int iLastEtx = sInData.LastIndexOf(m_cDevStatus.Msr.ETX);
                if (m_cDevStatus.Msr.ETX != "" && iLastEtx > 0) sInData = CmUtil.MidH(sInData, 0, iLastEtx);
                

                if (m_cPosStatus.Mst.CorpDiv == ItemConst.CORP_DIV.PC &&
                    (m_cPosStatus.Mst.CntryDiv == ItemConst.CNTRY_DIV.KR || m_cPosStatus.Mst.CntryDiv == ItemConst.CNTRY_DIV.CN ||
                     m_cPosStatus.Mst.CntryDiv == ItemConst.CNTRY_DIV.US || m_cPosStatus.Mst.CntryDiv == ItemConst.CNTRY_DIV.VN) //PC(한국, 중국, 미국, 베트남)
                    )
                {

                    if (m_cPosStatus.Mst.CntryDiv == ItemConst.CNTRY_DIV.KR)  //한국
                    {
                        iDefualtLen = 22;
                        iDefualtGap = 30;
                    }
                    else
                    {
                        iDefualtLen = 19;
                        iDefualtGap = 60;
                    }


                    if (sInData.Length == iDefualtLen)
                    {

                        sAddNum = CmUtil.MidH(sInData, 19, 3).Replace("A", " ").Trim();

                        //#20170803 제조기사 바코드에 'ㅁ' 들어오는 경우 공백 처리 start
                        sAddNum = sAddNum.Replace("ㅁ", " ").Trim();
                        //#20170803 제조기사 바코드에 'ㅁ' 들어오는 경우 공백 처리 end

                        char[] uchars = sInData.ToCharArray();

                        sCard = string.Format("{0}{1}{2}{3}{4}{5}{6}{7}"
                            , uchars[0], uchars[3], uchars[6], uchars[9], uchars[12], uchars[15], uchars[18], m_cPosStatus.Mst.CntryDiv == ItemConst.CNTRY_DIV.KR ? sAddNum : "");


                        string sTimeCheck = string.Format("20{0}{1}-{2}{3}-{4}{5} {6}{7}:{8}{9}:{10}{11}"
                            , uchars[1], uchars[2], uchars[4], uchars[5], uchars[7], uchars[8], uchars[10], uchars[11]
                            , uchars[13], uchars[14], uchars[16], uchars[17]);

                        DataTable dt = null;
                        DateTime tmpDt;

                        bool bDateFlag = DateTime.TryParse(sTimeCheck, out tmpDt);

                        if (bDateFlag == true)
                        {
                            dt = (DataTable)GetData(new string[] { "Time", sTimeCheck });
                        }

                        int iGap = 0;

                        if (dt == null || dt.Rows.Count == 0)
                        {
                            // 유효하지 않은 바코드
                            WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0328));
                            
                            // Add, 2017.08.30 
                            return bRet = false; 
                        }
                        else
                        {
                            iGap = CmUtil.IntParse(dt.Rows[0]["IGAP"].ToString());
                        }

                        if (iGap > iDefualtGap)
                        {
                            //유효기간이 만료 되었습니다.
                            WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0329));
                        }
                        else if (iGap < 0)
                        {
                            // 유효하지 않은 바코드
                            WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0328));
                        }
                        else
                        {
                            //정상!
                            sInType = ItemConst.EMP_VISIT_DIV.MOBILE;
                            bRet = true;
                        }

                    }
                    else
                    {
                        ////국내일땐 에러!
                        //if (m_cPosStatus.Base.CmpCd == "PCKR")
                        //{
                        //    WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0328));
                        //}
                        //else
                        //{
                        // 입력 데이터 그대로 입력!
                        sCard = sInData;
                        sInType = ItemConst.EMP_VISIT_DIV.MSR;
                        bRet = true;
                        //}

                    }
                }
                else if (m_cPosStatus.Mst.CorpDiv == ItemConst.CORP_DIV.BR) //BRK
                {

                    if (sInData.Contains("=") == true)
                    {
                        
                        bRet = sInData.StartsWith("8231");

                        if (bRet == true)
                        {
                            sCard = sInData;
                            sInType = ItemConst.EMP_VISIT_DIV.MSR;
                        }
                        else
                        {
                            WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0330));
                        }
                    }
                    else
                    {
                        if (sInData.Length != 17)
                        {
                            //에러
                            WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0328));
                        }
                        else
                        {

                            bRet = CmUtil.CheckHappyMobileCard(sInData);

                            if (bRet == false)
                            {
                                WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0328));
                            }
                            else
                            {
                                sCard = sInData;
                                sInType = ItemConst.EMP_VISIT_DIV.MOBILE;
                            }

                        }
                    }
                }
                else if (m_cPosStatus.Mst.CorpDiv == ItemConst.CORP_DIV.SL ||
                    (m_cPosStatus.Mst.CorpDiv == ItemConst.CORP_DIV.PC && (m_cPosStatus.Mst.CntryDiv == ItemConst.CNTRY_DIV.SG || m_cPosStatus.Mst.CntryDiv == ItemConst.CNTRY_DIV.FR))
                    ) //삼립, PC싱가포르, PC프랑스
                {
                    if (sInData.Length == 7 || sInData.Length == 16)
                    {
                        //정상!
                        sInType = ItemConst.EMP_VISIT_DIV.MSR;
                        bRet = true;
                    }
                    else
                    {
                        //정확한 직원카드를 입력하세요.
                        WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0330));
                    }
                }
                else
                {
                    //해당 없음!
                    WinManager.ErrorMessage(MessageManager.GetErrorMessage(POS_MESSAGE.ERROR.MSG_0331));
                }

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

        /// <summary>
        /// 서버 시간 동기화
        /// </summary>
        private void SetServerSysDateTime()
        {
            try
            {
                // 서버 시간 동기화
                string sRet = m_cSvr2Tran.ServerSysDateTime();
            }
            catch (Exception ex)
            {
                WinManager.ExceptionMessage(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "()", ex.Message);
            }
        }

    }
}
