using System;
using System.Collections.Generic;
using Library;
using LitJson;
using System.Linq;
using System.Data;
using System.Threading;
using MySystem.PxcModels;

namespace MySystem
{
    public class StatGdService
    {
        public readonly static StatGdService Instance = new StatGdService();
        private StatGdService()
        { }






        // 统计交易额V2
        public void Start()
        {
            Thread th = new Thread(StartDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StartDo()
        {
            while (true)
            {
                if(DateTime.Now.Hour >= 3 && RedisDbconn.Instance.Get<string>("StatServerStatus") == "1")
                {
                    StatTradeAmount();
                }
                Thread.Sleep(1000);
            }
        }
        public void StatTradeAmount()
        {
            string connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "统计创客归档交易日志");
            WebCMSEntities db = new WebCMSEntities();
            KxsMainModels.WebCMSEntities maindb = new KxsMainModels.WebCMSEntities();
            using (var tran = db.Database.BeginTransaction())
            {
                try
                {
                    string start = "2024-10-01 00:00:00";
                    DataTable idsDt = CustomerSqlConn.dtable("select Id from ConsumerOrders where Id>=318109 and CreateDate>='" + start + "' and Status>0 and Version=1 order by Id limit 50", connstr);
                    if(idsDt.Rows.Count > 0)
                    {
                        string ids = "";
                        foreach (DataRow idsDr in idsDt.Rows)
                        {
                            ids += idsDr["Id"].ToString() + ",";
                        }
                        DataTable selfDt = CustomerSqlConn.dtable("select UserId,MerchantId,SnNo,PayMode,IsAct,DATE_FORMAT(CreateDate,'%Y%m%d'),sum(PayMoney),count(Id),sum(MaxDivi),sum(MerchantActualAmount) from ConsumerOrders where Id in (" + ids.TrimEnd(',') + ") group by UserId,MerchantId,SnNo,PayMode,IsAct,DATE_FORMAT(CreateDate,'%Y%m%d')", connstr);
                        if (selfDt.Rows.Count > 0)
                        {
                            function.WriteLog("统计人数:" + selfDt.Rows.Count + "\n\n", "统计创客归档交易日志");
                            foreach (DataRow selfDr in selfDt.Rows)
                            {
                                int UserId = int.Parse(selfDr["UserId"].ToString());
                                int MerchantId = int.Parse(selfDr["MerchantId"].ToString());
                                MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new MerchantInfo();
                                if (UserId == 0)
                                {
                                    UserId = merchant.UserId;
                                }
                                KxsMainModels.Users user = maindb.Users.FirstOrDefault(m => m.Id == UserId) ?? new KxsMainModels.Users();
                                string ParentNav = user.ParentNav; //selfDr["ParentNav"].ToString();
                                if (merchant.CreateDate < DateTime.Now.AddMonths(-9))
                                {
                                    StatBefore(db, selfDr, UserId, ParentNav);
                                }
                                else
                                {
                                    StatAfter(db, selfDr, UserId, ParentNav);
                                }
                            }
                            CustomerSqlConn.op("update ConsumerOrders set Version=2 where Id in (" + ids.TrimEnd(',') + ")", connstr);
                        }
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "统计创客归档交易日志异常");
                }
            }
            db.Dispose();
            maindb.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "统计创客归档交易日志");
        }

        
        public void StatBefore(WebCMSEntities db, DataRow selfDr, int UserId, string ParentNav)
        {
            int MerchantId = int.Parse(selfDr["MerchantId"].ToString());
            int PayMode = int.Parse(selfDr["PayMode"].ToString());
            int IsAct = int.Parse(selfDr["IsAct"].ToString());
            string SnNo = selfDr["SnNo"].ToString();
            string TradeDate = selfDr[5].ToString();
            decimal TradeAmount = decimal.Parse(selfDr[6].ToString());
            int TradeCount = int.Parse(selfDr[7].ToString());
            decimal MaxDivi = decimal.Parse(selfDr[8].ToString());
            decimal ActualAmount = decimal.Parse(selfDr[9].ToString());
            string TradeMonth = TradeDate.Substring(0, 6);

            //创客交易额
            UserAmountSummaryBefore selfStat = db.UserAmountSummaryBefore.FirstOrDefault(m => m.UserId == UserId && m.IsAct == IsAct && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.PayMode == PayMode && m.SeoTitle == "self");
            if (selfStat == null)
            {
                selfStat = db.UserAmountSummaryBefore.Add(new UserAmountSummaryBefore()
                {
                    UserId = UserId,
                    TradeMonth = TradeMonth,
                    TradeDate = TradeDate,
                    PayMode = PayMode,
                    IsAct = IsAct,
                    SeoTitle = "self",
                }).Entity;
                db.SaveChanges();
            }
            selfStat.TotalAmount += TradeAmount;
            selfStat.TradeCount += TradeCount;
            ParentNav += "," + UserId + ",";
            if (!string.IsNullOrEmpty(ParentNav))
            {
                string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                foreach (string NavUserIdString in ParentNavList)
                {
                    int NavUserId = int.Parse(NavUserIdString);
                    UserAmountSummaryBefore teamStat = db.UserAmountSummaryBefore.FirstOrDefault(m => m.UserId == NavUserId && m.IsAct == IsAct && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.PayMode == PayMode && m.SeoTitle == "team");
                    if (teamStat == null)
                    {
                        teamStat = db.UserAmountSummaryBefore.Add(new UserAmountSummaryBefore()
                        {
                            UserId = NavUserId,
                            TradeMonth = TradeMonth,
                            TradeDate = TradeDate,
                            PayMode = PayMode,
                            IsAct = IsAct,
                            SeoTitle = "team",
                        }).Entity;
                        db.SaveChanges();
                    }
                    teamStat.TotalAmount += TradeAmount;
                    teamStat.TradeCount += TradeCount;
                }
            }
            db.SaveChanges();
        }

