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






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

        //补交易额
        public void StartOther()
        {
            Thread th = new Thread(StartOtherV2Do);
            th.IsBackground = true;
            th.Start();
        }
        public void StartOtherV2Do()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("AddTradeRecordByPosIdQueue");
                if(!string.IsNullOrEmpty(content))
                {
                    function.WriteLog("content:" + content, "补录同步未激活交易额");
                    int PosId = int.Parse(function.CheckInt(content));
                    WebCMSEntities db = new WebCMSEntities();
                    PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == PosId && m.ActivationState == 1);
                    if(pos != null)
                    {
                        function.WriteLog("1", "补录同步未激活交易额");
                        var Trades = db.TradeRecord.Select(m => new { m.Id, m.SnNo, m.CreateDate, m.ActStatus, m.MerchantId, m.BrandId, m.TradeAmount }).Where(m => m.Id > 10228440 && m.SnNo == pos.PosSn && m.CreateDate <= pos.ActivationTime && m.ActStatus == 0).ToList();
                        function.WriteLog("未激活记录数:" + Trades.Count, "补录同步未激活交易额");
                        foreach(var Trade in Trades)
                        {
                            //补创客交易
                            StatTradeAmountEverDayV2(Trade.Id);

                            //补商户交易
                            if(Trade.CreateDate.Value < DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00"))
                            {
                                string StatDate = Trade.CreateDate.Value.ToString("yyyyMMdd");
                                string StatMonth = StatDate.Substring(0, 6);
                                PosMerchantTradeSummay stat = db.PosMerchantTradeSummay.FirstOrDefault(m => m.BrandId == Trade.BrandId && m.MerchantId == Trade.MerchantId && m.TradeMonth == StatMonth && m.TradeDate == StatDate);
                                if(stat == null)
                                {
                                    stat = db.PosMerchantTradeSummay.Add(new PosMerchantTradeSummay()
                                    {
                                        BrandId = Trade.BrandId,
                                        MerchantId = Trade.MerchantId,
                                        TradeMonth = StatMonth,
                                        TradeDate = StatDate,
                                    }).Entity;
                                    db.SaveChanges();
                                }
                                stat.TradeAmount += Trade.TradeAmount;
                                db.SaveChanges();
                            }

                            //交易记录设置标记（已执行，激活标记为已激活）
                            CustomerSqlConn.op("update TradeRecord set QueryCount=1,ActStatus=1 where Id=" + Trade.Id, AppConfig.Base.SqlConn);
                        }
                    }
                    db.Dispose();
                    Thread.Sleep(1000);
                }
                else
                {
                    Thread.Sleep(60000);
                }
            }
        }

        public void StatTradeAmountEverDayV2(int Id = 0)
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "实时执行交易额V2日志");
            WebCMSEntities db = new WebCMSEntities();
            using (var tran = db.Database.BeginTransaction())
            {
                try
                {
                    string startId = function.ReadInstance("/TradeRecord/Id.txt");
                    if(string.IsNullOrEmpty(startId))
                    {
                        startId = "867041";
                    }
                    string sql = "select Id from TradeRecord where Id>=" + startId + " and QueryCount=0 and ActStatus=1 order by Id limit 50";
                    if(Id > 0)
                    {
                        sql = "select Id from TradeRecord where Id=" + Id;
                    }
                    DataTable idsDt = OtherMySqlConn.dtable(sql);
                    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 = OtherMySqlConn.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");
                        if (selfDt.Rows.Count > 0)
                        {
                            function.WriteLog("统计人数:" + selfDt.Rows.Count + "\n\n", "实时执行交易额V2日志");
                            foreach (DataRow selfDr in selfDt.Rows)
                            {
                                int UserId = int.Parse(selfDr["UserId"].ToString());
                                string SnNo = selfDr["SnNo"].ToString();
                                if(UserId == 0)
                                {
                                    PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == SnNo);
                                    if(pos != null)
                                    {
                                        UserId = pos.UserId;
                                    }
                                }
                                Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                                string ParentNav = user.ParentNav; //selfDr["ParentNav"].ToString();
                                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);

                                TradeDaySummary selfStat = db.TradeDaySummary.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.TradeDaySummary.Add(new TradeDaySummary()
                                    {
                                        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;
                                    }
                                }
                                ParentNav += "," + UserId + ",";
                                if (!string.IsNullOrEmpty(ParentNav))
                                {
                                    string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                                    foreach (string NavUserIdString in ParentNavList)
                                    {
                                        int NavUserId = int.Parse(NavUserIdString);
                                        TradeDaySummary teamStat = db.TradeDaySummary.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.TradeDaySummary.Add(new TradeDaySummary()
                                            {
                                                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;
                                            }
                                        }
                                    }
                                }

                                Dictionary<string, object> statData = new Dictionary<string, object>();
                                statData.Add("UserId", UserId);
                                statData.Add("BrandId", BrandId);
                                statData.Add("BankCardType", BankCardType);
                                statData.Add("QrPayFlag", QrPayFlag);
                                statData.Add("MerHelpFlag", MerHelpFlag);
                                statData.Add("Version", Version);
                                statData.Add("CapFlag", CapFlag);
                                statData.Add("VipFlag", VipFlag);
                                statData.Add("PayType", PayType);
                                statData.Add("TradeDate", TradeDate);
                                statData.Add("TradeAmount", TradeAmount);
                                statData.Add("TradeCount", TradeCount);
                                RedisDbconn.Instance.AddList("StatTradeAmountQueue", Newtonsoft.Json.JsonConvert.SerializeObject(statData));
                                // RedisDbconn.Instance.AddList("ProfitTradeAmountQueue", Newtonsoft.Json.JsonConvert.SerializeObject(statData));
                            }
                            OtherMySqlConn.op("update TradeRecord set QueryCount=1 where Id in (" + ids.TrimEnd(',') + ")");
                            if(Id == 0)
                            {
                                function.WritePage("/TradeRecord/", "Id.txt", startId);
                            }
                        }
                        db.SaveChanges();
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "统计昨天交易额V2异常");
                }
            }
            db.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "实时执行交易额V2日志");
        }


        // 每天统计头一天的交易额
        public void StartEverDay(string date)
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            // DateTime end = DateTime.Parse("2022-04-19 00:00:00");
            // DateTime check = DateTime.Parse("2022-03-11");
            // while (check <= end)
            // {
            //     Thread th = new Thread(StatTradeAmountEverDay);
            //     th.IsBackground = true;
            //     th.Start(check.ToString("yyyy-MM-dd"));
            //     check = check.AddDays(1);
            // }
            if (DateTime.Now.Day == 2)
            {
                OtherMySqlConn.op("update Users set ThisMonthTrade=0 where ThisMonthTrade>0");
                DataTable list = OtherMySqlConn.dtable("select UserId,sum(NonDirectTradeAmt) from UserTradeDaySummary where TradeMonth='" + DateTime.Now.ToString("yyyyMM") + "' GROUP BY UserId");
                foreach (DataRow dr in list.Rows)
                {
                    string UserId = dr["UserId"].ToString();
                    string ThisMonthTrade = dr[1].ToString();
                    OtherMySqlConn.op("update Users set ThisMonthTrade=" + ThisMonthTrade + " where Id=" + UserId);
                }
            }
            Thread th = new Thread(StatTradeAmountEverDay);
            th.IsBackground = true;
            th.Start(date);
        }
        public void StatTradeAmountEverDay(object sender)
        {
            string date = sender.ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "执行昨天交易额日志");
            WebCMSEntities db = new WebCMSEntities();
            try
            {
                string TradeDate = date.Replace("-", "");
                string TradeMonth = TradeDate.Substring(0, 6);
                string start = date + " 00:00:00";
                string end = DateTime.Parse(date).AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00";
                string startId = "0", endId = "9999999999";
                List<string> uids = new List<string>();
                DataTable startDt = OtherMySqlConn.dtable("select min(Id) from TradeRecord where CreateDate>='" + start + "'");
                if (startDt.Rows.Count > 0)
                {
                    startId = startDt.Rows[0][0].ToString();
                }
                function.WriteLog(startId + "\n\n", "执行昨天交易额日志");
                // DataTable endDt = OtherMySqlConn.dtable("select max(Id) from TradeRecord where CreateDate<'" + end + "'");
                // if (endDt.Rows.Count > 0)
                // {
                //     endId = endDt.Rows[0][0].ToString();
                // }
                DataTable userDt = OtherMySqlConn.dtable("select Id,ParentNav from Users where Id in (select DISTINCT UserId from TradeRecord where Id>=" + startId + " and Id<=" + endId + " and CreateDate>='" + start + "' and CreateDate<'" + end + "')");
                function.WriteLog("交易人数:" + userDt.Rows.Count + "\n\n", "执行昨天交易额日志");
                foreach (DataRow userDr in userDt.Rows)
                {
                    int UserId = int.Parse(userDr["Id"].ToString());
                    string ParentNav = userDr["ParentNav"].ToString();
                    function.WriteLog(UserId + ":" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行昨天交易额日志");
                    DataTable selfdt = OtherMySqlConn.dtable("select BrandId,BankCardType,QrPayFlag,sum(TradeAmount) from TradeRecord where Id>=" + startId + " and Id<=" + endId + " and CreateDate>='" + start + "' and CreateDate<'" + end + "' and UserId=" + UserId + " group by BrandId,BankCardType,QrPayFlag");
                    function.WriteLog(UserId + ":" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行昨天交易额日志");
                    foreach (DataRow selfDr in selfdt.Rows)
                    {
                        int BrandId = int.Parse(selfDr["BrandId"].ToString());
                        int BankCardType = int.Parse(selfDr["BankCardType"].ToString());
                        int QrPayFlag = int.Parse(selfDr["QrPayFlag"].ToString());
                        decimal TradeAmount = decimal.Parse(selfDr[3].ToString());
                        UserTradeDaySummary selfStat = db.UserTradeDaySummary.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.SeoTitle == "self");
                        if (selfStat == null)
                        {
                            selfStat = db.UserTradeDaySummary.Add(new UserTradeDaySummary()
                            {
                                UserId = UserId,
                                TradeMonth = TradeMonth,
                                TradeDate = TradeDate,
                                BrandId = BrandId,
                                QueryCount = QrPayFlag,
                                SeoTitle = "self",
                            }).Entity;
                            db.SaveChanges();
                        }
                        if (BankCardType == 0)
                        {
                            selfStat.DirectDebitTradeAmt += TradeAmount;
                        }
                        else if (BankCardType != 0)
                        {
                            selfStat.DirectTradeAmt += TradeAmount;
                        }
                        db.SaveChanges();
                    }
                    if (!string.IsNullOrEmpty(ParentNav))
                    {
                        ParentNav += "," + UserId + ",";
                        string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                        foreach (string NavUserIdString in ParentNavList)
                        {
                            if (!uids.Contains(NavUserIdString + start))
                            {
                                uids.Add(NavUserIdString + start);
                                int NavUserId = int.Parse(NavUserIdString);
                                function.WriteLog(NavUserId + ":team:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行昨天交易额日志");
                                DataTable teamDt = OtherMySqlConn.dtable("select BrandId,BankCardType,QrPayFlag,sum(TradeAmount) from TradeRecord where Id>=" + startId + " and Id<=" + endId + " and CreateDate>='" + start + "' and CreateDate<'" + end + "' and UserId in (select Id from Users where ParentNav like '%," + NavUserId + ",%' or Id=" + NavUserId + ") group by BrandId,BankCardType,QrPayFlag");
                                function.WriteLog(NavUserId + ":team:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行昨天交易额日志");
                                foreach (DataRow teamDr in teamDt.Rows)
                                {
                                    int BrandId = int.Parse(teamDr["BrandId"].ToString());
                                    int BankCardType = int.Parse(teamDr["BankCardType"].ToString());
                                    int QrPayFlag = int.Parse(teamDr["QrPayFlag"].ToString());
                                    decimal TradeAmount = decimal.Parse(teamDr[3].ToString());
                                    UserTradeDaySummary teamStat = db.UserTradeDaySummary.FirstOrDefault(m => m.UserId == NavUserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.SeoTitle == "team");
                                    if (teamStat == null)
                                    {
                                        teamStat = db.UserTradeDaySummary.Add(new UserTradeDaySummary()
                                        {
                                            UserId = NavUserId,
                                            TradeMonth = TradeMonth,
                                            TradeDate = TradeDate,
                                            BrandId = BrandId,
                                            QueryCount = QrPayFlag,
                                            SeoTitle = "team",
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    if (BankCardType == 0)
                                    {
                                        teamStat.NonDirectDebitTradeAmt += TradeAmount;
                                    }
                                    else if (BankCardType != 0)
                                    {
                                        teamStat.NonDirectTradeAmt += TradeAmount;
                                    }
                                    db.SaveChanges();
                                }
                            }
                        }
                    }
                }
                if (DateTime.Now.Day >= 2)
                {
                    Thread.Sleep(5000);
                    DataTable list = OtherMySqlConn.dtable("select UserId,sum(NonDirectTradeAmt) from UserTradeDaySummary where TradeDate='" + TradeDate + "' GROUP BY UserId");
                    foreach (DataRow dr in list.Rows)
                    {
                        string UserId = dr["UserId"].ToString();
                        string ThisMonthTrade = dr[1].ToString();
                        OtherMySqlConn.op("update Users set ThisMonthTrade=ThisMonthTrade+" + ThisMonthTrade + " where Id=" + UserId);
                    }
                }
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "统计昨天的交易额异常");
            }
            db.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行昨天交易额日志");

            StatMerchantTrade(date);
        }
        public void StatTradeAmountEverDaySum()
        {
            // WebCMSEntities db = new WebCMSEntities();
            // OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            // DataTable dt = OtherMySqlConn.dtable("select UserId,BrandId,QueryCount,TradeDate,TradeMonth,sum(DirectDebitTradeAmt) as DirectDebitTradeAmt,sum(DirectTradeAmt) as DirectTradeAmt,sum(NonDirectDebitTradeAmt) as NonDirectDebitTradeAmt,sum(NonDirectTradeAmt) as NonDirectTradeAmt from UserTradeDaySummary group by UserId,BrandId,QueryCount,TradeDate,TradeMonth order by UserId,BrandId,QueryCount");
            // string html = "<table>";
            // foreach (DataRow dr in dt.Rows)
            // {
            //     html += "<tr>";
            //     string TradeDate = dr["TradeDate"].ToString();
            //     string TradeMonth = dr["TradeMonth"].ToString();
            //     int UserId = int.Parse(dr["UserId"].ToString());
            //     int BrandId = int.Parse(dr["BrandId"].ToString());
            //     int QrPayFlag = int.Parse(dr["QueryCount"].ToString());
            //     decimal DirectDebitTradeAmt = decimal.Parse(dr["DirectDebitTradeAmt"].ToString());
            //     decimal DirectTradeAmt = decimal.Parse(dr["DirectTradeAmt"].ToString());
            //     decimal NonDirectDebitTradeAmt = decimal.Parse(dr["NonDirectDebitTradeAmt"].ToString());
            //     decimal NonDirectTradeAmt = decimal.Parse(dr["NonDirectTradeAmt"].ToString());
            //     decimal CurAmount = 0, CurTotalAmount = 0, CurMonthAmount = 0, CurDayAmount = 0;

            //     CurTotalAmount = RedisDbconn.Instance.Get<decimal>("TotalAmount:" + UserId); //总交易
            //     CurMonthAmount = RedisDbconn.Instance.Get<decimal>("TotalAmount:" + UserId + ":" + TradeDate); //总交易
            //     CurDayAmount = RedisDbconn.Instance.Get<decimal>("TotalAmount:" + UserId + ":" + TradeMonth); //总交易
            //     CurAmount = RedisDbconn.Instance.Get<decimal>("TotalAmount:" + UserId + ":" + BrandId + ":" + TradeDate); //总交易
            //     decimal TotalPosAmount = 0;
            //     decimal TotalCloudPayAmount = 0;
            //     decimal TeamTotalPosAmount = 0;
            //     decimal TeamTotalCloudPayAmount = 0;
            //     if (QrPayFlag == 1)
            //     {
            //         TotalCloudPayAmount = RedisDbconn.Instance.Get<decimal>("TotalCloudPayAmount:" + UserId + ":" + TradeDate); //云闪付小额交易额
            //         TeamTotalCloudPayAmount = RedisDbconn.Instance.Get<decimal>("TeamTotalCloudPayAmount:" + UserId + ":" + TradeDate); //POS机刷卡交易额
            //     }
            //     else
            //     {
            //         TotalPosAmount = RedisDbconn.Instance.Get<decimal>("TotalPosAmount:" + UserId + ":" + TradeDate); //POS机刷卡交易额
            //         TeamTotalPosAmount = RedisDbconn.Instance.Get<decimal>("TeamTotalPosAmount:" + UserId + ":" + TradeDate); //云闪付小额交易额
            //     }
            //     Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
            //     html += "<td>应得</td>";
            //     html += "<td>" + user.MakerCode + "</td>";
            //     html += "<td>" + user.RealName + "</td>";
            //     html += "<td>" + user.Mobile + "</td>";
            //     html += "<td>" + BrandId + "</td>";
            //     html += "<td>" + QrPayFlag + "</td>";
            //     html += "<td>" + DirectDebitTradeAmt + "</td>";
            //     html += "<td>" + DirectTradeAmt + "</td>";
            //     html += "<td>" + NonDirectDebitTradeAmt + "</td>";
            //     html += "<td>" + NonDirectTradeAmt + "</td>";
            //     html += "</tr>";

            //     html += "<tr>";
            //     html += "<td>当前</td>";
            //     html += "<td></td>";
            //     html += "<td></td>";
            //     html += "<td>当天品牌：" + CurAmount + "</td>";
            //     html += "<td>总交易：" + CurTotalAmount + "</td>";
            //     html += "<td>当月：" + CurMonthAmount + "</td>";
            //     html += "<td>当天：" + CurDayAmount + "</td>";
            //     html += "<td>" + TotalPosAmount + "</td>";
            //     html += "<td>" + TotalCloudPayAmount + "</td>";
            //     html += "<td>" + TeamTotalPosAmount + "</td>";
            //     html += "<td>" + TeamTotalCloudPayAmount + "</td>";
            //     html += "</tr>";
            // }
            // html += "</table>";
            // db.Dispose();
            // // OtherMySqlConn.connstr = ;
            // function.WritePage("/html/", "1.html", html);
        }



        //统计商户交易额
        private void StatMerchantTrade(string date)
        {
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "执行商户交易额日志");
            // WebCMSEntities db = new WebCMSEntities();
            try
            {
                string start = date + " 00:00:00";
                string end = DateTime.Parse(date).AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00";
                OtherMySqlConn.op("insert into PosMerchantTradeSummay (MerchantId,BrandId,TradeDate,TradeMonth,TradeAmount,CreateDate)  select *,now() from (select MerchantId,BrandId,DATE_FORMAT(CreateDate,'%Y%m%d') as TradeDate,DATE_FORMAT(CreateDate,'%Y%m') as TradeMonth,sum(TradeAmount) as TradeAmount from TradeRecord where CreateDate>='" + start + "' and CreateDate<'" + end + "' group by MerchantId,BrandId,DATE_FORMAT(CreateDate,'%Y%m%d'),TradeDate,DATE_FORMAT(CreateDate,'%Y%m') order by MerchantId,BrandId,DATE_FORMAT(CreateDate,'%Y%m%d')) tb");
            }
            catch (Exception ex)
            {
                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 StartPosActNum()
        {
            Thread th = new Thread(StartPosActNumFor);
            th.IsBackground = true;
            th.Start();
        }
        public void StartPosActNumFor()
        {
            while (true)
            {
                if(RedisDbconn.Instance.Get<string>("StatServerStatus") == "1" && DateTime.Now.Hour >= 3)
                {
                    StartPosActNumEverTime();
                    StatBusinessService.Instance.StartPosActNumEverTime();
                }
                Thread.Sleep(120000);
            }
        }
        public void StartPosActNumDo(object sender)
        {
            string date = sender.ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "执行创客激活数日志");
            WebCMSEntities db = new WebCMSEntities();
            try
            {
                string TradeDate = date.Replace("-", "");
                string TradeMonth = TradeDate.Substring(0, 6);
                string start = date + " 00:00:00";
                string end = DateTime.Parse(date).AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00";
                List<string> uids = new List<string>();
                DataTable userDt = OtherMySqlConn.dtable("select Id,ParentNav from Users where Id in (select DISTINCT BuyUserId from PosMachinesTwo where QueryCount=0 and ActivationState=1 and ActivationTime>='" + start + "' and ActivationTime<'" + end + "')");
                function.WriteLog("人数:" + userDt.Rows.Count + "\n\n", "执行创客激活数日志");
                foreach (DataRow userDr in userDt.Rows)
                {
                    int UserId = int.Parse(userDr["Id"].ToString());
                    string ParentNav = userDr["ParentNav"].ToString();
                    function.WriteLog(UserId + ":" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行创客激活数日志");
                    DataTable selfdt = OtherMySqlConn.dtable("select BrandId,count(Id) from PosMachinesTwo where QueryCount=0 and ActivationState=1 and ActivationTime>='" + start + "' and ActivationTime<'" + end + "' and BuyUserId=" + UserId + " group by BrandId");
                    function.WriteLog(UserId + ":" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行创客激活数日志");
                    foreach (DataRow selfDr in selfdt.Rows)
                    {
                        int BrandId = int.Parse(selfDr["BrandId"].ToString());
                        int QrPayFlag = 0;
                        int ActCount = int.Parse(selfDr[1].ToString());
                        UserTradeDaySummary selfStat = db.UserTradeDaySummary.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.SeoTitle == "self");
                        if (selfStat == null)
                        {
                            selfStat = db.UserTradeDaySummary.Add(new UserTradeDaySummary()
                            {
                                UserId = UserId,
                                TradeMonth = TradeMonth,
                                TradeDate = TradeDate,
                                BrandId = BrandId,
                                QueryCount = QrPayFlag,
                                SeoTitle = "self",
                            }).Entity;
                            db.SaveChanges();
                        }
                        selfStat.DirectDebitCapNum += ActCount;
                        db.SaveChanges();
                    }
                    if (!string.IsNullOrEmpty(ParentNav))
                    {
                        ParentNav += "," + UserId + ",";
                        string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                        foreach (string NavUserIdString in ParentNavList)
                        {
                            if (!uids.Contains(NavUserIdString + start))
                            {
                                uids.Add(NavUserIdString + start);
                                int NavUserId = int.Parse(NavUserIdString);
                                function.WriteLog(NavUserId + ":team:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行创客激活数日志");
                                DataTable teamDt = OtherMySqlConn.dtable("select BrandId,count(Id) from PosMachinesTwo where QueryCount=0 and ActivationState=1 and ActivationTime>='" + start + "' and ActivationTime<'" + end + "' and BuyUserId in (select Id from Users where ParentNav like '%," + NavUserId + ",%' or Id=" + NavUserId + ") group by BrandId");
                                function.WriteLog(NavUserId + ":team:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行创客激活数日志");
                                foreach (DataRow teamDr in teamDt.Rows)
                                {
                                    int BrandId = int.Parse(teamDr["BrandId"].ToString());
                                    int QrPayFlag = 0;
                                    int ActCount = int.Parse(teamDr[1].ToString());
                                    UserTradeDaySummary teamStat = db.UserTradeDaySummary.FirstOrDefault(m => m.UserId == NavUserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.SeoTitle == "team");
                                    if (teamStat == null)
                                    {
                                        teamStat = db.UserTradeDaySummary.Add(new UserTradeDaySummary()
                                        {
                                            UserId = NavUserId,
                                            TradeMonth = TradeMonth,
                                            TradeDate = TradeDate,
                                            BrandId = BrandId,
                                            QueryCount = QrPayFlag,
                                            SeoTitle = "team",
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    teamStat.NonDirectDebitCapNum += ActCount;
                                    db.SaveChanges();
                                }
                            }
                        }
                    }
                }
                OtherMySqlConn.op("update PosMachinesTwo set QueryCount=1 where QueryCount=0 and ActivationState=1 and ActivationTime>='" + start + "' and ActivationTime<'" + end + "'");
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "执行创客激活数异常");
            }
            db.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行创客激活数日志");
            Thread.Sleep(60000);
        }
        public void StartPosActNumEverTime()
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "实时执行创客激活数日志");
            WebCMSEntities db = new WebCMSEntities();
            try
            {
                DataTable idsDt = OtherMySqlConn.dtable("select Id from PosMachinesTwo where QueryCount=0 and ActivationState=1 and ActivationTime is not null and ActivationTime>='2022-06-01 00:00:00' and BuyUserId>0 limit 50");
                if(idsDt.Rows.Count > 0)
                {
                    string ids = "";
                    foreach (DataRow idsDr in idsDt.Rows)
                    {
                        ids += idsDr["Id"].ToString() + ",";
                    }
                    DataTable userDt = OtherMySqlConn.dtable("select BuyUserId,StoreId,BrandId,DATE_FORMAT(ActivationTime, '%Y%m%d'),count(Id) from PosMachinesTwo where Id in (" + ids.TrimEnd(',') + ") group by BuyUserId,StoreId,BrandId,DATE_FORMAT(ActivationTime, '%Y%m%d')");
                    if (userDt.Rows.Count > 0)
                    {
                        function.WriteLog("人数:" + userDt.Rows.Count + "\n\n", "实时执行创客激活数日志");
                        foreach (DataRow userDr in userDt.Rows)
                        {
                            int UserId = int.Parse(userDr["BuyUserId"].ToString());
                            int StoreId = int.Parse(userDr["StoreId"].ToString());
                            int BrandId = int.Parse(userDr["BrandId"].ToString());
                            string TradeDate = userDr[3].ToString();
                            int ActCount = int.Parse(function.CheckInt(userDr[4].ToString()));
                            int QrPayFlag = 0;
                            string TradeMonth = TradeDate.Substring(0, 6);
                            string date = TradeDate.Substring(0, 4) + "-" + TradeDate.Substring(4, 2) + "-" + TradeDate.Substring(6, 2);
                            string start = date + " 00:00:00";
                            string end = DateTime.Parse(date).AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00";
                            Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                            string ParentNav = user.ParentNav;
                            UserTradeMonthSummary selfStat = db.UserTradeMonthSummary.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.SeoKeyword == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.SeoTitle == "self");
                            if (selfStat == null)
                            {
                                selfStat = db.UserTradeMonthSummary.Add(new UserTradeMonthSummary()
                                {
                                    UserId = UserId,
                                    TradeMonth = TradeMonth,
                                    SeoKeyword = TradeDate,
                                    BrandId = BrandId,
                                    QueryCount = QrPayFlag,
                                    SeoTitle = "self",
                                }).Entity;
                                db.SaveChanges();
                            }
                            selfStat.ActiveBuddyMerStatus += ActCount;
                            ParentNav += "," + UserId + ",";
                            if (!string.IsNullOrEmpty(ParentNav))
                            {
                                string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                                foreach (string NavUserIdString in ParentNavList)
                                {
                                    int NavUserId = int.Parse(NavUserIdString);
                                    UserTradeMonthSummary teamStat = db.UserTradeMonthSummary.FirstOrDefault(m => m.UserId == NavUserId && m.TradeMonth == TradeMonth && m.SeoKeyword == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.SeoTitle == "team");
                                    if (teamStat == null)
                                    {
                                        teamStat = db.UserTradeMonthSummary.Add(new UserTradeMonthSummary()
                                        {
                                            UserId = NavUserId,
                                            TradeMonth = TradeMonth,
                                            SeoKeyword = TradeDate,
                                            BrandId = BrandId,
                                            QueryCount = QrPayFlag,
                                            SeoTitle = "team",
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    teamStat.ActiveBuddyMerStatus += ActCount;
                                }
                            }

                            //统计分仓激活数
                            StoreSnActivateSummary storeStat = db.StoreSnActivateSummary.FirstOrDefault(m => m.StoreId == StoreId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId);
                            if (storeStat == null)
                            {
                                storeStat = db.StoreSnActivateSummary.Add(new StoreSnActivateSummary()
                                {
                                    StoreId = StoreId,
                                    TradeMonth = TradeMonth,
                                    TradeDate = TradeDate,
                                    BrandId = BrandId,
                                }).Entity;
                                db.SaveChanges();
                            }
                            storeStat.ActivateNum += ActCount;
                        }
                        db.SaveChanges();
                        OtherMySqlConn.op("update PosMachinesTwo set QueryCount=1 where Id in (" + ids.TrimEnd(',') + ")");
                    }
                }
            }
            catch (Exception ex)
            {
                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 StartNewUserNum()
        {
            Thread th = new Thread(StartNewUserNumFor);
            th.IsBackground = true;
            th.Start();
        }
        public void StartNewUserNumFor()
        {
            while (true)
            {
                if(RedisDbconn.Instance.Get<string>("StatServerStatus") == "1" && DateTime.Now.Hour >= 3)
                {
                    StartNewUserNumEverTime();
                }
                Thread.Sleep(120000);
            }
        }
        public void StartNewUserNumDo(object sender)
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            string date = sender.ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "执行新增创客数日志");
            WebCMSEntities db = new WebCMSEntities();
            try
            {
                string StatDate = date.Replace("-", "");
                string StatMonth = StatDate.Substring(0, 6);
                string start = date + " 00:00:00";
                string end = DateTime.Parse(date).AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00";
                List<string> uids = new List<string>();
                DataTable userDt = OtherMySqlConn.dtable("select Id,ParentNav from Users where QueryCount=0 and AuthFlag=1 and AuthDate>='" + start + "' and AuthDate<'" + end + "'");
                function.WriteLog("人数:" + userDt.Rows.Count + "\n\n", "执行新增创客数日志");
                foreach (DataRow userDr in userDt.Rows)
                {
                    int UserId = int.Parse(userDr["Id"].ToString());
                    string ParentNav = userDr["ParentNav"].ToString();
                    function.WriteLog(UserId + ":" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行新增创客数日志");
                    DataTable selfdt = OtherMySqlConn.dtable("select count(Id) from Users where QueryCount=0 and AuthFlag=1 and AuthDate>='" + start + "' and AuthDate<'" + end + "' and ParentUserId=" + UserId + "");
                    function.WriteLog(UserId + ":" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行新增创客数日志");
                    foreach (DataRow selfDr in selfdt.Rows)
                    {
                        int AddCount = int.Parse(selfDr[0].ToString());
                        PullnewSummary selfStat = db.PullnewSummary.FirstOrDefault(m => m.UserId == UserId && m.StatMonth == StatMonth && m.StatDate == StatDate && m.SeoTitle == "self");
                        if (selfStat == null)
                        {
                            selfStat = db.PullnewSummary.Add(new PullnewSummary()
                            {
                                UserId = UserId,
                                StatMonth = StatMonth,
                                StatDate = StatDate,
                                SeoTitle = "self",
                            }).Entity;
                            db.SaveChanges();
                        }
                        selfStat.RecUserAuthNum += AddCount;
                        db.SaveChanges();
                    }
                    if (!string.IsNullOrEmpty(ParentNav))
                    {
                        ParentNav += "," + UserId + ",";
                        string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                        foreach (string NavUserIdString in ParentNavList)
                        {
                            if (!uids.Contains(NavUserIdString + start))
                            {
                                uids.Add(NavUserIdString + start);
                                int NavUserId = int.Parse(NavUserIdString);
                                function.WriteLog(NavUserId + ":team:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行新增创客数日志");
                                DataTable teamDt = OtherMySqlConn.dtable("select count(Id) from Users where QueryCount=0 and AuthFlag=1 and AuthDate>='" + start + "' and AuthDate<'" + end + "' and ParentNav like '%," + NavUserId + ",%'");
                                function.WriteLog(NavUserId + ":team:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行新增创客数日志");
                                foreach (DataRow teamDr in teamDt.Rows)
                                {
                                    int AddCount = int.Parse(teamDr[0].ToString());
                                    PullnewSummary teamStat = db.PullnewSummary.FirstOrDefault(m => m.UserId == NavUserId && m.StatMonth == StatMonth && m.StatDate == StatDate && m.SeoTitle == "team");
                                    if (teamStat == null)
                                    {
                                        teamStat = db.PullnewSummary.Add(new PullnewSummary()
                                        {
                                            UserId = NavUserId,
                                            StatMonth = StatMonth,
                                            StatDate = StatDate,
                                            SeoTitle = "team",
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    teamStat.RecUserAuthNum += AddCount;
                                    db.SaveChanges();
                                }
                            }
                        }
                    }
                }
                OtherMySqlConn.op("update Users set QueryCount=1 where QueryCount=0 and AuthFlag=1 and AuthDate>='" + start + "' and AuthDate<'" + end + "'");
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "执行新增创客数异常");
            }
            db.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行新增创客数日志");
            Thread.Sleep(60000);
        }
        public void StartNewUserNumEverTime()
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "实时执行新增创客数日志");
            WebCMSEntities db = new WebCMSEntities();
            try
            {
                DataTable idsDt = OtherMySqlConn.dtable("select Id from Users where QueryCount=0 and AuthFlag=1 and AuthDate is not null limit 50");
                if(idsDt.Rows.Count > 0)
                {
                    string ids = "";
                    foreach (DataRow idsDr in idsDt.Rows)
                    {
                        ids += idsDr["Id"].ToString() + ",";
                    }
                    DataTable userDt = OtherMySqlConn.dtable("select ParentUserId,DATE_FORMAT(AuthDate, '%Y%m%d'),count(Id) from Users where Id in (" + ids.TrimEnd(',') + ") group by ParentUserId,DATE_FORMAT(AuthDate, '%Y%m%d')");
                    if(userDt.Rows.Count > 0)
                    {
                        function.WriteLog("人数:" + userDt.Rows.Count + "\n\n", "实时执行新增创客数日志");
                        foreach (DataRow userDr in userDt.Rows)
                        {
                            string StatDate = userDr[1].ToString();
                            int UserId = int.Parse(userDr["ParentUserId"].ToString());
                            string StatMonth = StatDate.Substring(0, 6);
                            string date = StatDate.Substring(0, 4) + "-" + StatDate.Substring(4, 2) + "-" + StatDate.Substring(6, 2);
                            string start = date + " 00:00:00";
                            string end = DateTime.Parse(date).AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00";
                            int AddCount = int.Parse(userDr[2].ToString());
                            Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                            string ParentNav = user.ParentNav;
                            PullnewSummary selfStat = db.PullnewSummary.FirstOrDefault(m => m.UserId == UserId && m.StatMonth == StatMonth && m.StatDate == StatDate && m.SeoTitle == "self");
                            if (selfStat == null)
                            {
                                selfStat = db.PullnewSummary.Add(new PullnewSummary()
                                {
                                    UserId = UserId,
                                    StatMonth = StatMonth,
                                    StatDate = StatDate,
                                    SeoTitle = "self",
                                }).Entity;
                                db.SaveChanges();
                            }
                            selfStat.RecUserAuthNum += AddCount;
                            ParentNav += "," + UserId + ",";
                            if (!string.IsNullOrEmpty(ParentNav))
                            {
                                string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                                foreach (string NavUserIdString in ParentNavList)
                                {
                                    int NavUserId = int.Parse(NavUserIdString);                            
                                    PullnewSummary teamStat = db.PullnewSummary.FirstOrDefault(m => m.UserId == NavUserId && m.StatMonth == StatMonth && m.StatDate == StatDate && m.SeoTitle == "team");
                                    if (teamStat == null)
                                    {
                                        teamStat = db.PullnewSummary.Add(new PullnewSummary()
                                        {
                                            UserId = NavUserId,
                                            StatMonth = StatMonth,
                                            StatDate = StatDate,
                                            SeoTitle = "team",
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    teamStat.RecUserAuthNum += AddCount;
                                }
                            }
                        }
                        db.SaveChanges();
                        OtherMySqlConn.op("update Users set QueryCount=1 where Id in (" + ids.TrimEnd(',') + ")");
                    }
                }
            }
            catch (Exception ex)
            {
                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 StatProfit()
        {
            Thread th = new Thread(StatProfitDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StatProfitDo()
        {
            while (true)
            {
                if(RedisDbconn.Instance.Get<string>("StatServerStatus") == "1" && DateTime.Now.Hour >= 3)
                {
                    StatProfitEverDayEverTime();
                }
                Thread.Sleep(120000);
            }
        }
        public void StatProfitEverDay(object sender)
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            string date = sender.ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "执行昨天收益日志");
            WebCMSEntities db = new WebCMSEntities();
            try
            {
                string TradeDate = date.Replace("-", "");
                string TradeMonth = TradeDate.Substring(0, 6);
                string start = date + " 00:00:00";
                string end = DateTime.Parse(date).AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00";
                string startId = "0";
                List<string> uids = new List<string>();
                DataTable startDt = OtherMySqlConn.dtable("select min(Id) from UserAccountRecord where CreateDate>='" + start + "'");
                if (startDt.Rows.Count > 0)
                {
                    startId = startDt.Rows[0][0].ToString();
                }
                function.WriteLog(startId + "\n\n", "执行昨天收益日志");
                DataTable userDt = OtherMySqlConn.dtable("select Id,ParentNav from Users where Id in (select DISTINCT UserId from UserAccountRecord where Id>=" + startId + " and CreateDate>='" + start + "' and CreateDate<'" + end + "')");
                function.WriteLog("交易人数:" + userDt.Rows.Count + "\n\n", "执行昨天收益日志");
                foreach (DataRow userDr in userDt.Rows)
                {
                    int UserId = int.Parse(userDr["Id"].ToString());
                    string ParentNav = userDr["ParentNav"].ToString();
                    function.WriteLog(UserId + ":" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行昨天收益日志");
                    DataTable selfdt = OtherMySqlConn.dtable("select ChangeType,ProductType,sum(ChangeAmount) from UserAccountRecord where Id>=" + startId + " and CreateDate>='" + start + "' and CreateDate<'" + end + "' and UserId=" + UserId + " group by ChangeType,ProductType");
                    function.WriteLog(UserId + ":" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行昨天收益日志");
                    foreach (DataRow selfDr in selfdt.Rows)
                    {
                        int ChangeType = int.Parse(selfDr["ChangeType"].ToString());
                        int ProductType = int.Parse(selfDr["ProductType"].ToString());
                        decimal ProfitAmount = decimal.Parse(selfDr[2].ToString());
                        UserRebateDetail selfStat = db.UserRebateDetail.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.RebateType == ChangeType && m.ProductType == ProductType && m.SeoTitle == "self");
                        if (selfStat == null)
                        {
                            selfStat = db.UserRebateDetail.Add(new UserRebateDetail()
                            {
                                UserId = UserId,
                                TradeMonth = TradeMonth,
                                TradeDate = TradeDate,
                                RebateType = ChangeType,
                                ProductType = ProductType,
                                SeoTitle = "self",
                            }).Entity;
                            db.SaveChanges();
                        }
                        selfStat.CreditRewardAmount += ProfitAmount;
                        db.SaveChanges();
                    }
                    if (!string.IsNullOrEmpty(ParentNav))
                    {
                        ParentNav += "," + UserId + ",";
                        string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                        foreach (string NavUserIdString in ParentNavList)
                        {
                            if (!uids.Contains(NavUserIdString + start))
                            {
                                uids.Add(NavUserIdString + start);
                                int NavUserId = int.Parse(NavUserIdString);
                                function.WriteLog(NavUserId + ":team:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行昨天收益日志");
                                DataTable teamDt = OtherMySqlConn.dtable("select ChangeType,ProductType,sum(ChangeAmount) from UserAccountRecord where Id>=" + startId + " and CreateDate>='" + start + "' and CreateDate<'" + end + "' and UserId in (select Id from Users where ParentNav like '%," + NavUserId + ",%' or Id=" + NavUserId + ") group by ChangeType,ProductType");
                                function.WriteLog(NavUserId + ":team:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行昨天收益日志");
                                foreach (DataRow teamDr in teamDt.Rows)
                                {
                                    int ChangeType = int.Parse(teamDr["ChangeType"].ToString());
                                    int ProductType = int.Parse(teamDr["ProductType"].ToString());
                                    decimal ProfitAmount = decimal.Parse(teamDr[2].ToString());
                                    UserRebateDetail teamStat = db.UserRebateDetail.FirstOrDefault(m => m.UserId == NavUserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.RebateType == ChangeType && m.ProductType == ProductType && m.SeoTitle == "team");
                                    if (teamStat == null)
                                    {
                                        teamStat = db.UserRebateDetail.Add(new UserRebateDetail()
                                        {
                                            UserId = NavUserId,
                                            TradeMonth = TradeMonth,
                                            TradeDate = TradeDate,
                                            RebateType = ChangeType,
                                            ProductType = ProductType,
                                            SeoTitle = "team",
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    teamStat.CreditRewardAmount += ProfitAmount;
                                    db.SaveChanges();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                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 StatProfitEverDayEverTime()
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "实时统计收益日志");
            WebCMSEntities db = new WebCMSEntities();
            try
            {
                string startId = function.ReadInstance("/UserAccountRecord/Id.txt");
                if(string.IsNullOrEmpty(startId))
                {
                    startId = "160653";
                }
                DataTable idsDt = OtherMySqlConn.dtable("select Id from UserAccountRecord where Id>=" + startId + " and QueryCount=0 order by Id limit 50");
                if(idsDt.Rows.Count > 0)
                {
                    string ids = "";
                    foreach (DataRow idsDr in idsDt.Rows)
                    {
                        ids += idsDr["Id"].ToString() + ",";
                        startId = idsDr["Id"].ToString();
                    }
                    DataTable userDt = OtherMySqlConn.dtable("select UserId,ChangeType,ProductType,DATE_FORMAT(CreateDate, '%Y%m%d'),sum(ChangeAmount)  from UserAccountRecord where Id in (" + ids.TrimEnd(',') + ") group by UserId,ChangeType,ProductType,DATE_FORMAT(CreateDate, '%Y%m%d')");
                    if (userDt.Rows.Count > 0)
                    {
                        function.WriteLog("收益人数:" + userDt.Rows.Count + "\n\n", "实时统计收益日志");
                        foreach (DataRow userDr in userDt.Rows)
                        {
                            int UserId = int.Parse(userDr["UserId"].ToString());
                            int ChangeType = int.Parse(userDr["ChangeType"].ToString());
                            int ProductType = int.Parse(userDr["ProductType"].ToString());
                            string TradeDate = userDr[3].ToString();
                            decimal ProfitAmount = decimal.Parse(userDr[4].ToString());
                            string TradeMonth = TradeDate.Substring(0, 6);
                            string date = TradeDate.Substring(0, 4) + "-" + TradeDate.Substring(4, 2) + "-" + TradeDate.Substring(6, 2);
                            string start = date + " 00:00:00";
                            string end = DateTime.Parse(date).AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00";
                            Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                            string ParentNav = user.ParentNav;
                            UserRebateDetail selfStat = db.UserRebateDetail.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.RebateType == ChangeType && m.ProductType == ProductType && m.SeoTitle == "self");
                            if (selfStat == null)
                            {
                                selfStat = db.UserRebateDetail.Add(new UserRebateDetail()
                                {
                                    UserId = UserId,
                                    TradeMonth = TradeMonth,
                                    TradeDate = TradeDate,
                                    RebateType = ChangeType,
                                    ProductType = ProductType,
                                    SeoTitle = "self",
                                }).Entity;
                                db.SaveChanges();
                            }
                            selfStat.CreditRewardAmount += ProfitAmount;
                            ParentNav += "," + UserId + ",";
                            if (!string.IsNullOrEmpty(ParentNav))
                            {
                                string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                                foreach (string NavUserIdString in ParentNavList)
                                {
                                    int NavUserId = int.Parse(NavUserIdString);
                                    UserRebateDetail teamStat = db.UserRebateDetail.FirstOrDefault(m => m.UserId == NavUserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.RebateType == ChangeType && m.ProductType == ProductType && m.SeoTitle == "team");
                                    if (teamStat == null)
                                    {
                                        teamStat = db.UserRebateDetail.Add(new UserRebateDetail()
                                        {
                                            UserId = NavUserId,
                                            TradeMonth = TradeMonth,
                                            TradeDate = TradeDate,
                                            RebateType = ChangeType,
                                            ProductType = ProductType,
                                            SeoTitle = "team",
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    teamStat.CreditRewardAmount += ProfitAmount;
                                }
                            }
                        }
                        db.SaveChanges();
                        OtherMySqlConn.op("update UserAccountRecord set QueryCount=1 where Id in (" + ids.TrimEnd(',') + ")");
                        function.WritePage("/UserAccountRecord/", "Id.txt", startId);
                    }
                }
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "实时统计收益异常");
            }
            db.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "实时统计收益日志");
        }






        #region 判断品牌互斥条件，根据身份证号

        public bool CheckRepeatByBrand(WebCMSEntities db, int MerchantId)
        {
            int check = db.PosMachinesTwo.Count(m => m.Status > -1 && m.BindMerchantId == MerchantId);

            return false;
        }

        #endregion

    }
}