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

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






        // 统计交易额V2
        public void Start()
        {
            Thread th = new Thread(StartDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StartDo()
        {
            while (true)
            {
                if(DateTime.Now.Hour >= 0 && RedisDbconn.Instance.Get<string>("StatServerStatus") == "1")
                {
                    StatTradeAmount();
                }
                Thread.Sleep(100);
            }
        }
        public void StatTradeAmount()
        {
            string connstr = Library.ConfigurationManager.AppSettings["SqlConnStr2"].ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "统计创客归档交易日志2");
            PxcModels.WebCMSEntities db1 = new PxcModels.WebCMSEntities();
            PxcModels2.WebCMSEntities db = new PxcModels2.WebCMSEntities();
            KxsMainModels.WebCMSEntities maindb = new KxsMainModels.WebCMSEntities();
            KxsProductModels.WebCMSEntities pdb = new KxsProductModels.WebCMSEntities();
            using (var tran = db.Database.BeginTransaction())
            {
                try
                {
                    string start = "2025-01-01 00:00:00";
                    DataTable idsDt = CustomerSqlConn.dtable("select Id from ConsumerOrders where Id>=3344113 and CreateDate>='" + start + "' and Status>0 and Version=2 order by Id limit 1000", 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),Sort from ConsumerOrders where Id in (" + ids.TrimEnd(',') + ") group by UserId,MerchantId,SnNo,PayMode,IsAct,DATE_FORMAT(CreateDate,'%Y%m%d'),Sort", connstr);
                        if (selfDt.Rows.Count > 0)
                        {
                            function.WriteLog("统计人数:" + selfDt.Rows.Count + "\n\n", "统计创客归档交易日志2");
                            foreach (DataRow selfDr in selfDt.Rows)
                            {
                                int UserId = int.Parse(selfDr["UserId"].ToString());
                                int MerchantId = int.Parse(selfDr["MerchantId"].ToString());
                                string SnNo = selfDr["SnNo"].ToString();
                                DateTime BindTime = DateTime.Now;
                                MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new MerchantInfo();
                                if(merchant.BrandId == 1)
                                {
                                    KxsMachine pos = pdb.KxsMachine.FirstOrDefault(m => m.PosSn == SnNo && m.BindStatus == 1);
                                    if(pos != null)
                                    {
                                        if(pos.BindTime != null) BindTime = pos.BindTime.Value;
                                    }
                                }
                                else
                                {
                                    PxcModels.PosMachinesTwo pos = db1.PosMachinesTwo.FirstOrDefault(m => m.PosSn == SnNo) ?? new PxcModels.PosMachinesTwo();
                                    if(pos.BindingTime != null) BindTime = pos.BindingTime.Value;
                                }
                                KxsMainModels.Users user = maindb.Users.FirstOrDefault(m => m.Id == UserId) ?? new KxsMainModels.Users();
                                string ParentNav = user.ParentNav; //selfDr["ParentNav"].ToString();
                                if (BindTime < DateTime.Now.AddMonths(-9))
                                {
                                    if (BindTime < DateTime.Parse("2025-01-01 00:00:00"))
                                    {
                                        StatOldBefore(db, selfDr, UserId, ParentNav);
                                    }
                                    else
                                    {
                                        StatNewBefore(db, selfDr, UserId, ParentNav);
                                    }
                                }
                                else
                                {
                                    if (BindTime < DateTime.Parse("2025-01-01 00:00:00"))
                                    {
                                        StatOldAfter(db, selfDr, UserId, ParentNav);
                                    }
                                    else
                                    {
                                        StatNewAfter(db, selfDr, UserId, ParentNav);
                                    }
                                }
                            }
                            CustomerSqlConn.op("update ConsumerOrders set Version=3 where Id in (" + ids.TrimEnd(',') + ")", connstr);
                        }
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "统计创客归档交易日志2异常");
                }
            }
            db1.Dispose();
            db.Dispose();
            maindb.Dispose();
            pdb.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "统计创客归档交易日志2");
        }

        
        public void StatNewBefore(PxcModels2.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);
            int Sort = int.Parse(selfDr["Sort"].ToString());

            //创客交易额
            UserAmountSummaryNewBefore selfStat = db.UserAmountSummaryNewBefore.FirstOrDefault(m => m.Id >= 17385 && m.UserId == UserId && m.IsAct == IsAct && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.PayMode == PayMode && m.SeoTitle == "self" && m.Sort == Sort);
            if (selfStat == null)
            {
                selfStat = db.UserAmountSummaryNewBefore.Add(new UserAmountSummaryNewBefore()
                {
                    UserId = UserId,
                    TradeMonth = TradeMonth,
                    TradeDate = TradeDate,
                    PayMode = PayMode,
                    IsAct = IsAct,
                    SeoTitle = "self",
                    Sort = Sort,
                }).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);
                    UserAmountSummaryNewBefore teamStat = db.UserAmountSummaryNewBefore.FirstOrDefault(m => m.Id >= 17385 && m.UserId == NavUserId && m.IsAct == IsAct && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.PayMode == PayMode && m.SeoTitle == "team" && m.Sort == Sort);
                    if (teamStat == null)
                    {
                        teamStat = db.UserAmountSummaryNewBefore.Add(new UserAmountSummaryNewBefore()
                        {
                            UserId = NavUserId,
                            TradeMonth = TradeMonth,
                            TradeDate = TradeDate,
                            PayMode = PayMode,
                            IsAct = IsAct,
                            SeoTitle = "team",
                            Sort = Sort,
                        }).Entity;
                        db.SaveChanges();
                    }
                    teamStat.TotalAmount += TradeAmount;
                    teamStat.TradeCount += TradeCount;
                }
            }
            db.SaveChanges();
        }

        public void StatNewAfter(PxcModels2.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);
            int Sort = int.Parse(selfDr["Sort"].ToString());

            //创客交易额
            UserAmountSummaryNewAfter selfStat = db.UserAmountSummaryNewAfter.FirstOrDefault(m => m.Id >= 805733 && m.UserId == UserId && m.IsAct == IsAct && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.PayMode == PayMode && m.SeoTitle == "self" && m.Sort == Sort);
            if (selfStat == null)
            {
                selfStat = db.UserAmountSummaryNewAfter.Add(new UserAmountSummaryNewAfter()
                {
                    UserId = UserId,
                    TradeMonth = TradeMonth,
                    TradeDate = TradeDate,
                    PayMode = PayMode,
                    IsAct = IsAct,
                    SeoTitle = "self",
                    Sort = Sort,
                }).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);
                    UserAmountSummaryNewAfter teamStat = db.UserAmountSummaryNewAfter.FirstOrDefault(m => m.Id >= 805733 && m.UserId == NavUserId && m.IsAct == IsAct && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.PayMode == PayMode && m.SeoTitle == "team" && m.Sort == Sort);
                    if (teamStat == null)
                    {
                        teamStat = db.UserAmountSummaryNewAfter.Add(new UserAmountSummaryNewAfter()
                        {
                            UserId = NavUserId,
                            TradeMonth = TradeMonth,
                            TradeDate = TradeDate,
                            PayMode = PayMode,
                            IsAct = IsAct,
                            SeoTitle = "team",
                            Sort = Sort,
                        }).Entity;
                        db.SaveChanges();
                    }
                    teamStat.TotalAmount += TradeAmount;
                    teamStat.TradeCount += TradeCount;
                }
            }
            db.SaveChanges();
        }





        public void StatOldBefore(PxcModels2.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);
            int Sort = int.Parse(selfDr["Sort"].ToString());

            //创客交易额
            UserAmountSummaryOldBefore selfStat = db.UserAmountSummaryOldBefore.FirstOrDefault(m => m.Id >= 17385 && m.UserId == UserId && m.IsAct == IsAct && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.PayMode == PayMode && m.SeoTitle == "self" && m.Sort == Sort);
            if (selfStat == null)
            {
                selfStat = db.UserAmountSummaryOldBefore.Add(new UserAmountSummaryOldBefore()
                {
                    UserId = UserId,
                    TradeMonth = TradeMonth,
                    TradeDate = TradeDate,
                    PayMode = PayMode,
                    IsAct = IsAct,
                    SeoTitle = "self",
                    Sort = Sort,
                }).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);
                    UserAmountSummaryOldBefore teamStat = db.UserAmountSummaryOldBefore.FirstOrDefault(m => m.Id >= 17385 && m.UserId == NavUserId && m.IsAct == IsAct && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.PayMode == PayMode && m.SeoTitle == "team" && m.Sort == Sort);
                    if (teamStat == null)
                    {
                        teamStat = db.UserAmountSummaryOldBefore.Add(new UserAmountSummaryOldBefore()
                        {
                            UserId = NavUserId,
                            TradeMonth = TradeMonth,
                            TradeDate = TradeDate,
                            PayMode = PayMode,
                            IsAct = IsAct,
                            SeoTitle = "team",
                            Sort = Sort,
                        }).Entity;
                        db.SaveChanges();
                    }
                    teamStat.TotalAmount += TradeAmount;
                    teamStat.TradeCount += TradeCount;
                }
            }
            db.SaveChanges();
        }

        public void StatOldAfter(PxcModels2.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);
            int Sort = int.Parse(selfDr["Sort"].ToString());

            //创客交易额
            UserAmountSummaryOldAfter selfStat = db.UserAmountSummaryOldAfter.FirstOrDefault(m => m.Id >= 805733 && m.UserId == UserId && m.IsAct == IsAct && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.PayMode == PayMode && m.SeoTitle == "self" && m.Sort == Sort);
            if (selfStat == null)
            {
                selfStat = db.UserAmountSummaryOldAfter.Add(new UserAmountSummaryOldAfter()
                {
                    UserId = UserId,
                    TradeMonth = TradeMonth,
                    TradeDate = TradeDate,
                    PayMode = PayMode,
                    IsAct = IsAct,
                    SeoTitle = "self",
                    Sort = Sort,
                }).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);
                    UserAmountSummaryOldAfter teamStat = db.UserAmountSummaryOldAfter.FirstOrDefault(m => m.Id >= 805733 && m.UserId == NavUserId && m.IsAct == IsAct && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.PayMode == PayMode && m.SeoTitle == "team" && m.Sort == Sort);
                    if (teamStat == null)
                    {
                        teamStat = db.UserAmountSummaryOldAfter.Add(new UserAmountSummaryOldAfter()
                        {
                            UserId = NavUserId,
                            TradeMonth = TradeMonth,
                            TradeDate = TradeDate,
                            PayMode = PayMode,
                            IsAct = IsAct,
                            SeoTitle = "team",
                            Sort = Sort,
                        }).Entity;
                        db.SaveChanges();
                    }
                    teamStat.TotalAmount += TradeAmount;
                    teamStat.TradeCount += TradeCount;
                }
            }
            db.SaveChanges();
        }

    }
}