        public void StatAfter(WebCMSEntities db, DataRow selfDr, int UserId, string ParentNav)
        {
            int MerchantId = int.Parse(selfDr["MerchantId"].ToString());
            int PayMode = int.Parse(selfDr["PayMode"].ToString());
            int IsAct = int.Parse(selfDr["IsAct"].ToString());
            string SnNo = selfDr["SnNo"].ToString();
            string TradeDate = selfDr[5].ToString();
            decimal TradeAmount = decimal.Parse(selfDr[6].ToString());
            int TradeCount = int.Parse(selfDr[7].ToString());
            decimal MaxDivi = decimal.Parse(selfDr[8].ToString());
            decimal ActualAmount = decimal.Parse(selfDr[9].ToString());
            string TradeMonth = TradeDate.Substring(0, 6);

            //创客交易额
            UserAmountSummaryAfter selfStat = db.UserAmountSummaryAfter.FirstOrDefault(m => m.UserId == UserId && m.IsAct == IsAct && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.PayMode == PayMode && m.SeoTitle == "self");
            if (selfStat == null)
            {
                selfStat = db.UserAmountSummaryAfter.Add(new UserAmountSummaryAfter()
                {
                    UserId = UserId,
                    TradeMonth = TradeMonth,
                    TradeDate = TradeDate,
                    PayMode = PayMode,
                    IsAct = IsAct,
                    SeoTitle = "self",
                }).Entity;
                db.SaveChanges();
            }
            selfStat.TotalAmount += TradeAmount;
            selfStat.TradeCount += TradeCount;
            ParentNav += "," + UserId + ",";
            if (!string.IsNullOrEmpty(ParentNav))
            {
                string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                foreach (string NavUserIdString in ParentNavList)
                {
                    int NavUserId = int.Parse(NavUserIdString);
                    UserAmountSummaryAfter teamStat = db.UserAmountSummaryAfter.FirstOrDefault(m => m.UserId == NavUserId && m.IsAct == IsAct && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.PayMode == PayMode && m.SeoTitle == "team");
                    if (teamStat == null)
                    {
                        teamStat = db.UserAmountSummaryAfter.Add(new UserAmountSummaryAfter()
                        {
                            UserId = NavUserId,
                            TradeMonth = TradeMonth,
                            TradeDate = TradeDate,
                            PayMode = PayMode,
                            IsAct = IsAct,
                            SeoTitle = "team",
                        }).Entity;
                        db.SaveChanges();
                    }
                    teamStat.TotalAmount += TradeAmount;
                    teamStat.TradeCount += TradeCount;
                }
            }
            db.SaveChanges();
        }



    }
}