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 StatSimService
    {
        public readonly static StatSimService Instance = new StatSimService();
        private StatSimService()
        { }






        // 统计交易额V2
        public void Start()
        {
            Thread th = new Thread(StartDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StartDo()
        {
            while (true)
            {
                if (RedisDbconn.Instance.Get<string>("StatServerStatus") == "1" && DateTime.Now.Hour >= 3)
                {
                    StatTrade();
                }
                Thread.Sleep(300);
            }
        }

        public void StatTrade(int Id = 0)
        {
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "实时统计广电卡归档交易额日志");
            WebCMSEntities db = new WebCMSEntities();
            using (var tran = db.Database.BeginTransaction())
            {
                try
                {
                    string startId = function.ReadInstance("/TradeRecord/IdSim.txt");
                    if (string.IsNullOrEmpty(startId))
                    {
                        startId = "19613145";
                    }
                    string sql = "select Id from TradeRecord where Id>=" + startId + " and CreateDate>='2024-09-01 00:00:00' and DirectFlag=0 and ActStatus=1 and BrandId=14 order by Id limit 500";
                    if (Id > 0)
                    {
                        sql = "select Id from TradeRecord where Id=" + Id;
                    }
                    DataTable idsDt = CustomerSqlConn.dtable(sql, AppConfig.Base.SqlConn);
                    if (idsDt.Rows.Count > 0)
                    {
                        string ids = "";
                        foreach (DataRow idsDr in idsDt.Rows)
                        {
                            ids += idsDr["Id"].ToString() + ",";
                            if (Id == 0)
                            {
                                startId = idsDr["Id"].ToString();
                            }
                        }
                        DataTable selfDt = CustomerSqlConn.dtable("select UserId,ParentNav,BrandId,BankCardType,QrPayFlag,MerHelpFlag,Version,CapFlag,VipFlag,PayType,DATE_FORMAT(CreateDate,'%Y%m%d'),sum(TradeAmount),count(Id),SnNo from TradeRecord where Id in (" + ids.TrimEnd(',') + ") group by UserId,ParentNav,BrandId,BankCardType,QrPayFlag,MerHelpFlag,Version,CapFlag,VipFlag,PayType,DATE_FORMAT(CreateDate,'%Y%m%d'),SnNo", AppConfig.Base.SqlConn);
                        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());
                                string SnNo = selfDr["SnNo"].ToString();
                                PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == SnNo) ?? new PosMachinesTwo();
                                if (UserId == 0)
                                {
                                    UserId = pos.UserId;
                                }
                                Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                                string ParentNav = user.ParentNav; //selfDr["ParentNav"].ToString();
                                if (pos.BindingTime < DateTime.Now.AddMonths(-9))
                                {
                                    StatBefore(db, selfDr, UserId, ParentNav);
                                }
                                else
                                {
                                    StatAfter(db, selfDr, UserId, ParentNav);
                                }
                            }
                            CustomerSqlConn.op("update TradeRecord set DirectFlag=1 where Id in (" + ids.TrimEnd(',') + ")", AppConfig.Base.SqlConn);
                            if (Id == 0)
                            {
                                function.WritePage("/TradeRecord/", "IdSim.txt", startId);
                            }
                        }
                        db.SaveChanges();
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "实时统计广电卡归档交易额异常");
                }
            }
            db.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 BrandId = int.Parse(selfDr["BrandId"].ToString());
            int BankCardType = int.Parse(selfDr["BankCardType"].ToString());
            int QrPayFlag = int.Parse(selfDr["QrPayFlag"].ToString());
            int MerHelpFlag = int.Parse(selfDr["MerHelpFlag"].ToString());
            int Version = int.Parse(selfDr["Version"].ToString());
            int CapFlag = int.Parse(selfDr["CapFlag"].ToString());
            int VipFlag = int.Parse(selfDr["VipFlag"].ToString());
            int PayType = int.Parse(selfDr["PayType"].ToString());
            string TradeDate = selfDr[10].ToString();
            decimal TradeAmount = decimal.Parse(selfDr[11].ToString());
            int TradeCount = int.Parse(selfDr[12].ToString());
            string TradeMonth = TradeDate.Substring(0, 6);
            ParentNav += "," + UserId + ",";

            if (Version < 2)
            {
                TradeDaySummaryBefore selfStat = db.TradeDaySummaryBefore.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.VipFlag == VipFlag && m.PayType == PayType && m.SeoTitle == "self");
                if (selfStat == null)
                {
                    selfStat = db.TradeDaySummaryBefore.Add(new TradeDaySummaryBefore()
                    {
                        UserId = UserId,
                        TradeMonth = TradeMonth,
                        TradeDate = TradeDate,
                        BrandId = BrandId,
                        QueryCount = QrPayFlag,
                        VipFlag = VipFlag,
                        PayType = PayType,
                        SeoTitle = "self",
                    }).Entity;
                    db.SaveChanges();
                }
                if (BankCardType == 0)
                {
                    if (Version == 1)
                    {
                        selfStat.ProfitDirectDebitTradeAmt += TradeAmount;
                        if (CapFlag == 1)
                        {
                            selfStat.ProfitDirectDebitCapTradeAmt += TradeAmount;
                            selfStat.ProfitDirectDebitCapNum += TradeCount;
                        }
                    }
                    else if (MerHelpFlag == 1)
                    {
                        selfStat.HelpDirectDebitTradeAmt += TradeAmount;
                        if (CapFlag == 1)
                        {
                            selfStat.HelpDirectDebitCapTradeAmt += TradeAmount;
                            selfStat.HelpDirectDebitCapNum += TradeCount;
                        }
                    }
                    else
                    {
                        selfStat.NotHelpDirectDebitTradeAmt += TradeAmount;
                        if (CapFlag == 1)
                        {
                            selfStat.NotHelpDirectDebitCapTradeAmt += TradeAmount;
                            selfStat.NotHelpDirectDebitCapNum += TradeCount;
                        }
                    }
                }
                else if (BankCardType != 0)
                {
                    if (Version == 1)
                    {
                        selfStat.ProfitDirectTradeAmt += TradeAmount;
                    }
                    else if (MerHelpFlag == 1)
                    {
                        selfStat.HelpDirectTradeAmt += TradeAmount;
                    }
                    else
                    {
                        selfStat.NotHelpDirectTradeAmt += TradeAmount;
                    }
                }
                if (!string.IsNullOrEmpty(ParentNav))
                {
                    string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                    foreach (string NavUserIdString in ParentNavList)
                    {
                        int NavUserId = int.Parse(NavUserIdString);
                        TradeDaySummaryBefore teamStat = db.TradeDaySummaryBefore.FirstOrDefault(m => m.UserId == NavUserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.VipFlag == VipFlag && m.PayType == PayType && m.SeoTitle == "team");
                        if (teamStat == null)
                        {
                            teamStat = db.TradeDaySummaryBefore.Add(new TradeDaySummaryBefore()
                            {
                                UserId = NavUserId,
                                TradeMonth = TradeMonth,
                                TradeDate = TradeDate,
                                BrandId = BrandId,
                                QueryCount = QrPayFlag,
                                VipFlag = VipFlag,
                                PayType = PayType,
                                SeoTitle = "team",
                            }).Entity;
                            db.SaveChanges();
                        }
                        if (BankCardType == 0)
                        {
                            if (Version == 1)
                            {
                                teamStat.ProfitNonDirectDebitTradeAmt += TradeAmount;
                                if (CapFlag == 1)
                                {
                                    teamStat.ProfitDirectDebitCapTradeAmt += TradeAmount;
                                    teamStat.ProfitDirectDebitCapNum += TradeCount;
                                }
                            }
                            else if (MerHelpFlag == 1)
                            {
                                teamStat.HelpNonDirectDebitTradeAmt += TradeAmount;
                                if (CapFlag == 1)
                                {
                                    teamStat.HelpDirectDebitCapTradeAmt += TradeAmount;
                                    teamStat.HelpDirectDebitCapNum += TradeCount;
                                }
                            }
                            else
                            {
                                teamStat.NotHelpNonDirectDebitTradeAmt += TradeAmount;
                                if (CapFlag == 1)
                                {
                                    teamStat.NotHelpDirectDebitCapTradeAmt += TradeAmount;
                                    teamStat.NotHelpDirectDebitCapNum += TradeCount;
                                }
                            }
                        }
                        else if (BankCardType != 0)
                        {
                            if (Version == 1)
                            {
                                teamStat.ProfitNonDirectTradeAmt += TradeAmount;
                            }
                            else if (MerHelpFlag == 1)
                            {
                                teamStat.HelpNonDirectTradeAmt += TradeAmount;
                            }
                            else
                            {
                                teamStat.NotHelpNonDirectTradeAmt += TradeAmount;
                            }
                        }
                    }
                }
            }
            else
            {
                //盈利期，费率0.6
                TradeDaySummary2Before selfStat2 = db.TradeDaySummary2Before.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.VipFlag == VipFlag && m.PayType == PayType && m.SeoTitle == "self");
                if (selfStat2 == null)
                {
                    selfStat2 = db.TradeDaySummary2Before.Add(new TradeDaySummary2Before()
                    {
                        UserId = UserId,
                        TradeMonth = TradeMonth,
                        TradeDate = TradeDate,
                        BrandId = BrandId,
                        QueryCount = QrPayFlag,
                        VipFlag = VipFlag,
                        PayType = PayType,
                        SeoTitle = "self",
                    }).Entity;
                    db.SaveChanges();
                }
                if (BankCardType == 0)
                {
                    if (Version == 2)
                    {
                        selfStat2.ProfitDebitTradeAmt += TradeAmount;
                        if (CapFlag == 1)
                        {
                            selfStat2.ProfitDebitCapTradeAmt += TradeAmount;
                            selfStat2.ProfitDebitCapNum += TradeCount;
                        }
                    }
                }
                else if (BankCardType != 0)
                {
                    if (Version == 2)
                    {
                        selfStat2.ProfitTradeAmt += TradeAmount;
                    }
                }
                if (!string.IsNullOrEmpty(ParentNav))
                {
                    string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                    foreach (string NavUserIdString in ParentNavList)
                    {
                        int NavUserId = int.Parse(NavUserIdString);
                        TradeDaySummary2Before teamStat2 = db.TradeDaySummary2Before.FirstOrDefault(m => m.UserId == NavUserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.VipFlag == VipFlag && m.PayType == PayType && m.SeoTitle == "team");
                        if (teamStat2 == null)
                        {
                            teamStat2 = db.TradeDaySummary2Before.Add(new TradeDaySummary2Before()
                            {
                                UserId = NavUserId,
                                TradeMonth = TradeMonth,
                                TradeDate = TradeDate,
                                BrandId = BrandId,
                                QueryCount = QrPayFlag,
                                VipFlag = VipFlag,
                                PayType = PayType,
                                SeoTitle = "team",
                            }).Entity;
                            db.SaveChanges();
                        }
                        if (BankCardType == 0)
                        {
                            if (Version == 2)
                            {
                                teamStat2.ProfitDebitTradeAmt += TradeAmount;
                                if (CapFlag == 1)
                                {
                                    teamStat2.ProfitDebitCapTradeAmt += TradeAmount;
                                    teamStat2.ProfitDebitCapNum += TradeCount;
                                }
                            }
                        }
                        else if (BankCardType != 0)
                        {
                            if (Version == 2)
                            {
                                teamStat2.ProfitTradeAmt += TradeAmount;
                            }
                        }
                    }
                }
            }
        }

        public void StatAfter(WebCMSEntities db, DataRow selfDr, int UserId, string ParentNav)
        {
            int BrandId = int.Parse(selfDr["BrandId"].ToString());
            int BankCardType = int.Parse(selfDr["BankCardType"].ToString());
            int QrPayFlag = int.Parse(selfDr["QrPayFlag"].ToString());
            int MerHelpFlag = int.Parse(selfDr["MerHelpFlag"].ToString());
            int Version = int.Parse(selfDr["Version"].ToString());
            int CapFlag = int.Parse(selfDr["CapFlag"].ToString());
            int VipFlag = int.Parse(selfDr["VipFlag"].ToString());
            int PayType = int.Parse(selfDr["PayType"].ToString());
            string TradeDate = selfDr[10].ToString();
            decimal TradeAmount = decimal.Parse(selfDr[11].ToString());
            int TradeCount = int.Parse(selfDr[12].ToString());
            string TradeMonth = TradeDate.Substring(0, 6);
            ParentNav += "," + UserId + ",";
            if (Version < 2)
            {
                TradeDaySummaryAfter selfStat = db.TradeDaySummaryAfter.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.VipFlag == VipFlag && m.PayType == PayType && m.SeoTitle == "self");
                if (selfStat == null)
                {
                    selfStat = db.TradeDaySummaryAfter.Add(new TradeDaySummaryAfter()
                    {
                        UserId = UserId,
                        TradeMonth = TradeMonth,
                        TradeDate = TradeDate,
                        BrandId = BrandId,
                        QueryCount = QrPayFlag,
                        VipFlag = VipFlag,
                        PayType = PayType,
                        SeoTitle = "self",
                    }).Entity;
                    db.SaveChanges();
                }
                if (BankCardType == 0)
                {
                    if (Version == 1)
                    {
                        selfStat.ProfitDirectDebitTradeAmt += TradeAmount;
                        if (CapFlag == 1)
                        {
                            selfStat.ProfitDirectDebitCapTradeAmt += TradeAmount;
                            selfStat.ProfitDirectDebitCapNum += TradeCount;
                        }
                    }
                    else if (MerHelpFlag == 1)
                    {
                        selfStat.HelpDirectDebitTradeAmt += TradeAmount;
                        if (CapFlag == 1)
                        {
                            selfStat.HelpDirectDebitCapTradeAmt += TradeAmount;
                            selfStat.HelpDirectDebitCapNum += TradeCount;
                        }
                    }
                    else
                    {
                        selfStat.NotHelpDirectDebitTradeAmt += TradeAmount;
                        if (CapFlag == 1)
                        {
                            selfStat.NotHelpDirectDebitCapTradeAmt += TradeAmount;
                            selfStat.NotHelpDirectDebitCapNum += TradeCount;
                        }
                    }
                }
                else if (BankCardType != 0)
                {
                    if (Version == 1)
                    {
                        selfStat.ProfitDirectTradeAmt += TradeAmount;
                    }
                    else if (MerHelpFlag == 1)
                    {
                        selfStat.HelpDirectTradeAmt += TradeAmount;
                    }
                    else
                    {
                        selfStat.NotHelpDirectTradeAmt += TradeAmount;
                    }
                }
                if (!string.IsNullOrEmpty(ParentNav))
                {
                    string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                    foreach (string NavUserIdString in ParentNavList)
                    {
                        int NavUserId = int.Parse(NavUserIdString);
                        TradeDaySummaryAfter teamStat = db.TradeDaySummaryAfter.FirstOrDefault(m => m.UserId == NavUserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.VipFlag == VipFlag && m.PayType == PayType && m.SeoTitle == "team");
                        if (teamStat == null)
                        {
                            teamStat = db.TradeDaySummaryAfter.Add(new TradeDaySummaryAfter()
                            {
                                UserId = NavUserId,
                                TradeMonth = TradeMonth,
                                TradeDate = TradeDate,
                                BrandId = BrandId,
                                QueryCount = QrPayFlag,
                                VipFlag = VipFlag,
                                PayType = PayType,
                                SeoTitle = "team",
                            }).Entity;
                            db.SaveChanges();
                        }
                        if (BankCardType == 0)
                        {
                            if (Version == 1)
                            {
                                teamStat.ProfitNonDirectDebitTradeAmt += TradeAmount;
                                if (CapFlag == 1)
                                {
                                    teamStat.ProfitDirectDebitCapTradeAmt += TradeAmount;
                                    teamStat.ProfitDirectDebitCapNum += TradeCount;
                                }
                            }
                            else if (MerHelpFlag == 1)
                            {
                                teamStat.HelpNonDirectDebitTradeAmt += TradeAmount;
                                if (CapFlag == 1)
                                {
                                    teamStat.HelpDirectDebitCapTradeAmt += TradeAmount;
                                    teamStat.HelpDirectDebitCapNum += TradeCount;
                                }
                            }
                            else
                            {
                                teamStat.NotHelpNonDirectDebitTradeAmt += TradeAmount;
                                if (CapFlag == 1)
                                {
                                    teamStat.NotHelpDirectDebitCapTradeAmt += TradeAmount;
                                    teamStat.NotHelpDirectDebitCapNum += TradeCount;
                                }
                            }
                        }
                        else if (BankCardType != 0)
                        {
                            if (Version == 1)
                            {
                                teamStat.ProfitNonDirectTradeAmt += TradeAmount;
                            }
                            else if (MerHelpFlag == 1)
                            {
                                teamStat.HelpNonDirectTradeAmt += TradeAmount;
                            }
                            else
                            {
                                teamStat.NotHelpNonDirectTradeAmt += TradeAmount;
                            }
                        }
                    }
                }
            }
            else
            {
                //盈利期，费率0.6
                TradeDaySummary2After selfStat2 = db.TradeDaySummary2After.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.VipFlag == VipFlag && m.PayType == PayType && m.SeoTitle == "self");
                if (selfStat2 == null)
                {
                    selfStat2 = db.TradeDaySummary2After.Add(new TradeDaySummary2After()
                    {
                        UserId = UserId,
                        TradeMonth = TradeMonth,
                        TradeDate = TradeDate,
                        BrandId = BrandId,
                        QueryCount = QrPayFlag,
                        VipFlag = VipFlag,
                        PayType = PayType,
                        SeoTitle = "self",
                    }).Entity;
                    db.SaveChanges();
                }
                if (BankCardType == 0)
                {
                    if (Version == 2)
                    {
                        selfStat2.ProfitDebitTradeAmt += TradeAmount;
                        if (CapFlag == 1)
                        {
                            selfStat2.ProfitDebitCapTradeAmt += TradeAmount;
                            selfStat2.ProfitDebitCapNum += TradeCount;
                        }
                    }
                }
                else if (BankCardType != 0)
                {
                    if (Version == 2)
                    {
                        selfStat2.ProfitTradeAmt += TradeAmount;
                    }
                }
                if (!string.IsNullOrEmpty(ParentNav))
                {
                    string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                    foreach (string NavUserIdString in ParentNavList)
                    {
                        int NavUserId = int.Parse(NavUserIdString);
                        TradeDaySummary2After teamStat2 = db.TradeDaySummary2After.FirstOrDefault(m => m.UserId == NavUserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.VipFlag == VipFlag && m.PayType == PayType && m.SeoTitle == "team");
                        if (teamStat2 == null)
                        {
                            teamStat2 = db.TradeDaySummary2After.Add(new TradeDaySummary2After()
                            {
                                UserId = NavUserId,
                                TradeMonth = TradeMonth,
                                TradeDate = TradeDate,
                                BrandId = BrandId,
                                QueryCount = QrPayFlag,
                                VipFlag = VipFlag,
                                PayType = PayType,
                                SeoTitle = "team",
                            }).Entity;
                            db.SaveChanges();
                        }
                        if (BankCardType == 0)
                        {
                            if (Version == 2)
                            {
                                teamStat2.ProfitDebitTradeAmt += TradeAmount;
                                if (CapFlag == 1)
                                {
                                    teamStat2.ProfitDebitCapTradeAmt += TradeAmount;
                                    teamStat2.ProfitDebitCapNum += TradeCount;
                                }
                            }
                        }
                        else if (BankCardType != 0)
                        {
                            if (Version == 2)
                            {
                                teamStat2.ProfitTradeAmt += TradeAmount;
                            }
                        }
                    }
                }
            }
        }

    }
}