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

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

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : 고객 클레임 처리
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.Service
{
    class CustomerClaim : ICustomerService
    {
        private SManager sManager = new SManager();                                 // 이 객체를 통해 업무 Service 호출
        private PosStatus m_cPosStatus = new PosStatus();                           //기본정보 참조
        private StateServer StateObject = (StateServer)StateServer.GetInstance();   // StateObject : StateServer Object (객체)
        private IMasterUs m_cMstService = null;                                     // 마스터 인터페이스
        private IDatabaseSQL m_cSqlDbService = null;                                // 데이터베이스 관리
        private TranStatus m_cTrnStatus = null;                                     // 거래정보 참조

        private ISaleCompleteUs m_cSaleComplete = null;                             // 거래완료처리

        private IDataCommonUs m_cDataCommon = null;                               // 판매공통 모듈

        /// <summary>
        /// 고객 불편 사항
        /// </summary>
        protected Column.IQ_STORECLAIM_MSG_REQ.DATA m_cClaimData = null;

        public CustomerClaim()
        {
            m_cPosStatus = (PosStatus)StateObject.POS;      // POS 기본정보
            m_cTrnStatus = (TranStatus)StateObject.TRAN;    //POS 거래정보
            m_cMstService = (IMasterUs)sManager.InitServiceInstance(ServiceLists.ASV_MASTER.DLL, ServiceLists.ASV_MASTER.POS_MASTER);
            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);

            m_cSaleComplete = (ISaleCompleteUs)sManager.InitServiceInstance(ServiceLists.ASV_DATA_PROCESS.DLL, ServiceLists.ASV_DATA_PROCESS.SALE_COMPLETE);
        }

        /// <summary>
        /// 고객 불편 사항 처리조회 List
        /// </summary>
        /// <param name="sSearchDate">조회일자</param>
        /// <returns></returns>
        public DataTable SearchCustomerList(string sSearchDate)
        {
            string sQuery = "";
            try
            {
                // 고객 불편 사항 조회 처리
                sQuery += " SELECT SALE_DT ";
                sQuery += "      , SEQ ";
                sQuery += "      , CUST_NM ";
                sQuery += "      , CONVERT(VARCHAR, CLAIM_PRC_COST) CLAIM_PRC_COST ";
                sQuery += "      , ITEM_SNM ";
                sQuery += "      , CLAIM_PRC_MEMO ";
                sQuery += " FROM POSLOG..TR_STORE_CLAIM ";
                sQuery += " WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "'";
                sQuery += "   AND SALE_DT LIKE '" + sSearchDate + "%'";
                sQuery += "   AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "'";
                sQuery += "   AND POS_NO = '" + m_cPosStatus.Base.PosNo + "'";

                return m_cMstService.Select(new string[] { sQuery });
            }
            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="sSaleDate">조회일자</param>
        /// <param name="sSeq">SEQ</param>
        /// <returns></returns>
        public DataTable SearchCustomerDetail(string sSaleDate, string sSeq)
        {
            string sQuery = "";
            try
            {
                sQuery += " SELECT SALE_DT ";                                         // 접수일(접수번호)
                sQuery += "      , POS_NO ";                                          // POS번호(접수번호)
                sQuery += "      , SEQ ";                                             // SEQ(접수번호)
                sQuery += "      , CUST_NM ";                                         // 고객이름
                sQuery += "      , CUST_SEX ";                                        // 성별
                sQuery += "      , CUST_TEL ";                                        // 연락처
                sQuery += "      , ITEM_SNM ";                                        // 대표제품명
                sQuery += "      , BUY_DT ";                                          // 구매일
                sQuery += "      , LOT_NO ";                                          // 제품코드
                sQuery += "      , CLAIM_PRC_GB ";                                    // 처리구분
                sQuery += "      , CLAIM_PRC_COST ";                                  // 처리비용
                sQuery += "      , CLAIM_PRC_MEMO ";                                  // 처리내용
                sQuery += "   FROM POSLOG..TR_STORE_CLAIM ";
                sQuery += "  WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "'";
                sQuery += "    AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "'";
                sQuery += "    AND POS_NO = '" + m_cPosStatus.Base.PosNo + "'";
                sQuery += "    AND SALE_DT = '" + sSaleDate + "'";
                sQuery += "    AND SEQ = '" + sSeq + "'";

                return m_cMstService.Select(new string[] { sQuery });
            }
            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>
        /// 고객 불편 사항 최대 SEQ 구하기
        /// </summary>
        /// <returns></returns>
        public DataTable GetClaimSeq()
        {
            string sQuery = "";
            try
            {
                // 고객 불편 사항 조회 처리
                sQuery += " SELECT ISNULL(MAX(SEQ), 0) + 1 AS SEQ";                      // SEQ
                sQuery += "   FROM POSLOG..TR_STORE_CLAIM ";
                sQuery += "  WHERE CMP_CD = '" + m_cPosStatus.Base.CmpCd + "'";
                sQuery += "    AND STOR_CD = '" + m_cPosStatus.Base.StoreNo + "'";
                sQuery += "    AND SALE_DT = '" + m_cPosStatus.Base.SaleDate + "'";

                return m_cMstService.Select(new string[] { sQuery });
            }
            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="sClaimData">접수일자</param>
        /// <returns></returns>
        public string SetCustomerClaim(string sClaimData)
        {
            string sReturn = UserCom.RST_ERR;
            string sQuery = string.Empty;
            string sInsQuery = string.Empty;
            string sRegDateTime = string.Empty;
            string sOrgSaleDt = string.Empty;

            string[] sClaimInfo = null;

            sClaimInfo = sClaimData.Split('|');

            try
            {
                if (m_cSqlDbService.SetDBConnectionString(m_cPosStatus.Base.LocalDbSource,
                                                          m_cPosStatus.Base.LocalDbCatalog,
                                                          m_cPosStatus.Base.LocalDbUserID,
                                                          m_cPosStatus.Base.LocalDbPassword) == true)
                {
                    m_cSqlDbService.Begin();

                    if (sClaimInfo[0] != MessageManager.GetLabelMessage(POS_MESSAGE.LABEL.MSG_0718))
                    {
                        sInsQuery = " UPDATE POSLOG..TR_STORE_CLAIM ";
                        sInsQuery += "    SET CUST_NM = N'{0}' ";
                        sInsQuery += "       ,CUST_SEX = '{1}' ";
                        sInsQuery += "       ,CUST_TEL = '{2}' ";
                        sInsQuery += "       ,LOT_NO = '{3}' ";
                        sInsQuery += "       ,ITEM_SNM = N'{4}' ";
                        sInsQuery += "       ,BUY_DT = '{5}' ";
                        sInsQuery += "       ,CLAIM_PRC_GB = '{6}' ";
                        sInsQuery += "       ,CLAIM_PRC_COST = '{7}' ";
                        sInsQuery += "       ,CLAIM_PRC_MEMO = N'{8}' ";
                        sInsQuery += "       ,UPD_DT = '{9}' ";
                        sInsQuery += "       ,UPD_USER = '{10}' ";
                        sInsQuery += " WHERE CMP_CD = '{11}' ";
                        sInsQuery += "   AND SALE_DT = '{12}' ";
                        sInsQuery += "   AND STOR_CD = '{13}' ";
                        sInsQuery += "   AND POS_NO = '{14}' ";
                        sInsQuery += "   AND SEQ = '{15}' ";

                        sRegDateTime = DateTime.Now.ToString("yyyyMMddHHmmss");
                        sOrgSaleDt = sClaimInfo[0].Replace(".","").Substring(0, 8);

                        sQuery = string.Format(sInsQuery
                                                  , sClaimInfo[2]                           // 고객명
                                                  , sClaimInfo[3]                           // 성별
                                                  , sClaimInfo[4]                           // 연락처
                                                  , sClaimInfo[5]                           // 제품코드
                                                  , sClaimInfo[6]                           // 대표제품명
                                                  , sClaimInfo[7]                           // 구매일자
                                                  , sClaimInfo[8]                           // 처리구분
                                                  , CmUtil.DoubleParse(sClaimInfo[9])       // 처리비용
                                                  , sClaimInfo[10]                          // 처리내용
                                                  , sRegDateTime                            // 수정 일자
                                                  , m_cTrnStatus.Head.CashierId             // 수정 자
                                                  , m_cTrnStatus.Head.CmpCd                 // CMP_CD
                                                  , sOrgSaleDt                              // SALE_DT
                                                  , m_cTrnStatus.Head.StoreCd               // STOR_CD
                                                  , m_cTrnStatus.Head.PosNo                 // POS_NO
                                                  , sClaimInfo[1]                           // SEQ
                                                  );
                    }
                    else
                    {
                        //sInsQuery += " INSERT INTO POSLOG..TR_STORE_CLAIM ( ";
                        //sInsQuery += " CMP_CD ,SALE_DT ,STOR_CD ,POS_NO ,SEQ ,CUST_NM ,CUST_SEX ,CUST_TEL , LOT_NO, ITEM_SNM ";
                        //sInsQuery += ",BUY_DT ,CLAIM_PRC_GB ,CLAIM_PRC_COST ,CLAIM_PRC_MEMO, INST_DT ,INST_USER ,UPD_DT ,UPD_USER )  ";
                        //sInsQuery += "  SELECT '{0}', '{1}', '{2}', '{3}', ISNULL(MAX(SEQ), 0) + 1, '{4}', '{5}', '{6}', '{7}' , '{8}', ";
                        //sInsQuery += " '{9}','{10}', '{11}', '{12}', '{13}', '{14}', '{15}', '{16}' ";
                        //sInsQuery += " FROM POSLOG..TR_STORE_CLAIM ";
                        //sInsQuery += " WHERE CMP_CD = '{0}' ";
                        //sInsQuery += " AND STOR_CD = '{2}' ";
                        //sInsQuery += " AND SALE_DT = '{1}' ";

                        sInsQuery += " INSERT INTO POSLOG..TR_STORE_CLAIM ( ";
                        sInsQuery += " CMP_CD ,SALE_DT ,STOR_CD ,POS_NO ,SEQ ,CUST_NM ,CUST_SEX ,CUST_TEL , LOT_NO, ITEM_SNM ";
                        sInsQuery += ",BUY_DT ,CLAIM_PRC_GB ,CLAIM_PRC_COST ,CLAIM_PRC_MEMO, INST_DT ,INST_USER ,UPD_DT ,UPD_USER ";
                        sInsQuery += " ) VALUES ( '{0}', '{1}', '{2}', '{3}', '{4}', N'{5}', '{6}', '{7}', '{8}' , N'{9}', ";
                        sInsQuery += " '{10}','{11}', '{12}', N'{13}', '{14}', '{15}', '{16}', '{17}' )";

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

                        sQuery = string.Format(sInsQuery
                                                  , m_cTrnStatus.Head.CmpCd
                                                  , m_cTrnStatus.Head.SaleDate
                                                  , m_cTrnStatus.Head.StoreCd
                                                  , m_cTrnStatus.Head.PosNo
                                                  , sClaimInfo[1]                           // SEQ
                                                  , sClaimInfo[2]                           // 고객명
                                                  , sClaimInfo[3]                           // 성별
                                                  , sClaimInfo[4]                           // 연락처
                                                  , sClaimInfo[5]                           // 제품코드
                                                  , sClaimInfo[6]                           // 대표제품명
                                                  , sClaimInfo[7]                           // 구매일자
                                                  , sClaimInfo[8]                           // 처리구분
                                                  , CmUtil.DoubleParse(sClaimInfo[9])       // 처리비용
                                                  , sClaimInfo[10]                           // 처리내용
                                                  , sRegDateTime                            // 여유필드02
                                                  , m_cTrnStatus.Head.CashierId             // 최초 입력
                                                  , sRegDateTime                            // 여유필드04
                                                  , m_cTrnStatus.Head.CashierId             // 수정자
                                                  );
                    }
                }

                if (m_cSqlDbService.DBExecuteNonQuery(new string[] { sQuery }) == UserCom.OK)
                {
                    sReturn = CustomerClaimIrt(sClaimData, sRegDateTime);
                    if (sReturn != UserCom.RST_OK)
                    {
                        m_cSqlDbService.Rollback();
                        return sReturn;
                    }
                    else
                    {
                        m_cSqlDbService.Commit();
                        sReturn = 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 sReturn;
        }

        /// <summary>
        /// 고객불만 서버 전송
        /// </summary>
        /// <param name="sClaimData">고객불만정보</param>
        /// <param name="sClaimDate">고객불만접수일자</param>
        /// <returns></returns>
        private string CustomerClaimIrt(string sClaimData, string sClaimDate)
        {
            string sRet = UserCom.RST_ERR;

            try
            {
                string[] sClaimInfo = null;

                sClaimInfo = sClaimData.Split('|');

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

                htSendData.Add("INQ_TYPE", ItemConst.IRT_INQ_TYPE.STORECLAIM_MSG_REQ);
                htSendData.Add("STOR_CD", m_cPosStatus.Base.StoreNo);
                htSendData.Add("SALE_DT", m_cPosStatus.Base.SaleDate);
                htSendData.Add("SEQ", sClaimInfo[1]);
                htSendData.Add("CUST_NM", sClaimInfo[2]);
                htSendData.Add("CUST_SEX", sClaimInfo[3]);
                htSendData.Add("CUST_TEL", sClaimInfo[4]);
                htSendData.Add("LOT_NO", sClaimInfo[5]);
                htSendData.Add("ITEM_SNM", sClaimInfo[6]);
                htSendData.Add("BUY_DT", sClaimInfo[7]);
                htSendData.Add("CLAIM_PRC_GB", sClaimInfo[8]);
                htSendData.Add("CLAIM_PRC_COST", sClaimInfo[9]);
                htSendData.Add("CLAIM_PRC_MEMO", sClaimInfo[10]);
                htSendData.Add("REG_YMDHMS", sClaimDate);
                htSendData.Add("USER_ID", m_cTrnStatus.Head.CashierId);

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

                if (htRecvData[Column.IQ_SALEONCREDIT_CUSTINQ_RSP.DATA.RES_CD].ToString() != "00")
                {
                    sRet = UserCom.RST_ERR;
                    return sRet;
                }

                sRet = UserCom.RST_OK;

                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 UserCom.RST_ERR;
        }

        /// <summary>
        /// 고객불만 내용 영수증 출력
        /// </summary>
        /// <param name="sClaimData">영수증 데이터</param>
        /// <returns></returns>
        public string CustomerClaimPrt(string sClaimData)
        {
            string[] sClaimInfo = null;
            string sRet = UserCom.RST_ERR;

            try
            {
                sClaimInfo = sClaimData.Split('|');

                m_cClaimData = new Column.IQ_STORECLAIM_MSG_REQ.DATA();
            
                m_cClaimData.SALE_DT = sClaimInfo[0];
                m_cClaimData.CUST_NM = sClaimInfo[2];
                m_cClaimData.CUST_SEX = sClaimInfo[3];
                m_cClaimData.CUST_TEL = sClaimInfo[4];
                m_cClaimData.ITEM_SNM = sClaimInfo[6];
                m_cClaimData.BUY_DT = sClaimInfo[7];
                m_cClaimData.LOT_NO = sClaimInfo[5];
                m_cClaimData.CLAIM_PRC_GB = sClaimInfo[8];
                m_cClaimData.CLAIM_PRC_COST = sClaimInfo[9];
                m_cClaimData.CLAIM_PRC_MEMO = sClaimInfo[10];

                ArrayList aClaimData = (ArrayList)StateObject.GetItemObject(Column.IQ_STORECLAIM_MSG_REQ.ITEM);     // 기타 내역 받아 오기

                aClaimData.Add(m_cClaimData);

                // 영수증 출력
                sRet = m_cSaleComplete.PosClaimReceiptExecute();
                if (sRet != UserCom.RST_OK) return sRet;
            }
            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;
        }
    }
}
