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 StoreEquipCheck : IStoreEquipCheck
    {
        private PosStatus m_cPosStatus = new PosStatus();                           //기본정보 참조
        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        private IDatabaseSQL m_cSqlDbService = null;                                // 데이터베이스 관리

        private IMasterUs m_cMstService = null;                                     // 마스터 인터페이스
        protected IDataCommonUs m_cDataCommon = null;                               // 판매공통 모듈

        #region 생성자 & 소멸자
        public StoreEquipCheck()
        {
            m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
            m_cDataCommon = (IDataCommonUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.DATA_COMMON);
            m_cSqlDbService = (IDatabaseSQL)sManager.InitServiceInstance(ServiceLists.AGENT_DATABASE.DLL, ServiceLists.AGENT_DATABASE.DATABASE_MSSQL);
            m_cMstService = (IMasterUs)sManager.InitServiceInstance(ServiceLists.ASV_MASTER.DLL, ServiceLists.ASV_MASTER.POS_MASTER);
        }
        #endregion 생성자 & 소멸자

        /// <summary>
        /// 일일점검리스트 일자별 상태 조회
        /// </summary>
        /// <returns></returns>
        public string SearchStoreEquipCheckList(string sSearchFlag, string sDateFrom, string sDateTo)
        {
            string sRet = UserCom.RST_ERR;

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

                //INQ_TYPE
                htSendData.Add(Column.IQ_POS_LIVECHECK_REQ.DATA.INQ_TYPE, ItemConst.IRT_INQ_TYPE.STR_EQUIP_CHECK);
                // CMP_CD
                htSendData.Add(Column.IQ_POS_LIVECHECK_REQ.DATA.CMP_CD, m_cPosStatus.Base.CmpCd);
                // STOR_CD
                htSendData.Add(Column.IQ_POS_LIVECHECK_REQ.DATA.STOR_CD, m_cPosStatus.Base.StoreNo);
                // START_DT
                htSendData.Add(Column.IQ_POS_LIVECHECK_REQ.DATA.FROM_DATE, sDateFrom);
                // END_DT
                htSendData.Add(Column.IQ_POS_LIVECHECK_REQ.DATA.TO_DATE, sDateTo);
                // DATA_DIV
                htSendData.Add(Column.IQ_POS_LIVECHECK_REQ.DATA.DATA_DIV, sSearchFlag);
                // DATA
                htSendData.Add(Column.IQ_POS_LIVECHECK_REQ.DATA.RETURN_DATA, "");
                // RES_CD
                htSendData.Add(Column.IQ_POS_LIVECHECK_REQ.DATA.RES_CD, "");

                sRet = m_cDataCommon.ExecutePosIrt(ItemConst.COMM_MSG_TYPE.POSIRT, m_cPosStatus.Base.CommSvrIp, (int)m_cPosStatus.Base.PayInqPort, 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[Column.IQ_POS_LIVECHECK_REQ.DATA.RES_CD].ToString() != "01")
                {
                    return htRecvData[Column.IQ_POS_LIVECHECK_REQ.DATA.RETURN_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>
        public DataTable SearchStoreEquipCheckInfo()
        {
            string sQuery = "";
            try
            {
                sQuery = " SELECT MC1.ENTRY_NM AS CD_NM1";
                sQuery += "      ,MC2.ENTRY_NM AS CD_NM2";
                sQuery += "      ,MC2.EXPLN AS EXPLN ";
                sQuery += "      ,MC2.CMM_CD AS CMM_CD ";
                sQuery += "      ,MC2.CHAR_VAL_TITLE_VAL_01 AS CHAR_VAL_TITLE_VAL_01 ";
                sQuery += " FROM POSMST.dbo.MST_STR_DAILY_INSPCT_LIST AS ML ";
                sQuery += "     LEFT OUTER JOIN POSMST.dbo.MST_CMM AS MC2 ON ML.CMP_CD = MC2.CMP_CD AND ML.INSPCT_CD = MC2.CMM_CD AND MC2.CMM_GRP_CD = 'D0031' ";
                sQuery += "     LEFT OUTER JOIN POSMST.dbo.MST_CMM AS MC1 ON MC2.CMP_CD = MC1.CMP_CD AND MC2.CHAR_VAL_TITLE_VAL_01 = MC1.CMM_CD AND MC1.CMM_GRP_CD = 'D0030' ";
                sQuery += " WHERE ML.CMP_CD = '" + m_cPosStatus.Base.CmpCd + "'";
                sQuery += "   AND ML.STOR_CD = '" + m_cPosStatus.Base.StoreNo + "'";
                sQuery += "   AND ML.USE_YN = '1' ";

                DataTable dtDataInfo = m_cMstService.Select(new string[] { sQuery });

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

        /// <summary>
        /// 일일점검리스트 점포 저장
        /// </summary>
        /// <returns></returns>
        public string StoreCheckSave(DataTable dtData1, DataTable dtData2)
        {
            string sInsQuery1 = string.Empty;
            string sInsQuery2 = string.Empty;
            string sQuery = string.Empty;

            string sRet = UserCom.RST_ERR;
            string sRegDateTime = string.Empty;

            try
            {
                if (dtData1 != null && dtData2 != null)
                {
                    if (m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource,
                                                                  m_cPosStatus.Base.LocalDbCatalog,
                                                                  m_cPosStatus.Base.LocalDbUserID,
                                                                  m_cPosStatus.Base.LocalDbPassword) == true)
                    {

                        m_cSqlDbService.Begin();

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


                        foreach (DataRow dr1 in dtData1.Rows)
                        {
                            // 점포 점검 헤더 저장
                            sInsQuery1 = "";
                            sInsQuery1 += " IF NOT EXISTS (SELECT * ";
                            sInsQuery1 += "                       FROM POSLOG.dbo.ETC_STOR_EQU_CHECK_LIST ";
                            sInsQuery1 += "  WHERE CMP_CD     = '{0}'";
                            sInsQuery1 += "    AND STOR_CD    = '{1}'";
                            sInsQuery1 += "    AND SALE_DT    = '{2}' )";
                            sInsQuery1 += " BEGIN";
                            sInsQuery1 += "  INSERT INTO POSLOG.dbo.ETC_STOR_EQU_CHECK_LIST (";
                            sInsQuery1 += "   CMP_CD, STOR_CD, SALE_DT, CHECK_STATE, SEND_YN, REG_USER_ID, REG_DATE, UPD_USER_ID, UPD_DATE ";
                            sInsQuery1 += " ) VALUES ( ";
                            sInsQuery1 += "    '{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}' ) ";
                            sInsQuery1 += " END ";
                            sInsQuery1 += " ELSE ";
                            sInsQuery1 += " BEGIN";
                            sInsQuery1 += "  UPDATE POSLOG.dbo.ETC_STOR_EQU_CHECK_LIST ";
                            sInsQuery1 += "     SET CHECK_STATE = '{3}'";
                            sInsQuery1 += "        ,SEND_YN = '{4}'";
                            sInsQuery1 += "        ,UPD_USER_ID = '{7}'";
                            sInsQuery1 += "        ,UPD_DATE = '{8}'";
                            sInsQuery1 += "  WHERE CMP_CD     = '{0}'";
                            sInsQuery1 += "    AND STOR_CD    = '{1}'";
                            sInsQuery1 += "    AND SALE_DT    = '{2}'";
                            sInsQuery1 += " END ";

                            sQuery = string.Format(sInsQuery1
                                                        , m_cPosStatus.Base.CmpCd                                              // 회사코드
                                                        , m_cPosStatus.Base.StoreNo                                            // 점포코드
                                                        , dr1["SALE_DT"]                   // 점검일자   
                                                        , dr1["CHECK_STATE"]                  // 점검일자   
                                                        , "0"                                                                  // 전송여부
                                                        , dr1["REG_USER_ID"]               // 등록자
                                                        , sRegDateTime                                                         // 등록일자
                                                        , dr1["REG_USER_ID"]               // 수정자
                                                        , sRegDateTime                                                         // 수정일자
                                                        );
                        }

                        foreach (DataRow dr2 in dtData2.Rows)
                        {
                            // 점포 점검 헤더 저장
                            sInsQuery2 = "";
                            sInsQuery2 += " IF NOT EXISTS (SELECT * ";
                            sInsQuery2 += "                       FROM POSLOG.dbo.ETC_STOR_EQU_CHECK_DETAIL ";
                            sInsQuery2 += "  WHERE CMP_CD     = '{0}'";
                            sInsQuery2 += "    AND STOR_CD    = '{1}'";
                            sInsQuery2 += "    AND SALE_DT    = '{2}'";
                            sInsQuery2 += "    AND CHECK_DIV_CD    = '{3}'";
                            sInsQuery2 += "    AND CHECK_EQU_CD    = '{4}' )";
                            sInsQuery2 += " BEGIN";
                            sInsQuery2 += "  INSERT INTO POSLOG.dbo.ETC_STOR_EQU_CHECK_DETAIL (";
                            sInsQuery2 += "   CMP_CD, STOR_CD, SALE_DT, CHECK_DIV_CD, CHECK_EQU_CD, CHECK_RESULT, AS_RESULT, STOR_RESULT, REG_USER_ID, REG_DATE, UPD_USER_ID, UPD_DATE ";
                            sInsQuery2 += " ) VALUES ( ";
                            sInsQuery2 += "    '{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}', '{11}' ) ";
                            sInsQuery2 += " END ";
                            sInsQuery2 += " ELSE ";
                            sInsQuery2 += " BEGIN";
                            sInsQuery2 += "  UPDATE POSLOG.dbo.ETC_STOR_EQU_CHECK_DETAIL ";
                            sInsQuery2 += "     SET AS_RESULT = '{6}'";
                            sInsQuery2 += "        ,STOR_RESULT = '{7}'";
                            sInsQuery2 += "        ,UPD_USER_ID = '{10}'";
                            sInsQuery2 += "        ,UPD_DATE = '{11}'";
                            sInsQuery2 += "  WHERE CMP_CD     = '{0}'";
                            sInsQuery2 += "    AND STOR_CD    = '{1}'";
                            sInsQuery2 += "    AND SALE_DT    = '{2}'";
                            sInsQuery2 += "    AND CHECK_DIV_CD    = '{3}'";
                            sInsQuery2 += "    AND CHECK_EQU_CD    = '{4}'";
                            sInsQuery2 += " END ";

                            sQuery += string.Format(sInsQuery2
                                                        , m_cPosStatus.Base.CmpCd                                         // 회사코드
                                                        , m_cPosStatus.Base.StoreNo                                       // 점포코드
                                                        , dr2["SALE_DT"]                 // 점검일자 
                                                        , dr2["CHECK_DIV_CD"]   // 점검항목대분류코드
                                                        , dr2["CHECK_EQU_CD"]             // 점검항목
                                                        , dr2["CHECK_RESULT"]           // 선택항목1 여부
                                                        , dr2["AS_RESULT"]           // 선택항목2 여부
                                                        , dr2["STOR_RESULT"]           // 선택항목3 여부
                                                        , dr2["REG_USER_ID"]           // 선택항목4 여부
                                                        , sRegDateTime           // 선택항목5 여부
                                                        , dr2["REG_USER_ID"]                  // 점수1
                                                        , sRegDateTime                  // 점수2
                                                        );
                        }

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

    }
}
