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

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

        public void Start()
        {
            Thread th = new Thread(StartDo);
            th.IsBackground = true;
            th.Start();
        }

        public void StartDo()
        {
            while(true)
            {
                try
                {
                    if(DateTime.Now.Hour > 0 && DateTime.Now.Hour < 9)
                    {
                        string doDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                        string flag = function.ReadInstance("/Stat/" + doDate + ".txt");
                        if (string.IsNullOrEmpty(flag))
                        {
                            function.WritePage("/Stat/", doDate + ".txt", DateTime.Now.ToString("HH:mm:ss"));
                            StartEverDay();
                            StatMerchantTrade(doDate);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Utils.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "每天同步创客上级关联异常");
                }
                Thread.Sleep(1800000);
            }
        }


        public void StartActiveReward()
        {
            Thread th = new Thread(ActiveReward);
            th.IsBackground = true;
            th.Start();
        }

        public void ActiveReward()
        {
            while(true)
            {
                try
                {
                    Utils.WriteLog(DateTime.Now.ToString() + ":start", "实时处理激活奖励");
                    dosomething3();
                    Utils.WriteLog(DateTime.Now.ToString() + ":end\n\n", "实时处理激活奖励");
                }
                catch (Exception ex)
                {
                    Utils.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "实时处理激活奖励异常");
                }
                Thread.Sleep(30000);
            }
        }

        public void StartActiveReward1()
        {
            Thread th = new Thread(ActiveReward1);
            th.IsBackground = true;
            th.Start();
        }

        public void ActiveReward1()
        {
            while(true)
            {
                try
                {
                    Utils.WriteLog(DateTime.Now.ToString() + ":start", "实时处理0押激活奖励");
                    activePrizeWithoutDeposit();
                    Utils.WriteLog(DateTime.Now.ToString() + ":end\n\n", "实时处理0押激活奖励");
                }
                catch (Exception ex)
                {
                    Utils.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "实时处理0押激活奖励异常");
                }
                Thread.Sleep(30000);
            }
        }

        public void StartActiveReward2()
        {
            Thread th = new Thread(ActiveReward2);
            th.IsBackground = true;
            th.Start();
        }

        public void ActiveReward2()
        {
            while(true)
            {
                try
                {
                    Utils.WriteLog(DateTime.Now.ToString() + ":start", "实时处理盒易付0押激活奖励");
                    activePrizeWithoutDeposit12();
                    Utils.WriteLog(DateTime.Now.ToString() + ":end\n\n", "实时处理盒易付0押激活奖励");
                }
                catch (Exception ex)
                {
                    Utils.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "实时处理盒易付0押激活奖励异常");
                }
                Thread.Sleep(30000);
            }
        }

        public void StartActiveReward15()
        {
            Thread th = new Thread(ActiveReward15);
            th.IsBackground = true;
            th.Start();
        }

        public void ActiveReward15()
        {
            while(true)
            {
                try
                {
                    Utils.WriteLog(DateTime.Now.ToString() + ":start", "实时处理来客吧0押激活奖励");
                    activePrizeWithoutDeposit15();
                    Utils.WriteLog(DateTime.Now.ToString() + ":end\n\n", "实时处理来客吧0押激活奖励");
                }
                catch (Exception ex)
                {
                    Utils.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "实时处理来客吧0押激活奖励异常");
                }
                Thread.Sleep(30000);
            }
        }



        //广电卡激活奖励
        public void StartSimActive()
        {
            Thread th = new Thread(StartSimActiveListen);
            th.IsBackground = true;
            th.Start();
        }

        public void StartSimActiveListen()
        {
            while(true)
            {
                try
                {
                    Utils.WriteLog(DateTime.Now.ToString() + ":start", "实时处理广电卡激活奖励");
                    StartSimActiveDo();
                    Utils.WriteLog(DateTime.Now.ToString() + ":end\n\n", "实时处理广电卡激活奖励");
                }
                catch (Exception ex)
                {
                    Utils.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "实时处理广电卡激活奖励异常");
                }
                Thread.Sleep(29000);
            }
        }

        public void StartSimActiveDo(int posid = 0)
        {
            WebCMSEntities db = new WebCMSEntities();
            DateTime yesterday = DateTime.Now.AddDays(-30);
            DateTime today = DateTime.Now.AddMinutes(-5);
            IQueryable<PosMachinesTwo> posList = db.PosMachinesTwo.Where(m => m.ActivationState == 1 && m.BrandId == 14 && m.CardType > 0 && m.Detail != "1");
            if (posid > 0)
            {
                posList = posList.Where(m => m.Id == posid);
            }
            else
            {
                posList = posList.Where(m => m.ActivationTime >= yesterday && m.ActivationTime < today);
            }
            foreach (PosMachinesTwo pos in posList.ToList())
            {
                PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId);
                if (merchant != null)
                {
                    string ParentNav = "";
                    Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId);
                    if (user != null)
                    {
                        int GetUserId = user.Id;
                        ParentNav = user.ParentNav;
                        int TopUserId = 0;
                        if (!string.IsNullOrEmpty(ParentNav))
                        {
                            TopUserId = int.Parse(ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                        }
                        decimal Amount = 19 * 1.5M;
                        doActiveReward(db, merchant, pos, GetUserId, ParentNav, TopUserId, Amount);
                        PosMachinesTwo item = db.PosMachinesTwo.FirstOrDefault(m => m.Id == pos.Id);
                        if(item != null)
                        {
                            item.Detail = "1";
                            db.SaveChanges();
                        }
                    }
                }
            }
            db.Dispose();
        }








        // 1. 前一天的绑定记录和创客信息匹配，设置商户型创客
        public void dosomething1(string date)
        {
            // TODO: 每天扫描非商户型创客的持有机具数量
            SpModels.WebCMSEntities spdb = new SpModels.WebCMSEntities();
            WebCMSEntities db = new WebCMSEntities();
            DateTime yesterday = DateTime.Parse(date + " 00:00:00");
            DateTime today = DateTime.Parse(DateTime.Parse(date).AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00");
            List<SpModels.BindRecord> binds = spdb.BindRecord.Where(m => m.CreateTime >= yesterday && m.CreateTime < today).ToList();
            foreach (SpModels.BindRecord bind in binds)
            {
                string Mobile = bind.MerNewSnNo;
                string MerNo = bind.MerNo;
                string BeforeNum = "";
                string AfterNum = "";
                if (Mobile.Contains("****") && Mobile.Length == 11)
                {
                    BeforeNum = Mobile.Substring(0, 3);
                    AfterNum = Mobile.Substring(7);
                }
                string Name = bind.MerName;
                if (bind.ProductType == "2")
                {
                    if (Name.Contains("-"))
                    {
                        Name = Name.Split('-')[1];
                    }
                    else if (Name.Contains("_"))
                    {
                        Name = Name.Split('_')[1];
                    }
                }
                else if (bind.ProductType == "4")
                {
                    Name = bind.SeoTitle;
                }
                PxcModels.Users user = db.Users.FirstOrDefault(m => m.Mobile.StartsWith(BeforeNum) && m.Mobile.EndsWith(AfterNum) && m.RealName == Name && m.AuthFlag == 1 && m.MerchantType == 0);
                if (user != null)
                {
                    bool checkPos = db.PosMachinesTwo.Any(m => m.UserId == user.Id);
                    if (!checkPos)
                    {
                        PxcModels.MachineForSnNo forSnNo = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == bind.MerSnNo) ?? new PxcModels.MachineForSnNo();
                        PxcModels.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == forSnNo.SnId && m.UserId != user.Id);
                        if (pos != null)
                        {
                            pos.UserId = user.Id;
                            user.MerchantType = 1;
                            PxcModels.PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.KqMerNo == MerNo) ?? new PxcModels.PosMerchantInfo();
                            merchant.UserId = user.Id;
                            merchant.MerUserType = 1;
                            pos.SeoTitle = user.Id.ToString(); // 记录商户型创客的Id
                            db.SaveChanges();
                        }
                    }
                }
            }
            spdb.Dispose();
            db.Dispose();
        }

        // 1. 前一天的商户型创客，判断名下是否3台激活机器，是则变为非商户型创客
        public void dosomething11(string date)
        {
            WebCMSEntities db = new WebCMSEntities();
            DateTime yesterday = DateTime.Parse(date + " 00:00:00");
            DateTime today = DateTime.Parse(DateTime.Parse(date).AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00");
            var users = db.Users.Select(m => new { m.Id, m.MerchantType }).Where(m => m.MerchantType == 1).ToList();
            foreach (var user in users)
            {
                int machineCount = db.PosMachinesTwo.Count(m => m.UserId == user.Id && m.PosSnType == 0);
                int couponCount = db.PosCoupons.Count(m => m.UserId == user.Id && m.IsUse == 0); //判断是否拥有3张券
                if (machineCount + couponCount >= 3)
                {
                    Users edit = db.Users.FirstOrDefault(m => m.Id == user.Id);
                    if (edit != null)
                    {
                        edit.MerchantType = 0;
                        db.SaveChanges();
                    }
                }
            }
            db.Dispose();
        }


        public void testStatTrade(string date)
        {
            string yesterday = date + " 00:00:00";
            string today = DateTime.Parse(date).AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00";
            string TradeMonth = DateTime.Parse(date).ToString("yyyyMM");
            string TradeDate = DateTime.Parse(date).ToString("yyyyMMdd");
            DataTable dt = dbconn.dtable("select UserId,BrandId,MerchantId,BankCardType,QrPayFlag,sum(TradeAmount) from TradeRecord where CreateDate>='" + yesterday + "' and CreateDate<'" + today + "' group by UserId,BrandId,MerchantId,BankCardType,QrPayFlag");
            foreach (DataRow dr in dt.Rows)
            {
                int UserId = int.Parse(dr["UserId"].ToString()); //创客ID
                int BrandId = int.Parse(dr["BrandId"].ToString()); //品牌
                int MerchantId = int.Parse(dr["MerchantId"].ToString()); //商户Id
                int BankCardType = int.Parse(dr["BankCardType"].ToString()); //卡类型
                int QrPayFlag = int.Parse(dr["QrPayFlag"].ToString()); //云闪付
                decimal TradeAmount = decimal.Parse(dr[5].ToString()); //当日交易额
                string content = "{";
                content += "\"DateString\":\"" + date + "\",";
                content += "\"UserId\":\"" + UserId + "\",";
                content += "\"BrandId\":\"" + BrandId + "\",";
                content += "\"MerchantId\":\"" + MerchantId + "\",";
                content += "\"BankCardType\":\"" + BankCardType + "\",";
                content += "\"QrPayFlag\":\"" + QrPayFlag + "\",";
                content += "\"TradeAmount\":\"" + TradeAmount + "\"";
                content += "}";
                RedisDbconn.Instance.AddList("TradeStatQueueTest", content);
            }
        }

        // 3. 前一天的激活记录，根据创客类型，如果是商户型创客，则激活奖励的起始人从此人上级计算。如果不是，则从此人开始计算
        public void dosomething3(int posid = 0)
        {
            List<int> BrandIds = new List<int>();
            BrandIds.Add(14);
            BrandIds.Add(18);
            BrandIds.Add(19);
            BrandIds.Add(20);
            BrandIds.Add(21);
            BrandIds.Add(29);
            BrandIds.Add(23);
            BrandIds.Add(24);
            BrandIds.Add(25);
            BrandIds.Add(26);
            BrandIds.Add(32);
            WebCMSEntities db = new WebCMSEntities();
            DateTime yesterday = DateTime.Now.AddDays(-1);
            DateTime today = DateTime.Now.AddMinutes(-10);
            IQueryable<PosMachinesTwo> posList = db.PosMachinesTwo.Where(m => m.ActivationState == 1 && !string.IsNullOrEmpty(m.SeoKeyword) && m.SeoKeyword != "" && m.SeoKeyword != "0" && m.Detail != "1" && !BrandIds.Contains(m.BrandId));
            if (posid > 0)
            {
                posList = posList.Where(m => m.Id == posid);
            }
            else
            {
                posList = posList.Where(m => m.ActivationTime >= yesterday && m.ActivationTime < today);
            }
            foreach (PosMachinesTwo pos in posList.ToList())
            {
                PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId);
                if (merchant != null && pos.ActivationTime.Value <= pos.BindingTime.Value.AddDays(30))
                {
                    Utils.WriteLog("机具号:" + pos.PosSn + ";奖励标记:" + pos.Detail + ";", "实时处理激活奖励");
                    string ParentNav = "";
                    Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId);
                    if (user != null)
                    {
                        int GetUserId = user.Id;
                        ParentNav = user.ParentNav;
                        int TopUserId = 0;
                        if (!string.IsNullOrEmpty(ParentNav))
                        {
                            TopUserId = int.Parse(ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                        }
                        decimal ActPrize = decimal.Parse(function.CheckNum(pos.SeoKeyword));
                        KqProducts brand = db.KqProducts.FirstOrDefault(m => m.Id == pos.BrandId) ?? new KqProducts();
                        if (brand.NoticeMoneyUnit == 2)
                        {
                            ActPrize = ActPrize / 100;
                        }
                        if (ActPrize > 0)
                        {
                            // if (ActPrize == 99)
                            // {
                            //     ActPrize = 100;
                            // }
                            // else if (ActPrize == 199)
                            // {
                            //     ActPrize = 200;
                            // }
                            // else if (ActPrize == 299)
                            // {
                            //     ActPrize = 300;
                            // }
                            // else if (ActPrize == 249)
                            // {
                            //     ActPrize = 260;
                            // }
                            ActPrize = 100;
                            if (GetUserId > 0)
                            {
                                doActiveReward(db, merchant, pos, GetUserId, ParentNav, TopUserId, ActPrize);
                                Utils.WriteLog("ActPrize:" + ActPrize + "", "实时处理激活奖励");
                            }
                        }
                        else if(ActPrize == 0)
                        {
                            if(pos.BrandId == 6)
                            {
                                doActiveReward(db, merchant, pos, GetUserId, ParentNav, TopUserId, 50);
                                Utils.WriteLog("ActPrize:50", "实时处理激活奖励");
                            }
                        }
                        PosMachinesTwo edit = db.PosMachinesTwo.FirstOrDefault(m => m.Id == pos.Id);
                        if(edit != null)
                        {
                            edit.Detail = "1";
                            db.SaveChanges();
                        }
                    }
                    // }
                }
            }
            db.Dispose();
        }
        //金控活动机返奖励
        private void doJk30(WebCMSEntities db, PosMachinesTwo pos, PosMerchantInfo merchant, int GetUserId, string ParentNav, int TopUserId)
        {
            // DateTime start = DateTime.Parse("2022-04-06 00:00:00");
            // DateTime end = DateTime.Parse("2022-07-05 00:00:00");
            // if((pos.BrandId == 1 || pos.BrandId == 3) && pos.CreateDate >= start && pos.CreateDate < end)
            // {
            //     decimal amt = 0;
            //     if(DateTime.Now < DateTime.Parse("2023-05-01 00:00:00"))
            //     {
            //         amt = 10;
            //     }
            //     if(amt > 0)
            //     {
            //         doActiveReward(db, merchant, pos, GetUserId, ParentNav, TopUserId, amt, 0, 1);
            //     }
            // }
        }

        //无押金激活奖励
        public void activePrizeWithoutDeposit(int posid = 0)
        {
            WebCMSEntities db = new WebCMSEntities();
            DateTime yesterday = DateTime.Now.AddDays(-31);
            DateTime today = DateTime.Now.AddMinutes(-10);
            List<int> BrandIds = new List<int>();
            BrandIds.Add(12);
            BrandIds.Add(13);
            BrandIds.Add(14);
            BrandIds.Add(15);
            BrandIds.Add(16);
            BrandIds.Add(23);
            BrandIds.Add(24);
            BrandIds.Add(25);
            BrandIds.Add(26);
            BrandIds.Add(32);
            IQueryable<PosMachinesTwo> posList = db.PosMachinesTwo.Where(m => m.ActivationState == 1 && (string.IsNullOrEmpty(m.SeoKeyword) || m.SeoKeyword == "0") && m.CreditTrade >= 5000 && !BrandIds.Contains(m.BrandId) && m.Detail != "1");
            if (posid > 0)
            {
                posList = posList.Where(m => m.Id == posid);
            }
            else
            {
                posList = posList.Where(m => m.ActivationTime >= yesterday && m.ActivationTime < today);
            }
            foreach (PosMachinesTwo pos in posList.ToList())
            {
                Utils.WriteLog("机具号:" + pos.PosSn, "无押金激活奖励日志");
                PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId);
                if (merchant != null)
                {
                    Utils.WriteLog("商户号:" + merchant.KqMerNo, "无押金激活奖励日志");
                    string ParentNav = "";
                    Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId);
                    if (user != null)
                    {
                        Utils.WriteLog("机具所属人:" + user.Id, "无押金激活奖励日志");
                        int GetUserId = user.Id;
                        ParentNav = user.ParentNav;
                        int TopUserId = 0;
                        if (!string.IsNullOrEmpty(ParentNav))
                        {
                            TopUserId = int.Parse(ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                        }
                        Utils.WriteLog("BindingTime:" + pos.BindingTime, "无押金激活奖励日志");
                        Utils.WriteLog("ActivationTime:" + pos.ActivationTime, "无押金激活奖励日志");
                        if(pos.BindingTime.Value.AddDays(30) >= pos.ActivationTime)
                        {
                            Utils.WriteLog("满足条件", "无押金激活奖励日志");
                            doActiveReward(db, merchant, pos, GetUserId, ParentNav, TopUserId, 30);
                            Utils.WriteLog("已发放", "无押金激活奖励日志");

                            DateTime now = pos.ActivationTime.Value;
                            //盟主奖励
                            if (pos.LeaderUserId > 0 && db.Leaders.Any(m => m.Id == pos.LeaderUserId && m.ExpiredDate > now) && pos.BindingTime > now.AddDays(-30) && pos.CardType < 100)
                            {
                                Utils.WriteLog("大盟主奖发放", "无押金激活奖励日志");
                                RedisDbconn.Instance.AddList("LeaderPrizeQueue", pos.Id);
                            }
                            //运营中心奖励
                            if (pos.BindingTime > now.AddDays(-30) && pos.CardType < 100)
                            {
                                Utils.WriteLog("运营中心奖发放", "无押金激活奖励日志");
                                RedisDbconn.Instance.AddList("OperatePrizeQueue", pos.Id);
                            }
                        }
                        PosMachinesTwo edit = db.PosMachinesTwo.FirstOrDefault(m => m.Id == pos.Id);
                        if(edit != null)
                        {
                            edit.Detail = "1";
                            db.SaveChanges();
                        }
                    }
                }
                Utils.WriteLog("\n\n\n", "无押金激活奖励日志");
            }
            db.Dispose();
        }

        public void activePrizeWithoutDeposit6(int posid = 0)
        {
            WebCMSEntities db = new WebCMSEntities();
            DateTime yesterday = DateTime.Now.AddDays(-30);
            DateTime today = DateTime.Now.AddMinutes(-10);
            IQueryable<PosMachinesTwo> posList = db.PosMachinesTwo.Where(m => m.ActivationState == 1 && m.CreditTrade >= 5000 && string.IsNullOrEmpty(m.SeoKeyword) && m.BrandId == 6 && m.Detail != "1");
            if (posid > 0)
            {
                posList = posList.Where(m => m.Id == posid);
            }
            else
            {
                posList = posList.Where(m => m.ActivationTime >= yesterday && m.ActivationTime < today);
            }
            foreach (PosMachinesTwo pos in posList.ToList())
            {
                PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId);
                if (merchant != null)
                {
                    string ParentNav = "";
                    Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId);
                    if (user != null)
                    {
                        int GetUserId = user.Id;
                        ParentNav = user.ParentNav;
                        int TopUserId = 0;
                        if (!string.IsNullOrEmpty(ParentNav))
                        {
                            TopUserId = int.Parse(ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                        }
                        // 立刷30天内刷满5000，无服务费机具，返50
                        if (pos.BrandId == 6 && pos.BindingTime > DateTime.Now.AddDays(-30))
                        {
                            doActiveReward(db, merchant, pos, GetUserId, ParentNav, TopUserId, 50);
                        }
                        PosMachinesTwo edit = db.PosMachinesTwo.FirstOrDefault(m => m.Id == pos.Id);
                        if(edit != null)
                        {
                            edit.Detail = "1";
                            db.SaveChanges();
                        }
                    }
                }
            }
            db.Dispose();
        }

        public void activePrizeWithoutDeposit12(int posid = 0)
        {
            WebCMSEntities db = new WebCMSEntities();
            DateTime yesterday = DateTime.Now.AddDays(-30);
            DateTime today = DateTime.Now.AddMinutes(-10);
            IQueryable<PosMachinesTwo> posList = db.PosMachinesTwo.Where(m => m.ActivationState == 1 && m.CreditTrade >= 5000 && string.IsNullOrEmpty(m.SeoKeyword) && (m.BrandId == 12 || m.BrandId == 13) && m.Detail != "1");
            if (posid > 0)
            {
                posList = posList.Where(m => m.Id == posid);
            }
            else
            {
                posList = posList.Where(m => m.ActivationTime >= yesterday && m.ActivationTime < today);
            }
            foreach (PosMachinesTwo pos in posList.ToList())
            {
                PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId);
                if (merchant != null)
                {
                    string ParentNav = "";
                    Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId);
                    if (user != null)
                    {
                        int GetUserId = user.Id;
                        ParentNav = user.ParentNav;
                        int TopUserId = 0;
                        if (!string.IsNullOrEmpty(ParentNav))
                        {
                            TopUserId = int.Parse(ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                        }
                        //首台无押金机返50
                        if(pos.BindingTime.Value.AddDays(30) >= pos.ActivationTime)
                        {
                            doActiveReward(db, merchant, pos, GetUserId, ParentNav, TopUserId, 30);

                            DateTime now = pos.ActivationTime.Value;
                            //盟主奖励
                            if (pos.LeaderUserId > 0 && db.Leaders.Any(m => m.Id == pos.LeaderUserId && m.ExpiredDate > now) && pos.BindingTime > now.AddDays(-30) && pos.CardType < 100)
                            {
                                Utils.WriteLog("大盟主奖发放", "开机奖励在激活中监控");
                                RedisDbconn.Instance.AddList("LeaderPrizeQueue", pos.Id);
                            }
                            //运营中心奖励
                            if (pos.BindingTime > now.AddDays(-30) && pos.CardType < 100)
                            {
                                Utils.WriteLog("运营中心奖发放", "开机奖励在激活中监控");
                                RedisDbconn.Instance.AddList("OperatePrizeQueue", pos.Id);
                            }
                        }
                        PosMachinesTwo item = db.PosMachinesTwo.FirstOrDefault(m => m.Id == pos.Id);
                        if(item != null)
                        {
                            item.Detail = "1";
                            db.SaveChanges();
                        }
                    }
                }
            }
            db.Dispose();
        }

        public void activePrizeWithoutDeposit15(int posid = 0)
        {
            WebCMSEntities db = new WebCMSEntities();
            DateTime yesterday = DateTime.Now.AddDays(-100);
            DateTime today = DateTime.Now.AddHours(-1);
            IQueryable<PosMachinesTwo> posList = db.PosMachinesTwo.Where(m => m.ActivationState == 1 && m.CreditTrade >= 5000 && string.IsNullOrEmpty(m.SeoKeyword) && (m.BrandId == 15 || m.BrandId == 16) && m.Detail != "1");
            if (posid > 0)
            {
                posList = posList.Where(m => m.Id == posid);
            }
            else
            {
                posList = posList.Where(m => m.ActivationTime >= yesterday && m.ActivationTime < today);
            }
            foreach (PosMachinesTwo pos in posList.ToList())
            {
                Utils.WriteLog("机具号:" + pos.PosSn + ";奖励标记:" + pos.Detail + ";", "实时处理来客吧0押激活奖励");
                PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId);
                if (merchant != null)
                {
                    string ParentNav = "";
                    Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId);
                    if (user != null)
                    {
                        int GetUserId = user.Id;
                        ParentNav = user.ParentNav;
                        int TopUserId = 0;
                        if (!string.IsNullOrEmpty(ParentNav))
                        {
                            TopUserId = int.Parse(ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                        }
                        //首台无押金机返50
                        if(pos.BindingTime.Value.AddDays(30) >= pos.ActivationTime)
                        {
                            doActiveReward(db, merchant, pos, GetUserId, ParentNav, TopUserId, 30);

                            DateTime now = pos.ActivationTime.Value;
                            //盟主奖励
                            if (pos.LeaderUserId > 0 && db.Leaders.Any(m => m.Id == pos.LeaderUserId && m.ExpiredDate > now) && pos.BindingTime > now.AddDays(-30) && pos.CardType < 100)
                            {
                                Utils.WriteLog("大盟主奖发放", "开机奖励在激活中监控");
                                RedisDbconn.Instance.AddList("LeaderPrizeQueue", pos.Id);
                            }
                            //运营中心奖励
                            if (pos.BindingTime > now.AddDays(-30) && pos.CardType < 100)
                            {
                                Utils.WriteLog("运营中心奖发放", "开机奖励在激活中监控");
                                RedisDbconn.Instance.AddList("OperatePrizeQueue", pos.Id);
                            }
                        }
                        Utils.WriteLog("ActPrize:30", "实时处理来客吧0押激活奖励");
                        PosMachinesTwo item = db.PosMachinesTwo.FirstOrDefault(m => m.Id == pos.Id);
                        if(item != null)
                        {
                            item.Detail = "1";
                            db.SaveChanges();
                        }
                    }
                }
            }
            db.Dispose();
        }


        public void activePrizeWithoutDeposit122(int posid = 0)
        {
            WebCMSEntities db = new WebCMSEntities();
            DateTime yesterday = DateTime.Now.AddDays(-30);
            DateTime today = DateTime.Now.AddMinutes(-5);
            DateTime checkTime = DateTime.Parse("2023-08-01 00:00:00");
            IQueryable<PosMachinesTwo> posList = db.PosMachinesTwo.Where(m => m.ActivationState == 1 && m.CreditTrade >= 1000 && m.ActivationTime < checkTime && string.IsNullOrEmpty(m.SeoKeyword) && (m.BrandId == 12 || m.BrandId == 13) && m.Detail != "1");
            if (posid > 0)
            {
                posList = posList.Where(m => m.Id == posid);
            }
            else
            {
                posList = posList.Where(m => m.ActivationTime >= yesterday && m.ActivationTime < today);
            }
            foreach (PosMachinesTwo pos in posList.ToList())
            {
                PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId);
                if (merchant != null)
                {
                    string ParentNav = "";
                    Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId);
                    if (user != null)
                    {
                        int GetUserId = user.Id;
                        ParentNav = user.ParentNav;
                        int TopUserId = 0;
                        if (!string.IsNullOrEmpty(ParentNav))
                        {
                            TopUserId = int.Parse(ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                        }
                        string IdCard = merchant.MerIdcardNo;
                        string IdCardStart = IdCard.Substring(0, 6);
                        string IdCardEnd = IdCard.Substring(IdCard.Length - 4);
                        string MerName = merchant.MerchantName;
                        List<int> BrandIds = new List<int>();
                        BrandIds.Add(4);
                        BrandIds.Add(5);
                        BrandIds.Add(8);
                        BrandIds.Add(9);
                        PosMerchantInfo other = db.PosMerchantInfo.FirstOrDefault(m => m.MerIdcardNo.StartsWith(IdCardStart) && m.MerIdcardNo.EndsWith(IdCardEnd) && m.MerchantName.Contains(MerName) && BrandIds.Contains(m.BrandId));
                        if(other != null)
                        {
                            PosMachinesTwo checkpos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == other.KqSnNo);
                            if(checkpos != null)
                            {
                                doActiveReward(db, merchant, pos, GetUserId, ParentNav, TopUserId, 50);
                                PosMachinesTwo edit = db.PosMachinesTwo.FirstOrDefault(m => m.Id == pos.Id);
                                if(edit != null)
                                {
                                    edit.SeoKeyword = Utils.Instance.TransferDeposit(edit, checkpos.SeoKeyword);
                                    edit.UpFeeFlag = checkpos.UpFeeFlag;
                                    edit.DownFeeFlag = checkpos.DownFeeFlag;
                                    edit.UpFeeDate = checkpos.UpFeeDate;
                                    edit.DownFeeDate = checkpos.DownFeeDate;
                                    edit.BindingTime = checkpos.BindingTime;
                                    edit.IsFirst = checkpos.IsFirst;
                                    db.SaveChanges();
                                    if(edit.UpFeeFlag == 1 && edit.DownFeeFlag == 0)
                                    {
                                        string info = "{\"RecordId\":\"\",\"PosId\":\"" + edit.Id + "\",\"Fee\": \"0.63\",\"Kind\": \"1\",\"OpMan\": \"系统\"}";
                                        RedisDbconn.Instance.AddList("SetDepositPostQueue", info);
                                    }
                                }
                            }
                        }
                        PosMachinesTwo item = db.PosMachinesTwo.FirstOrDefault(m => m.Id == pos.Id);
                        if(item != null)
                        {
                            item.Detail = "1";
                            db.SaveChanges();
                        }
                    }
                }
            }
            db.Dispose();
        }

        public void doActiveReward(WebCMSEntities db, PosMerchantInfo merchant, PosMachinesTwo pos, int GetUserId, string ParentNav, int TopUserId, decimal ActPrize, int ChangeType = 0, int ActType = 0)
        {
            if(GetUserId < 1) return;
            string MerNo = merchant.KqMerNo;
            //判断商户号是否为空，避免下次再有空商户的情况，导致奖励不发放
            List<int> ChkBrandIds = new List<int>();
            ChkBrandIds.Add(23);
            ChkBrandIds.Add(24);
            ChkBrandIds.Add(25);
            ChkBrandIds.Add(26);
            ChkBrandIds.Add(32);
            if(string.IsNullOrEmpty(MerNo) && !ChkBrandIds.Contains(pos.BrandId))
            {
                // MerNo = "n" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
                RedisDbconn.Instance.AddList("ActiveRewardFailQueue", "{\"PosId\":\"" + pos.Id + "\",\"UserId\":\"" + GetUserId + "\",\"ActPrize\":\"" + ActPrize + "\",\"ChangeType\":\"" + ChangeType + "\",\"ActType\":\"" + ActType + "\"}");
                return;
            }
            List<int> BrandIds = new List<int>();
            BrandIds.Add(18);
            BrandIds.Add(19);
            BrandIds.Add(20);
            BrandIds.Add(21);
            BrandIds.Add(29);
            BrandIds.Add(23);
            BrandIds.Add(24);
            BrandIds.Add(25);
            BrandIds.Add(26);
            BrandIds.Add(32);
            bool check = false;
            if(!BrandIds.Contains(pos.BrandId) && !MerNo.Contains("*"))
            {
                check = db.ActiveReward.Any(m => m.KqMerNo == MerNo && m.RewardAmount == ActPrize && m.ActType == ActType);
            }
            bool check1 = db.ActiveReward.Any(m => m.KqSnNo == pos.PosSn && m.RewardAmount == ActPrize && m.ActType == ActType);
            if(Utils.Instance.IsWifi(pos.BrandId))
            {
                // check1 = db.ActiveReward.Any(m => m.KqSnNo == pos.PosSn);
                check = false;
                check1 = false;
            }
            if (!check && !check1)
            {
                doActiveRewardFunc(db, merchant, pos, GetUserId, ParentNav, TopUserId, ActPrize, ChangeType, ActType);
            }
        }

        public void doActiveRewardFunc(WebCMSEntities db, PosMerchantInfo merchant, PosMachinesTwo pos, int GetUserId, string ParentNav, int TopUserId, decimal ActPrize, int ChangeType = 0, int ActType = 0)
        {            
            Utils.WriteLog(DateTime.Now.ToString() + ":" + pos.PosSn, "实时处理激活奖励");
            Users machineUser = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId) ?? new Users();
            db.ActiveReward.Add(new ActiveReward()
            {
                CreateDate = DateTime.Now,
                UpdateDate = DateTime.Now,
                UserId = GetUserId, //创客
                MerchantId = pos.BindMerchantId, //商户
                StandardDate = pos.ActivationTime, //达标日期
                RewardAmount = ActPrize, //奖励金额
                BrandId = pos.BrandId, //品牌
                UserNav = ParentNav, //创客父级
                DirectBuddyNo = merchant.UserId, //商户直属创客
                KqMerNo = merchant.KqMerNo, //渠道商户编号
                KqSnNo = pos.PosSn, //渠道SN号
                SnType = pos.PosSnType, //机具类型
                SnApplyUserId = pos.BuyUserId, //机具申请创客
                ActType = ActType, //激活类型
                SnStoreId = pos.StoreId, //SN仓库
                RewardTips = "激活奖励", //奖励描述
                Remark = "激活奖励", //备注
                ActDate = pos.ActivationTime, //激活时间
                TopUserId = TopUserId, //顶级创客
                SeoTitle = machineUser.RealName,
            });
            db.SaveChanges();
            string IdBrand = GetUserId + "_" + pos.BrandId;
            UserMachineData userData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
            if (userData == null)
            {
                userData = db.UserMachineData.Add(new UserMachineData()
                {
                    IdBrand = IdBrand,
                }).Entity;
                db.SaveChanges();
            }
            userData.ActProfit += ActPrize;
            db.SaveChanges();
            UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == GetUserId);
            if (account == null)
            {
                account = db.UserAccount.Add(new UserAccount()
                {
                    Id = GetUserId,
                    UserId = GetUserId,
                }).Entity;
                db.SaveChanges();
            }
            decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
            decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
            decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
            account.BalanceAmount += ActPrize;
            account.TotalAmount += ActPrize;
            decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
            decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
            decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
            UserAccountRecord userAccountRecord = db.UserAccountRecord.Add(new UserAccountRecord()
            {
                CreateDate = DateTime.Now,
                UpdateDate = DateTime.Now,
                UserId = GetUserId, //创客
                ChangeType = ChangeType, //变动类型
                ProductType = pos.BrandId, //产品类型
                ChangeAmount = ActPrize, //变更金额
                BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                AfterTotalAmount = AfterTotalAmount, //变更后总金额
                BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                QueryCount = pos.Id, //机具Id
                Kind = 3
            }).Entity;
            db.SaveChanges();

            //发送APP推送消息
            Utils.Instance.PrizePush(GetUserId, ActPrize);
        }

        public void doPrizeFunc(WebCMSEntities db, PosMerchantInfo merchant, PosMachinesTwo pos, int GetUserId, string ParentNav, int TopUserId, decimal ActPrize, int ChangeType = 0, int ActType = 0)
        {
            Users machineUser = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId) ?? new Users();
            UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == GetUserId);
            if (account == null)
            {
                account = db.UserAccount.Add(new UserAccount()
                {
                    Id = GetUserId,
                    UserId = GetUserId,
                }).Entity;
                db.SaveChanges();
            }
            decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
            decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
            decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
            account.BalanceAmount += ActPrize;
            account.TotalAmount += ActPrize;
            decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
            decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
            decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
            UserAccountRecord userAccountRecord = db.UserAccountRecord.Add(new UserAccountRecord()
            {
                CreateDate = DateTime.Now,
                UpdateDate = DateTime.Now,
                UserId = GetUserId, //创客
                ChangeType = ChangeType, //变动类型
                ProductType = pos.BrandId, //产品类型
                ChangeAmount = ActPrize, //变更金额
                BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                AfterTotalAmount = AfterTotalAmount, //变更后总金额
                BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                QueryCount = pos.Id, //机具Id
                Kind = 3
            }).Entity;
            db.SaveChanges();

            //发送APP推送消息
            Utils.Instance.PrizePush(GetUserId, ActPrize);
        }


        //根据商户信息发放激活奖励
        public void dosomething32(int merid = 0)
        {
            WebCMSEntities db = new WebCMSEntities();
            DateTime yesterday = DateTime.Now.AddHours(-3);
            DateTime today = DateTime.Now;
            IQueryable<PosMerchantInfo> merList = db.PosMerchantInfo.Where(m => m.ActiveStatus == 1 && !string.IsNullOrEmpty(m.SeoKeyword));
            if (merid > 0)
            {
                merList = merList.Where(m => m.Id == merid);
            }
            else
            {
                merList = merList.Where(m => m.MerStandardDate >= yesterday && m.MerStandardDate < today);
            }
            foreach (PosMerchantInfo merchant in merList.ToList())
            {
                // PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId && !string.IsNullOrEmpty(m.MerIdcardNo));
                // PosMerchantOtherInfo otherInfo = db.PosMerchantOtherInfo.FirstOrDefault(m => m.CertId == merchant.MerIdcardNo && m.PrizeFlag1 == 0);
                // if (otherInfo != null)
                // {
                //     otherInfo.PrizeFlag1 = 1;
                //     db.SaveChanges();
                MachineForMerNo forMerNo = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == merchant.MerchantNo) ?? new MachineForMerNo();
                PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == forMerNo.SnId) ?? new PosMachinesTwo();
                string ParentNav = "";
                Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId);
                if (user != null)
                {
                    int GetUserId = user.Id;
                    ParentNav = user.ParentNav;
                    int TopUserId = 0;
                    if (!string.IsNullOrEmpty(ParentNav))
                    {
                        TopUserId = int.Parse(ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                    }
                    decimal ActPrize = decimal.Parse(function.CheckNum(merchant.SeoKeyword));
                    KqProducts brand = db.KqProducts.FirstOrDefault(m => m.Id == pos.BrandId) ?? new KqProducts();
                    if (brand.NoticeMoneyUnit == 2)
                    {
                        ActPrize = ActPrize / 100;
                    }
                    if (ActPrize > 0)
                    {
                        bool check = db.ActiveReward.Any(m => m.KqSnNo == pos.PosSn);
                        if (!check)
                        {
                            if (ActPrize == 99)
                            {
                                ActPrize = 100;
                            }
                            else if (ActPrize == 199)
                            {
                                ActPrize = 200;
                            }
                            else if (ActPrize == 299)
                            {
                                ActPrize = 300;
                            }
                            Users machineUser = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId) ?? new Users();
                            db.ActiveReward.Add(new ActiveReward()
                            {
                                CreateDate = DateTime.Now,
                                UpdateDate = DateTime.Now,
                                UserId = GetUserId, //创客
                                MerchantId = pos.BindMerchantId, //商户
                                StandardDate = pos.ActivationTime, //达标日期
                                RewardAmount = ActPrize, //奖励金额
                                BrandId = pos.BrandId, //品牌
                                UserNav = ParentNav, //创客父级
                                DirectBuddyNo = merchant.UserId, //商户直属创客
                                KqMerNo = merchant.KqMerNo, //渠道商户编号
                                KqSnNo = pos.PosSn, //渠道SN号
                                SnType = pos.PosSnType, //机具类型
                                SnApplyUserId = pos.BuyUserId, //机具申请创客
                                ActType = 0, //激活类型
                                SnStoreId = pos.StoreId, //SN仓库
                                RewardTips = "激活奖励", //奖励描述
                                Remark = "激活奖励", //备注
                                ActDate = pos.ActivationTime, //激活时间
                                TopUserId = TopUserId, //顶级创客
                                SeoTitle = machineUser.RealName,
                            });
                            db.SaveChanges();
                            string IdBrand = GetUserId + "_" + pos.BrandId;
                            UserMachineData userData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
                            if (userData == null)
                            {
                                userData = db.UserMachineData.Add(new UserMachineData()
                                {
                                    IdBrand = IdBrand,
                                }).Entity;
                                db.SaveChanges();
                            }
                            userData.ActProfit += ActPrize;
                            db.SaveChanges();
                            UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == GetUserId);
                            if (account == null)
                            {
                                account = db.UserAccount.Add(new UserAccount()
                                {
                                    Id = GetUserId,
                                    UserId = GetUserId,
                                }).Entity;
                                db.SaveChanges();
                            }
                            decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                            decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                            decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                            account.BalanceAmount += ActPrize;
                            account.TotalAmount += ActPrize;
                            decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                            decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                            decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                            UserAccountRecord userAccountRecord = db.UserAccountRecord.Add(new UserAccountRecord()
                            {
                                CreateDate = DateTime.Now,
                                UpdateDate = DateTime.Now,
                                UserId = GetUserId, //创客
                                ChangeType = 0, //变动类型
                                ProductType = pos.BrandId, //产品类型
                                ChangeAmount = ActPrize, //变更金额
                                BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                                AfterTotalAmount = AfterTotalAmount, //变更后总金额
                                BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                                AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                                BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                                AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                            }).Entity;
                            db.SaveChanges();
                        }
                    }
                }
                // }
            }
            db.Dispose();
        }



        //3. 前一天的激活记录，根据创客类型，如果是商户型创客，则开机奖励的起始人从此人上级计算。如果不是，则从此人开始计算
        public void dosomething4(string date)
        {
            WebCMSEntities db = new WebCMSEntities();
            DateTime yesterday = DateTime.Parse(date + " 00:00:00");
            DateTime today = DateTime.Parse(DateTime.Parse(date).AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00");
            List<PosMachinesTwo> posList = db.PosMachinesTwo.Where(m => m.ActivationState == 1 && m.ActivationTime >= yesterday && m.ActivationTime < today && !string.IsNullOrEmpty(m.SeoKeyword) && m.SeoKeyword != "0" && m.CreditTrade >= 1000).ToList();
            foreach (PosMachinesTwo pos in posList)
            {
                if (pos.BindingTime > DateTime.Now.AddDays(-30))
                {
                    decimal ActPrize = decimal.Parse(function.CheckNum(pos.SeoKeyword));
                    if (ActPrize > 0)
                    {
                        // PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId && !string.IsNullOrEmpty(m.MerIdcardNo));
                        // PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId && m.Sort == 1);
                        PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId);
                        if (merchant != null)
                        {
                            // PosMerchantOtherInfo otherInfo = db.PosMerchantOtherInfo.FirstOrDefault(m => m.CertId == merchant.MerIdcardNo && m.PrizeFlag2 == 0);
                            // if (otherInfo != null)
                            // {
                            //     otherInfo.PrizeFlag2 = 1;
                            //     db.SaveChanges();
                            // 从机具所属人上级开始分开机奖励
                            Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId);
                            if (user != null)
                            {
                                if (!string.IsNullOrEmpty(user.ParentNav))
                                {
                                    decimal Prize = 20;
                                    string[] ParentNavs = user.ParentNav.Trim(',').Replace(",,", ",").Split(',');
                                    for (int i = ParentNavs.Length - 1; i >= 0; i--)
                                    {
                                        int UserId = int.Parse(ParentNavs[i]);
                                        Users puser = db.Users.FirstOrDefault(m => m.Id == UserId && m.AuthFlag == 1);
                                        if (puser != null && Prize > 0)
                                        {
                                            int machineCount = db.PosMachinesTwo.Count(m => m.BuyUserId == puser.Id && m.PosSnType == 0 && m.ActivationState == 0); //判断是否拥有3台兑换机
                                            int ActiveCount = db.PosMachinesTwo.Count(m => m.BuyUserId == puser.Id && m.ActivationState == 1); //判断是否拥有3台激活机（不限购买或赠送）
                                            int couponCount = db.PosCoupons.Count(m => m.UserId == puser.Id && m.IsUse == 0); //判断是否拥有3张券
                                            // int BigCount = db.PosMachinesTwo.Count(m => m.UserId == puser.Id && m.BrandId == 3); //判断是否拥有2台大机
                                            // int BigActiveCount = db.PosMachinesTwo.Count(m => m.UserId == puser.Id && m.ActivationState == 1 && m.BrandId == 3); //判断是否拥有2台激活大机（不限购买或赠送）
                                            if (machineCount + ActiveCount + couponCount >= 3)
                                            {
                                                int pTopUserId = 0;
                                                if (!string.IsNullOrEmpty(puser.ParentNav))
                                                {
                                                    pTopUserId = int.Parse(puser.ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                                                }
                                                Users machineUser = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId) ?? new Users();
                                                OpenRewardDetail detail = db.OpenRewardDetail.Add(new OpenRewardDetail()
                                                {
                                                    CreateDate = DateTime.Now,
                                                    UpdateDate = DateTime.Now,
                                                    TradeMonth = yesterday.ToString("yyyyMM"), //交易月
                                                    TradeDate = yesterday, //达标日期
                                                    UserId = puser.Id, //创客
                                                    BrandId = pos.BrandId, //品牌
                                                    ProductName = RelationClass.GetKqProductsInfo(pos.BrandId), //产品名称
                                                    MerchantId = pos.BindMerchantId, //商户
                                                    DirectUserId = merchant.UserId, //商户直属人
                                                    SnNo = pos.PosSn, //SN号
                                                    MerNo = merchant.KqMerNo, //渠道商户号
                                                    SnType = pos.PosSnType, //机具类型
                                                    StandardDate = pos.ActivationTime, //商户的激活日期
                                                    SnStoreId = pos.StoreId, //SN仓库
                                                    MerBuddyType = puser.MerchantType, //商户创客类型
                                                    RewardType = 1, //奖励类型 1-开机直接奖励，2-开机间接奖励
                                                    RewardTips = "开机奖励", //奖励描述
                                                    CreditTradeAmt = pos.CreditTrade, //贷记卡交易总金额
                                                    DebitTradeAmt = pos.DebitCardTrade, //借记卡交易总金额
                                                    CreditRewardAmount = Prize, //贷记卡交易奖励金额
                                                    RewardDesc = "开机奖励", //奖励描述
                                                    TopUserId = pTopUserId, //顶级创客
                                                    SeoTitle = machineUser.RealName,
                                                }).Entity;
                                                db.OpenReward.Add(new OpenReward()
                                                {
                                                    CreateDate = DateTime.Now,
                                                    UpdateDate = DateTime.Now,
                                                    TradeMonth = yesterday.ToString("yyyyMM"), //交易月
                                                    TradeDate = DateTime.Now, //达标日期
                                                    UserId = puser.Id, //创客
                                                    BrandId = pos.BrandId, //品牌
                                                    RewardType = 2, //奖励类型
                                                    CreditTradeAmt = pos.CreditTrade, //贷记卡交易总金额
                                                    DebitTradeAmt = pos.DebitCardTrade, //借记卡交易总金额
                                                    CreditRewardAmount = Prize, //贷记卡交易奖励金额
                                                    RewardDesc = "开机奖励", //奖励描述
                                                    TopUserId = pTopUserId, //顶级创客
                                                });
                                                string IdBrand = puser.Id + "_" + pos.BrandId;
                                                UserMachineData userData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
                                                if (userData == null)
                                                {
                                                    userData = db.UserMachineData.Add(new UserMachineData()
                                                    {
                                                        IdBrand = IdBrand,
                                                    }).Entity;
                                                    db.SaveChanges();
                                                }
                                                userData.OpenProfit += Prize;
                                                db.SaveChanges();
                                                //账户入库
                                                UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == puser.Id);
                                                if (account == null)
                                                {
                                                    account = db.UserAccount.Add(new UserAccount()
                                                    {
                                                        Id = puser.Id,
                                                        UserId = puser.Id,
                                                    }).Entity;
                                                    db.SaveChanges();
                                                }
                                                //收支明细入库
                                                decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                                                decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                                                decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                                                account.BalanceAmount += Prize;
                                                account.TotalAmount += Prize;
                                                decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                                                decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                                                decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                                                UserAccountRecord userAccountRecord = db.UserAccountRecord.Add(new UserAccountRecord()
                                                {
                                                    CreateDate = DateTime.Now,
                                                    UpdateDate = DateTime.Now,
                                                    UserId = puser.Id, //创客
                                                    ChangeType = 50, //变动类型
                                                    ProductType = pos.BrandId, //产品类型
                                                    ChangeAmount = Prize, //变更金额
                                                    BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                                                    AfterTotalAmount = AfterTotalAmount, //变更后总金额
                                                    BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                                                    AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                                                    BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                                                    AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                                                }).Entity;
                                                db.SaveChanges();

                                                Prize = 0;
                                            }
                                        }
                                    }
                                }
                            }
                            // }
                        }
                    }
                }
            }
            db.Dispose();
        }

        //实时获取开机奖励
        public void StartOpenReward()
        {
            Thread th = new Thread(StartOpenRewardDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StartOpenRewardDo()
        {
            while(true)
            {
                string content = RedisDbconn.Instance.RPop<string>("OpenRewardQueue");
                if(!string.IsNullOrEmpty(content))
                {
                    try
                    {
                        Utils.WriteLog("\n\n" + DateTime.Now.ToString() + "\nposid:" + content, "开机奖励发放日志");
                        int PosId = int.Parse(content);
                        Thread.Sleep(1000);
                        List<int> BrandIds = new List<int>();
                        BrandIds.Add(14);
                        BrandIds.Add(18);
                        BrandIds.Add(19);
                        BrandIds.Add(20);
                        BrandIds.Add(21);
                        BrandIds.Add(29);
                        BrandIds.Add(23);
                        BrandIds.Add(24);
                        BrandIds.Add(25);
                        BrandIds.Add(26);
                        BrandIds.Add(32);
                        WebCMSEntities db = new WebCMSEntities();
                        OpModels.WebCMSEntities opdb = new OpModels.WebCMSEntities();
                        PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == PosId && m.ActivationState == 1 && ((!string.IsNullOrEmpty(m.SeoKeyword) && m.SeoKeyword != "0" && m.CreditTrade >= 1000) || BrandIds.Contains(m.BrandId)));
                        if (pos != null)
                        {
                            Utils.WriteLog("sn:" + pos.PosSn, "开机奖励发放日志");
                            bool IsGet = true;
                            if(Utils.Instance.IsWifi(pos.BrandId))
                            {
                                int Count = db.OpenRewardDetail.Count(m => m.SnNo == pos.PosSn);
                                int Count1 = db.WifiTradeRecord.Count(m => m.SnNo == pos.PosSn);
                                IsGet = Count >= Count1;
                            }
                            else
                            {
                                IsGet = db.OpenRewardDetail.Any(m => m.SnNo == pos.PosSn);
                            }
                            if (pos.BindingTime > DateTime.Now.AddDays(-30) && !IsGet)
                            {
                                decimal ActPrize = decimal.Parse(function.CheckNum(pos.SeoKeyword));
                                Utils.WriteLog("押金:" + pos.SeoKeyword, "开机奖励发放日志");
                                if (ActPrize > 0 || pos.BrandId == 14)
                                {
                                    PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId) ?? new PosMerchantInfo();
                                    Utils.WriteLog("商户:" + merchant.KqMerNo, "开机奖励发放日志");
                                    Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId);
                                    if (user != null)
                                    {
                                        Utils.WriteLog("所属人:" + user.MakerCode, "开机奖励发放日志");
                                        string ParentNav = function.CheckNull(user.ParentNav) + "," + user.Id + ",";
                                        if (!string.IsNullOrEmpty(ParentNav))
                                        {
                                            decimal Prize = 0;
                                            if(pos.BrandId == 14)
                                            {
                                                Prize = 19 * 0.3M;
                                            }
                                            if(Utils.Instance.IsHaoDa(pos.BrandId))
                                            {
                                                Prize = 20;
                                            }
                                            if(Utils.Instance.IsWifi(pos.BrandId))
                                            {
                                                PxcModels.WifiTradeRecord trade = db.WifiTradeRecord.FirstOrDefault(m => m.SnNo == pos.PosSn);
                                                if (trade != null)
                                                {
                                                    Prize = trade.TradeAmount * 0.03M;
                                                }                                                    
                                            }
                                            List<int> CheckUserIds = RedisDbconn.Instance.GetList<int>("OpenPrizeUserIds", 1, 1000);
                                            if(CheckUserIds.Count > 0)
                                            {
                                                PosMachines posItem = db.PosMachines.FirstOrDefault(m => m.Id == pos.Id) ?? new PosMachines();
                                                if(posItem.UserId > 0)
                                                {
                                                    UserRankItem puser = PosCouponPrizeService.Instance.GetUserLevel(posItem.UserId);
                                                    if (puser.Id > 0 && (puser.LeaderLevel > 0 || puser.OperateLevel > 0) && Prize > 0)
                                                    {
                                                        bool op = false;
                                                        foreach(int CheckUserId in CheckUserIds)
                                                        {
                                                            if(puser.ParentNav.Contains("," + CheckUserId + ","))
                                                            {
                                                                op = true;
                                                                break;
                                                            }
                                                        }
                                                        if(op)
                                                        {
                                                            PostOpenReward(db, pos, merchant, puser, Prize);
                                                            Prize = 0;
                                                        }
                                                    }
                                                }
                                            }
                                            if(Prize > 0)
                                            {
                                                string[] ParentNavs = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                                                for (int i = ParentNavs.Length - 1; i >= 0; i--)
                                                {
                                                    int UserId = int.Parse(ParentNavs[i]);
                                                    // Users puser = db.Users.FirstOrDefault(m => m.Id == UserId && m.AuthFlag == 1 && m.Status > -1);
                                                    UserRankItem puser = PosCouponPrizeService.Instance.GetUserLevel(UserId);
                                                    if (puser.Id > 0 && Prize > 0)
                                                    {
                                                        Utils.WriteLog("上级:" + puser.MakerCode, "开机奖励发放日志");
                                                        Utils.WriteLog("条件:LeaderLevel:" + puser.LeaderLevel + ",UserType:" + puser.UserType, "开机奖励发放日志");
                                                        if(puser.UserType > 0 || puser.LeaderLevel > 0)
                                                        {
                                                            bool leaderOp = true;
                                                            if(puser.LeaderLevel > 0 && puser.UserType == 0)
                                                            {
                                                                DateTime now = DateTime.Now;
                                                                leaderOp = db.Leaders.Any(m => m.Id == puser.Id && m.ExpiredDate >= now);
                                                                Utils.WriteLog("条件:leaderOp:" + leaderOp, "开机奖励发放日志");
                                                            }
                                                            else if(puser.LeaderLevel == 0 && puser.UserType > 0)
                                                            {
                                                                DateTime now = DateTime.Now;
                                                                leaderOp = opdb.SysAdmin.Any(m => m.UserId == puser.Id && m.ExpireDate >= now);
                                                                Utils.WriteLog("条件:2-leaderOp:" + leaderOp, "盟主开机奖励发放日志");
                                                            }
                                                            else if(puser.LeaderLevel > 0 && puser.UserType > 0)
                                                            {
                                                                DateTime now = DateTime.Now;
                                                                leaderOp = db.Leaders.Any(m => m.Id == puser.Id && m.ExpiredDate >= now);
                                                                if(!leaderOp) leaderOp = opdb.SysAdmin.Any(m => m.UserId == puser.Id && m.ExpireDate >= now);
                                                            }
                                                            if(leaderOp)
                                                            {
                                                                Utils.WriteLog("满足条件", "开机奖励发放日志");
                                                                int pTopUserId = 0;
                                                                if (!string.IsNullOrEmpty(puser.ParentNav))
                                                                {
                                                                    pTopUserId = int.Parse(puser.ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                                                                }
                                                                PostOpenReward(db, pos, merchant, puser, Prize);
                                                                
                                                                Prize = 0;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        db.Dispose();
                        opdb.Dispose();
                    }
                    catch(Exception ex)
                    {
                        Utils.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "实时获取开机奖励异常");
                    }
                }
                else
                {
                    Thread.Sleep(5000);
                }
            }
        }

        public void StartLeaderReward()
        {
            Thread th = new Thread(StartLeaderRewardDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StartLeaderRewardDo()
        {
            while(true)
            {
                string content = RedisDbconn.Instance.RPop<string>("LeaderRewardQueue");
                if(!string.IsNullOrEmpty(content))
                {
                    try
                    {
                        Utils.WriteLog("\n\n" + DateTime.Now.ToString() + "\nposid:" + content, "盟主开机奖励发放日志");
                        int PosId = int.Parse(content);
                        Thread.Sleep(1000);
                        WebCMSEntities db = new WebCMSEntities();
                        OpModels.WebCMSEntities opdb = new OpModels.WebCMSEntities();
                        PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == PosId && m.ActivationState == 1 && m.CreditTrade >= 10000 && m.BrandId != 14);
                        if (pos != null)
                        {
                            Utils.WriteLog("sn:" + pos.PosSn, "盟主开机奖励发放日志");
                            bool IsGet = db.OpenRewardDetail.Any(m => m.SnNo == pos.PosSn);
                            if (!IsGet)
                            {
                                // decimal ActPrize = decimal.Parse(function.CheckNum(pos.SeoKeyword));
                                // Utils.WriteLog("押金:" + pos.SeoKeyword, "盟主开机奖励发放日志");
                                // if (ActPrize > 0)
                                // {
                                    PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId);
                                    if (merchant != null)
                                    {
                                        Utils.WriteLog("商户:" + merchant.KqMerNo, "盟主开机奖励发放日志");
                                        Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId);
                                        if (user != null)
                                        {
                                            Utils.WriteLog("所属人:" + user.MakerCode, "盟主开机奖励发放日志");
                                            string ParentNav = function.CheckNull(user.ParentNav) + "," + user.Id + ",";
                                            if (!string.IsNullOrEmpty(ParentNav))
                                            {
                                                decimal Prize = 50;
                                                string[] ParentNavs = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                                                for (int i = ParentNavs.Length - 1; i >= 0; i--)
                                                {
                                                    int UserId = int.Parse(ParentNavs[i]);
                                                    // Users puser = db.Users.FirstOrDefault(m => m.Id == UserId && m.AuthFlag == 1 && m.Status > -1);
                                                    UserRankItem puser = PosCouponPrizeService.Instance.GetUserLevel(UserId);
                                                    if (puser.Id > 0 && Prize > 0)
                                                    {
                                                        Utils.WriteLog("上级:" + puser.MakerCode, "盟主开机奖励发放日志");
                                                        Utils.WriteLog("条件:LeaderLevel:" + puser.LeaderLevel + ",UserType:" + puser.UserType, "盟主开机奖励发放日志");
                                                        if(puser.LeaderLevel > 0 || puser.UserType > 0)
                                                        {
                                                            bool leaderOp = true;
                                                            if(puser.LeaderLevel > 0 && puser.UserType == 0)
                                                            {
                                                                DateTime now = DateTime.Now;
                                                                leaderOp = db.Leaders.Any(m => m.Id == puser.Id && m.ExpiredDate >= now);
                                                                Utils.WriteLog("条件:1-leaderOp:" + leaderOp, "盟主开机奖励发放日志");
                                                            }
                                                            // else if(puser.LeaderLevel == 0 && puser.UserType > 0)
                                                            // {
                                                            //     DateTime now = DateTime.Now;
                                                            //     leaderOp = opdb.SysAdmin.Any(m => m.UserId == puser.Id && m.ExpireDate >= now);
                                                            //     Utils.WriteLog("条件:2-leaderOp:" + leaderOp, "盟主开机奖励发放日志");
                                                            // }
                                                            if(leaderOp)
                                                            {
                                                                Utils.WriteLog("满足条件", "盟主开机奖励发放日志");
                                                                int pTopUserId = 0;
                                                                if (!string.IsNullOrEmpty(puser.ParentNav))
                                                                {
                                                                    pTopUserId = int.Parse(puser.ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                                                                }
                                                                PostOpenReward(db, pos, merchant, puser, Prize);
                                                                
                                                                Prize = 0;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        // }
                                    }
                                // }
                            }
                        }
                        db.Dispose();
                        opdb.Dispose();
                    }
                    catch(Exception ex)
                    {
                        Utils.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "盟主开机奖励发放异常");
                    }
                }
                else
                {
                    Thread.Sleep(5000);
                }
            }
        }

        public void dosomething42(string date)
        {
            WebCMSEntities db = new WebCMSEntities();
            DateTime yesterday = DateTime.Parse(date + " 00:00:00");
            DateTime today = DateTime.Parse(DateTime.Parse(date).AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00");
            List<PosMerchantInfo> merList = db.PosMerchantInfo.Where(m => m.ActiveStatus == 1 && m.MerStandardDate >= yesterday && m.MerStandardDate < today && !string.IsNullOrEmpty(m.SeoKeyword) && m.SeoKeyword != "0").ToList();
            foreach (PosMerchantInfo merchant in merList)
            {
                MachineForMerNo forMerNo = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == merchant.MerchantNo) ?? new MachineForMerNo();
                PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == forMerNo.SnId) ?? new PosMachinesTwo();
                if (pos.ActivationTime > DateTime.Now.AddDays(-20) && pos.CreditTrade >= 1000)
                {
                    decimal ActPrize = decimal.Parse(function.CheckNum(merchant.SeoKeyword));
                    if (ActPrize > 0)
                    {
                        // PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId && !string.IsNullOrEmpty(m.MerIdcardNo));
                        // PosMerchantOtherInfo otherInfo = db.PosMerchantOtherInfo.FirstOrDefault(m => m.CertId == merchant.MerIdcardNo && m.PrizeFlag2 == 0);
                        // if (otherInfo != null)
                        // {
                        //     otherInfo.PrizeFlag2 = 1;
                        //     db.SaveChanges();
                        // 从机具所属人上级开始分开机奖励
                        Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId);
                        if (user != null)
                        {
                            if (!string.IsNullOrEmpty(user.ParentNav))
                            {
                                decimal Prize = 20;
                                string[] ParentNavs = user.ParentNav.Trim(',').Replace(",,", ",").Split(',');
                                for (int i = ParentNavs.Length - 1; i >= 0; i--)
                                {
                                    int UserId = int.Parse(ParentNavs[i]);
                                    Users puser = db.Users.FirstOrDefault(m => m.Id == UserId && m.AuthFlag == 1);
                                    if (puser != null && Prize > 0)
                                    {
                                        int machineCount = db.PosMachinesTwo.Count(m => m.BuyUserId == puser.Id && m.PosSnType == 0 && m.ActivationState == 0); //判断是否拥有3台兑换机
                                        int ActiveCount = db.PosMachinesTwo.Count(m => m.BuyUserId == puser.Id && m.ActivationState == 1); //判断是否拥有3台激活机（不限购买或赠送）
                                        int couponCount = db.PosCoupons.Count(m => m.UserId == puser.Id && m.IsUse == 0); //判断是否拥有3张券
                                        // int BigCount = db.PosMachinesTwo.Count(m => m.UserId == puser.Id && m.BrandId == 3); //判断是否拥有2台大机
                                        // int BigActiveCount = db.PosMachinesTwo.Count(m => m.UserId == puser.Id && m.ActivationState == 1 && m.BrandId == 3); //判断是否拥有2台激活大机（不限购买或赠送）
                                        if (machineCount + ActiveCount + couponCount >= 3)
                                        {
                                            int pTopUserId = 0;
                                            if (!string.IsNullOrEmpty(puser.ParentNav))
                                            {
                                                pTopUserId = int.Parse(puser.ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                                            }
                                            Users machineUser = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId) ?? new Users();
                                            OpenRewardDetail detail = db.OpenRewardDetail.Add(new OpenRewardDetail()
                                            {
                                                CreateDate = DateTime.Now,
                                                UpdateDate = DateTime.Now,
                                                TradeMonth = yesterday.ToString("yyyyMM"), //交易月
                                                TradeDate = yesterday, //达标日期
                                                UserId = puser.Id, //创客
                                                BrandId = pos.BrandId, //品牌
                                                ProductName = RelationClass.GetKqProductsInfo(pos.BrandId), //产品名称
                                                MerchantId = pos.BindMerchantId, //商户
                                                DirectUserId = merchant.UserId, //商户直属人
                                                SnNo = pos.PosSn, //SN号
                                                MerNo = merchant.KqMerNo, //渠道商户号
                                                SnType = pos.PosSnType, //机具类型
                                                StandardDate = pos.ActivationTime, //商户的激活日期
                                                SnStoreId = pos.StoreId, //SN仓库
                                                MerBuddyType = puser.MerchantType, //商户创客类型
                                                RewardType = 1, //奖励类型 1-开机直接奖励，2-开机间接奖励
                                                RewardTips = "开机奖励", //奖励描述
                                                CreditTradeAmt = pos.CreditTrade, //贷记卡交易总金额
                                                DebitTradeAmt = pos.DebitCardTrade, //借记卡交易总金额
                                                CreditRewardAmount = Prize, //贷记卡交易奖励金额
                                                RewardDesc = "开机奖励", //奖励描述
                                                TopUserId = pTopUserId, //顶级创客
                                                SeoTitle = machineUser.RealName,
                                            }).Entity;
                                            db.OpenReward.Add(new OpenReward()
                                            {
                                                CreateDate = DateTime.Now,
                                                UpdateDate = DateTime.Now,
                                                TradeMonth = yesterday.ToString("yyyyMM"), //交易月
                                                TradeDate = DateTime.Now, //达标日期
                                                UserId = puser.Id, //创客
                                                BrandId = pos.BrandId, //品牌
                                                RewardType = 2, //奖励类型
                                                CreditTradeAmt = pos.CreditTrade, //贷记卡交易总金额
                                                DebitTradeAmt = pos.DebitCardTrade, //借记卡交易总金额
                                                CreditRewardAmount = Prize, //贷记卡交易奖励金额
                                                RewardDesc = "开机奖励", //奖励描述
                                                TopUserId = pTopUserId, //顶级创客
                                            });
                                            string IdBrand = puser.Id + "_" + pos.BrandId;
                                            UserMachineData userData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
                                            if (userData == null)
                                            {
                                                userData = db.UserMachineData.Add(new UserMachineData()
                                                {
                                                    IdBrand = IdBrand,
                                                }).Entity;
                                                db.SaveChanges();
                                            }
                                            userData.OpenProfit += Prize;
                                            db.SaveChanges();
                                            //账户入库
                                            UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == puser.Id);
                                            if (account == null)
                                            {
                                                account = db.UserAccount.Add(new UserAccount()
                                                {
                                                    Id = puser.Id,
                                                    UserId = puser.Id,
                                                }).Entity;
                                                db.SaveChanges();
                                            }
                                            //收支明细入库
                                            decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                                            decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                                            decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                                            account.BalanceAmount += Prize;
                                            account.TotalAmount += Prize;
                                            decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                                            decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                                            decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                                            UserAccountRecord userAccountRecord = db.UserAccountRecord.Add(new UserAccountRecord()
                                            {
                                                CreateDate = DateTime.Now,
                                                UpdateDate = DateTime.Now,
                                                UserId = puser.Id, //创客
                                                ChangeType = 50, //变动类型
                                                ProductType = pos.BrandId, //产品类型
                                                ChangeAmount = Prize, //变更金额
                                                BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                                                AfterTotalAmount = AfterTotalAmount, //变更后总金额
                                                BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                                                AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                                                BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                                                AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                                            }).Entity;
                                            db.SaveChanges();

                                            string dateString = yesterday.ToString("yyyyMMdd");
                                            string monthString = yesterday.ToString("yyyyMM");
                                            // 开机奖励列表
                                            List<string> dates = RedisDbconn.Instance.GetList<string>("OpenRewardDay:" + puser.Id + ":" + pos.BrandId);
                                            if (!dates.Contains(dateString))
                                            {
                                                RedisDbconn.Instance.AddList("OpenRewardDay:" + puser.Id + ":" + pos.BrandId, dateString);
                                            }
                                            RedisDbconn.Instance.AddNumber("OpenRewardAmt:" + puser.Id + ":" + pos.BrandId + ":" + dateString, Prize);

                                            List<string> months = RedisDbconn.Instance.GetList<string>("OpenRewardMonth:" + puser.Id + ":" + pos.BrandId);
                                            if (!months.Contains(monthString))
                                            {
                                                RedisDbconn.Instance.AddList("OpenRewardMonth:" + puser.Id + ":" + pos.BrandId, monthString);
                                            }
                                            RedisDbconn.Instance.AddNumber("OpenRewardAmt:" + puser.Id + ":" + pos.BrandId + ":" + monthString, Prize);

                                            // 开机奖励详情
                                            RedisDbconn.Instance.AddList("OpenRewardDetail:" + puser.Id + ":" + pos.BrandId + ":" + dateString, detail);

                                            Prize -= 10;
                                        }
                                    }
                                }
                            }
                        }
                        // }
                    }
                }
            }
            db.Dispose();
        }


        // 4. 前一天的流量卡记录和匹配
        public void ListenFluxRecord()
        {
            Thread th = new Thread(ListenFluxRecordD0);
            th.IsBackground = true;
            th.Start();
        }
        public void ListenFluxRecordD0()
        {
            while(true)
            {
                if(DateTime.Now.Hour > 0)
                {
                    CheckFluxForTrade();
                }
                Thread.Sleep(600000);
            }
        }
        public void doFluxRecord()
        {
            Utils.WriteLog(DateTime.Now.ToString(), "执行流量费返佣");
            SpModels.WebCMSEntities spdb = new SpModels.WebCMSEntities();
            WebCMSEntities db = new WebCMSEntities();
            DateTime start = DateTime.Now.AddDays(-20);
            List<SpModels.TradeFluxRecord> trades = spdb.TradeFluxRecord.Where(m => m.CreateDate >= start && m.Status == 1).ToList();
            foreach (SpModels.TradeFluxRecord trade in trades)
            {
                try
                {
                    string OrderNo = trade.TradeSerialNo; //单号
                    DateTime TradeDate = trade.CreateDate.Value;
                    string TradeMonth = TradeDate.ToString("yyyyMM");
                    decimal FeeAmount = trade.FeeAmount; //流量费
                    int BrandId = int.Parse(trade.ProductType);
                    KqProducts brand = db.KqProducts.FirstOrDefault(m => m.Id == BrandId) ?? new KqProducts();
                    if (brand.NoticeMoneyUnit == 2)
                    {
                        FeeAmount = FeeAmount / 100;
                    }
                    string TradeSnNo = trade.TradeSnNo; //机具SN
                    decimal FluxProfit = 0;
                    if (trade.ProductType == "1" && FeeAmount == 60)
                    {
                        FluxProfit = 24;
                    }
                    else if (trade.ProductType == "7" && FeeAmount == 46)
                    {
                        FluxProfit = 10;
                    }
                    else if (trade.ProductType != "1" && FeeAmount == 48)
                    {
                        FluxProfit = 12;
                    }
                    else if (trade.ProductType != "1" && FeeAmount == 60)
                    {
                        FluxProfit = 24;
                    }
                    if (FluxProfit > 0)
                    {
                        MachineForSnNo forSnNo = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == TradeSnNo) ?? new MachineForSnNo();
                        PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == forSnNo.SnId) ?? new PosMachinesTwo();
                        // PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId && m.Sort == 1);
                        PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId);
                        if (merchant != null && pos.BrandId != 6)
                        {
                            bool checkExist = db.FluxProfitDetail.Any(m => m.MerNo == merchant.KqMerNo);
                            if (!checkExist && decimal.Parse(function.CheckNum(pos.SeoKeyword)) > 0)
                            {
                                Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId) ?? new Users();
                                int GetUserId = user.Id;
                                int TopUserId = 0;
                                string ParentNav = user.ParentNav;
                                if (!string.IsNullOrEmpty(ParentNav))
                                {
                                    string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                                    if (ParentNavList.Length > 1)
                                    {
                                        TopUserId = int.Parse(ParentNavList[1]);
                                    }
                                    else if (ParentNavList.Length == 1)
                                    {
                                        TopUserId = int.Parse(ParentNavList[0]);
                                    }
                                }
                                FluxProfitSummary fluxProfit = db.FluxProfitSummary.FirstOrDefault(m => m.UserId == GetUserId && m.BrandId == pos.BrandId && m.TradeMonth == TradeMonth);
                                if (fluxProfit == null)
                                {
                                    fluxProfit = db.FluxProfitSummary.Add(new FluxProfitSummary()
                                    {
                                        CreateDate = DateTime.Now,
                                        UpdateDate = DateTime.Now,
                                        UserId = GetUserId, //创客
                                        BrandId = pos.BrandId,
                                        TopUserId = TopUserId, //顶级创客
                                        TradeMonth = TradeMonth, //交易月
                                        MerUserType = user.MerchantType, //商户创客类型
                                        Remark = "流量卡分佣", //备注
                                    }).Entity;
                                    db.SaveChanges();
                                }
                                fluxProfit.FluxProfitAmt += FluxProfit; //流量分润总金额
                                db.FluxProfitDetail.Add(new FluxProfitDetail()
                                {
                                    CreateDate = DateTime.Now,
                                    UpdateDate = DateTime.Now,
                                    RecordNo = OrderNo, //单号
                                    TradeDate = TradeDate.ToString("yyyyMMdd"), //交易日期
                                    TradeTime = TradeDate.ToString("HHmmss"), //交易时间
                                    TradeMonth = TradeMonth, //交易月
                                    UserId = GetUserId, //创客
                                    MerchantId = pos.BindMerchantId, //商户
                                    MerchantUserId = pos.UserId, //商户直属人
                                    MerNo = merchant.KqMerNo, //渠道商户编号
                                    SnNo = pos.PosSn, //渠道SN号
                                    FluxOrderNo = OrderNo, //流量扣费单号
                                    TradeOrderNo = OrderNo, //交易流水号
                                    TradeAmt = trade.TradeAmount, //商户交易额
                                    FluxFeeAmt = FeeAmount, //流量费
                                    FluxProfitAmt = FluxProfit, //流量分润总金额
                                    PosType = pos.PosSnType.ToString(), //POS类型
                                    Remark = "流量卡分佣", //备注
                                    BrandId = pos.BrandId, //品牌
                                    TopUserId = TopUserId, //顶级创客
                                    MerUserType = user.MerchantType, //商户创客类型
                                });
                                string IdBrand = user.Id + "_" + pos.BrandId;
                                UserMachineData userData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
                                if (userData == null)
                                {
                                    userData = db.UserMachineData.Add(new UserMachineData()
                                    {
                                        IdBrand = IdBrand,
                                    }).Entity;
                                    db.SaveChanges();
                                }
                                userData.FluxProfit += FluxProfit;
                                db.SaveChanges();
                                UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == GetUserId);
                                if (account == null)
                                {
                                    account = db.UserAccount.Add(new UserAccount()
                                    {
                                        Id = GetUserId,
                                        UserId = GetUserId,
                                    }).Entity;
                                    db.SaveChanges();
                                }
                                decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                                decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                                decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                                account.BalanceAmount += FluxProfit;
                                account.TotalAmount += FluxProfit;
                                decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                                decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                                decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                                UserAccountRecord userAccountRecord = db.UserAccountRecord.Add(new UserAccountRecord()
                                {
                                    CreateDate = DateTime.Now,
                                    UpdateDate = DateTime.Now,
                                    UserId = GetUserId, //创客
                                    ChangeType = 60, //变动类型
                                    ProductType = pos.BrandId, //产品类型
                                    ChangeAmount = FluxProfit, //变更金额
                                    BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                                    AfterTotalAmount = AfterTotalAmount, //变更后总金额
                                    BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                                    AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                                    BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                                    AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                                }).Entity;
                                db.SaveChanges();
                            }
                            SpModels.TradeFluxRecord edit = spdb.TradeFluxRecord.FirstOrDefault(m => m.Id == trade.Id);
                            if (edit != null)
                            {
                                edit.Status = 2;
                                spdb.SaveChanges();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Utils.WriteLog(DateTime.Now.ToString() + "\n$" + trade.Id + "$\n" + ex.ToString(), "流量卡分佣异常");
                }
            }
            spdb.Dispose();
            db.Dispose();
            Utils.WriteLog(DateTime.Now.ToString() + "\n", "执行流量费返佣");
        }
        public void CheckFluxForTrade()
        {
            Utils.WriteLog(DateTime.Now.ToString(), "扫描交易记录中的流量费");
            SpModels.WebCMSEntities spdb = new SpModels.WebCMSEntities();
            DateTime start = DateTime.Now.AddDays(-120);
            int StartId = int.Parse(function.CheckInt(function.ReadInstance("/SycnSp/TradeRecordId.txt")));
            List<string> BrandIds = new List<string>();
            BrandIds.Add("1");
            BrandIds.Add("10");
            BrandIds.Add("12");
            var list = spdb.TradeRecord.Select(m => new { m.Id, m.CreateDate, m.ProductType, m.Status }).Where(m => m.Id >= StartId && m.Status == 2 && m.CreateDate > start && BrandIds.Contains(m.ProductType)).OrderBy(m => m.CreateDate);
            foreach (var sub in list.ToList())
            {
                try
                {
                    SpModels.TradeRecord trade = spdb.TradeRecord.FirstOrDefault(m => m.Id == sub.Id);
                    if (trade != null)
                    {
                        if(trade.ProductType == "1") //金控
                        {
                            string content = trade.SeoDescription;
                            if (!string.IsNullOrEmpty(content))
                            {
                                content = System.Web.HttpUtility.UrlDecode(content);
                                JsonData jsonObj = JsonMapper.ToObject(content);
                                decimal terminalDataFlowFee = decimal.Parse(function.CheckNum(jsonObj["terminalDataFlowFee"].ToString()));
                                if (terminalDataFlowFee > 0)
                                {
                                    spdb.TradeFluxRecord.Add(new SpModels.TradeFluxRecord()
                                    {
                                        SeoDescription = trade.TradeSerialNo,
                                        FeeAmount = terminalDataFlowFee,
                                        TradeSerialNo = function.MD5_16(trade.TradeSerialNo),
                                        CreateDate = trade.CreateDate,
                                        TradeSnNo = trade.TradeSnNo,
                                        ProductType = trade.ProductType,
                                        Status = 1,
                                    });
                                    spdb.SaveChanges();
                                }
                            }
                        }
                        else if(trade.ProductType == "10" || trade.ProductType == "12") //10联动、12盒易付
                        {
                            if (trade.DigAmt > 0)
                            {
                                spdb.TradeFluxRecord.Add(new SpModels.TradeFluxRecord()
                                {
                                    SeoDescription = trade.TradeSerialNo,
                                    FeeAmount = trade.DigAmt,
                                    TradeSerialNo = function.MD5_16(trade.TradeSerialNo),
                                    CreateDate = trade.CreateDate,
                                    TradeSnNo = trade.TradeSnNo,
                                    ProductType = trade.ProductType,
                                    Status = 1,
                                });
                                spdb.SaveChanges();
                            }
                        }
                        trade.Status = 3;
                        spdb.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    Utils.WriteLog(DateTime.Now.ToString() + "\n$" + sub.Id + "$\n" + ex.ToString(), "扫描交易记录中的流量费异常");
                }
            }
            spdb.Dispose();
            Utils.WriteLog(DateTime.Now.ToString() + "\n", "扫描交易记录中的流量费");

            // doFluxRecord();
        }






        // 每天统计头一天的交易额
        public void StartEverDay()
        {
            string TradeMonth = DateTime.Now.AddMonths(-6).ToString("yyyyMM");
            // string PreMonth = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            // if(DateTime.Now.Day == 1)
            // {
            //     TradeMonth = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            //     PreMonth = DateTime.Now.AddMonths(-2).ToString("yyyyMM");
            // }
            // else 
            if(DateTime.Now.Day == 1)
            {
                CustomerSqlConn.op("update Users set ThisMonthTrade=0 where ThisMonthTrade>0", MysqlConn.SqlConnStr);
            }
            Dictionary<string, decimal> dic = new Dictionary<string, decimal>();
            DataTable list = CustomerSqlConn.dtable("select UserId,sum(HelpNonDirectTradeAmt+HelpNonDirectDebitTradeAmt+NotHelpNonDirectTradeAmt+NotHelpNonDirectDebitTradeAmt+ProfitNonDirectTradeAmt+ProfitNonDirectDebitTradeAmt) from TradeDaySummary where Id>=15055757 and TradeMonth>='" + TradeMonth + "' and SeoTitle='team' and UserId>0 group by UserId", MysqlConn.ReadSqlConnStr);
            foreach (DataRow dr in list.Rows)
            {
                string UserId = dr["UserId"].ToString();
                string ThisMonthTrade = dr[1].ToString();
                dic.Add(UserId, decimal.Parse(function.CheckNum(ThisMonthTrade)));
            }
            list = CustomerSqlConn.dtable("select UserId,sum(ProfitTradeAmt+ProfitDebitTradeAmt) from TradeDaySummary2 where TradeMonth>='" + TradeMonth + "' and SeoTitle='team' and UserId>0 group by UserId", MysqlConn.ReadSqlConnStr);
            foreach (DataRow dr in list.Rows)
            {
                string UserId = dr["UserId"].ToString();
                string ThisMonthTrade = dr[1].ToString();
                if(dic.ContainsKey(UserId))
                {
                    dic[UserId] += decimal.Parse(function.CheckNum(ThisMonthTrade));
                }
                else
                {
                    dic.Add(UserId, decimal.Parse(function.CheckNum(ThisMonthTrade)));
                }
            }
            // list = CustomerSqlConn.dtable("select UserId,sum(ActiveBuddyMerStatus)*10000 from UserTradeMonthSummary where TradeMonth>='" + TradeMonth + "' and BrandId=14 and SeoTitle='team' and UserId>0 group by UserId", MysqlConn.ReadSqlConnStr);
            // foreach (DataRow dr in list.Rows)
            // {
            //     string UserId = dr["UserId"].ToString();
            //     string ThisMonthTrade = dr[1].ToString();
            //     if(dic.ContainsKey(UserId))
            //     {
            //         dic[UserId] += decimal.Parse(function.CheckNum(ThisMonthTrade));
            //     }
            //     else
            //     {
            //         dic.Add(UserId, decimal.Parse(function.CheckNum(ThisMonthTrade)));
            //     }
            // }
            list = CustomerSqlConn.dtable("select UserId,sum(TotalAmount) from UserAmountSummary where TradeMonth>='" + TradeMonth + "' and SeoTitle='team' and UserId>0 group by UserId", MysqlConn.MpSqlConnStr);
            foreach (DataRow dr in list.Rows)
            {
                string UserId = dr["UserId"].ToString();
                string ThisMonthTrade = dr[1].ToString();
                if(dic.ContainsKey(UserId))
                {
                    dic[UserId] += decimal.Parse(function.CheckNum(ThisMonthTrade));
                }
                else
                {
                    dic.Add(UserId, decimal.Parse(function.CheckNum(ThisMonthTrade)));
                }
            }
            list = CustomerSqlConn.dtable("select UserId,sum(TotalAmount) from UserAmountSummary where TradeMonth>='" + TradeMonth + "' and SeoTitle='team' and UserId>0 group by UserId", MysqlConn.MpSqlConnStr2);
            foreach (DataRow dr in list.Rows)
            {
                string UserId = dr["UserId"].ToString();
                string ThisMonthTrade = dr[1].ToString();
                if(dic.ContainsKey(UserId))
                {
                    dic[UserId] += decimal.Parse(function.CheckNum(ThisMonthTrade));
                }
                else
                {
                    dic.Add(UserId, decimal.Parse(function.CheckNum(ThisMonthTrade)));
                }
            }
            // list = CustomerSqlConn.dtable("select UserId,SimValidActTeamCount*10000 from KxsStatServer.SimValidAct" + PreMonth + " where UserId>0", MysqlConn.ReadSqlConnStr);
            // foreach (DataRow dr in list.Rows)
            // {
            //     string UserId = dr["UserId"].ToString();
            //     string ThisMonthTrade = dr[1].ToString();
            //     if(dic.ContainsKey(UserId))
            //     {
            //         dic[UserId] += decimal.Parse(function.CheckNum(ThisMonthTrade));
            //     }
            //     else
            //     {
            //         dic.Add(UserId, decimal.Parse(function.CheckNum(ThisMonthTrade)));
            //     }
            // }
            list = CustomerSqlConn.dtable("select UserId,sum(TradeAmount) from HelpProfitUserTradeSummay where UserId>0 and TradeMonth>='" + TradeMonth + "' and SeoTitle='team' group by UserId", MysqlConn.ReadSqlConnStr);
            foreach (DataRow dr in list.Rows)
            {
                string UserId = dr["UserId"].ToString();
                string ThisMonthTrade = dr[1].ToString();
                if(dic.ContainsKey(UserId))
                {
                    dic[UserId] += decimal.Parse(function.CheckNum(ThisMonthTrade));
                }
                else
                {
                    dic.Add(UserId, decimal.Parse(function.CheckNum(ThisMonthTrade)));
                }
            }

            int index = 0;
            string sql = "";
            foreach(string UserId in dic.Keys)
            {
                index += 1;
                sql += "update Users set ThisMonthTrade=" + dic[UserId] + " where Id=" + UserId + ";";
                if(index >= 200)
                {
                    CustomerSqlConn.op(sql, MysqlConn.SqlConnStr);
                    sql = "";
                    index = 0;
                }
            }
            if(!string.IsNullOrEmpty(sql))
            {
                CustomerSqlConn.op(sql, MysqlConn.SqlConnStr);
            }
        }
        public void StatTradeAmountEverDay(object sender)
        {
            string date = sender.ToString();
            Utils.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();
                }
                Utils.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 + "')");
                Utils.WriteLog("交易人数:" + userDt.Rows.Count + "\n\n", "执行昨天交易额日志");
                foreach (DataRow userDr in userDt.Rows)
                {
                    int UserId = int.Parse(userDr["Id"].ToString());
                    string ParentNav = userDr["ParentNav"].ToString();
                    Utils.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");
                    Utils.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);
                                Utils.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");
                                Utils.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)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "统计昨天的交易额异常");
            }
            db.Dispose();
            Utils.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行昨天交易额日志");

            StatMerchantTrade(date);
        }

        





        //统计商户交易额
        private void StatMerchantTrade(string date)
        {
            Utils.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "执行商户交易额日志");
            try
            {
                string start = date + " 00:00:00";
                string end = DateTime.Parse(date).AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00";
                CustomerSqlConn.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 Id>=13000000 and CreateDate>='" + start + "' and CreateDate<'" + end + "' and ActStatus=1 and BrandId!=14 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", MysqlConn.SqlConnStr);
            }
            catch (Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "统计商户的交易额");
            }

            WebCMSEntities db = new WebCMSEntities();
            var tran = db.Database.BeginTransaction();
            try
            {
                SpModels.WebCMSEntities spdb = new SpModels.WebCMSEntities();
                DateTime s = DateTime.Parse(date + " 00:00:00");
                DateTime e = s.AddDays(1);
                int StartId = int.Parse(function.CheckInt(function.ReadInstance("/SycnSp/TradeRecordId.txt")));
                IQueryable<SpModels.TradeRecord> trades = spdb.TradeRecord.Where(m => m.Id >= StartId && m.ProductType == "23" && m.CreateDate >= s && m.CreateDate < e).OrderBy(m => m.CreateDate);
                foreach (SpModels.TradeRecord trade in trades.ToList())
                {
                    string MerNo = trade.TradeSnNo;
                    string TradeDate = trade.CreateDate.Value.ToString("yyyyMMdd");
                    string TradeMonth = TradeDate.Substring(0, 6);
                    PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.KqMerNo == MerNo);
                    if(merchant != null)
                    {
                        PosMerchantTradeSummay stat = db.PosMerchantTradeSummay.FirstOrDefault(m => m.MerchantId == merchant.Id && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == merchant.BrandId);
                        if (stat == null)
                        {
                            stat = db.PosMerchantTradeSummay.Add(new PosMerchantTradeSummay()
                            {
                                MerchantId = merchant.Id,
                                TradeMonth = TradeMonth,
                                TradeDate = TradeDate,
                                BrandId = merchant.BrandId,
                            }).Entity;
                            db.SaveChanges();
                        }
                        stat.TradeAmount += trade.TradeAmount / 100;
                        db.SaveChanges();
                    }
                }
                spdb.Dispose();
                tran.Commit();
            }
            catch (Exception ex)
            {
                tran.Rollback();
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "统计WIFI商户的交易额");
            }
            tran.Dispose();
            db.Dispose();
            Utils.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行商户交易额日志");
        }


        // 5. 创客升级
        public void StatUserLevel()
        {
            Thread th = new Thread(StatUserLevelDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StatUserLevelDo()
        {
            while (true)
            {
                if(DateTime.Now.Day < 15 && DateTime.Now.Hour >= 0)
                {
                    string Month = DateTime.Now.AddDays(-1).ToString("yyyy-MM");
                    string flag = function.ReadInstance("/ProfitFlag/" + Month + ".txt");
                    if (string.IsNullOrEmpty(flag))
                    {
                        function.WritePage("/ProfitFlag/", Month + ".txt", DateTime.Now.ToString("HH:mm:ss"));
                        LogoutUserHelper.Instance.DoWorks(); //每月一号归档注销创客,把伞下创客归到注销创客的上级
                        StatUserLevelStartNew();
                    }
                }
                Thread.Sleep(600000);
            }
        }
        public void StatUserLevelStart()
        {
            WebCMSEntities db = new WebCMSEntities();
            MpMainModels.WebCMSEntities mpmaindb = new MpMainModels.WebCMSEntities();
            try
            {
                OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["Pxc1SqlConnStr"].ToString();
                Utils.WriteLog(DateTime.Now.ToString(), "创客升级日志");
                DateTime start = DateTime.Parse(DateTime.Now.AddMonths(-1).ToString("yyyy-MM") + "-01 00:00:00");
                DateTime end = start.AddDays(1);
                string TradeMonth = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
                List<UserLevelSet> sets = db.UserLevelSet.ToList();
                bool op = true;
                int startid = 0;
                while(op)
                {
                    var users = db.Users.Select(m => new { m.Id, m.AuthFlag }).Where(m => m.Id > startid && m.AuthFlag == 1).OrderBy(m => m.Id).Take(500).ToList();
                    Utils.WriteLog(users.Count.ToString(), "创客升级日志");
                    if(users.Count > 0)
                    {
                        foreach (var subuser in users)
                        {
                            Users user = db.Users.FirstOrDefault(m => m.Id == subuser.Id);
                            if (user != null)
                            {
                                int BeforeLevel = user.UserLevel;
                                int AfterLevel = 0;
                                decimal TradeAmount = 0;
                                //创客团队交易额
                                bool check = db.TradeDaySummary.Any(m => m.UserId == user.Id && m.TradeMonth == TradeMonth && m.SeoTitle == "team");
                                if (check)
                                {
                                    TradeAmount += db.TradeDaySummary.Where(m => m.UserId == user.Id && m.TradeMonth == TradeMonth && m.SeoTitle == "team").Sum(m => m.HelpNonDirectTradeAmt + m.HelpNonDirectDebitTradeAmt + m.NotHelpNonDirectTradeAmt + m.NotHelpNonDirectDebitTradeAmt + m.ProfitNonDirectTradeAmt + m.ProfitNonDirectDebitTradeAmt);
                                }
                                //助利宝团队交易额
                                DataTable checkdt = OtherMySqlConn.dtable("SELECT SUM(TradeAmount) TradeAmount FROM HelpProfitMerTradeSummay WHERE (MerchantId IN(SELECT MerchantId FROM HelpProfitMerIds WHERE UserId IN(SELECT Id from Users WHERE ParentNav like '%," + user.Id + ",%' OR Id=" + user.Id + "))) AND TradeMonth=" + TradeMonth + "");
                                if (checkdt.Rows.Count > 0)
                                {
                                    TradeAmount += decimal.Parse(function.CheckNum(checkdt.Rows[0]["TradeAmount"].ToString()));
                                }
                                //码牌团队交易额
                                check = mpmaindb.UserAmountSummary.Any(m => m.UserId == user.Id && m.TradeMonth == TradeMonth && m.SeoTitle == "team");
                                if (check)
                                {
                                    TradeAmount += mpmaindb.UserAmountSummary.Where(m => m.UserId == user.Id && m.TradeMonth == TradeMonth && m.SeoTitle == "team").Sum(m => m.TotalAmount);
                                }
                                UserLevelSet set = sets.FirstOrDefault(m => m.UpLevelGrowth <= TradeAmount && m.UpLevelIntegral > TradeAmount);
                                if (set != null)
                                {
                                    AfterLevel = set.Id;
                                }

                                // K6以上计算小市场是否达标
                                // 升级逻辑
                                bool upFlag = true;
                                if(AfterLevel > 5)
                                {
                                    DataTable dt = OtherMySqlConn.dtable("select UserId,sum(HelpNonDirectTradeAmt+NotHelpNonDirectTradeAmt+ProfitNonDirectTradeAmt+HelpNonDirectDebitTradeAmt+NotHelpNonDirectDebitTradeAmt+ProfitNonDirectDebitTradeAmt) from TradeDaySummary where UserId in (select Id from Users where ParentUserId=" + user.Id + ") and TradeMonth='" + TradeMonth + "' and SeoTitle='team' group by UserId order by sum(HelpNonDirectTradeAmt+NotHelpNonDirectTradeAmt+ProfitNonDirectTradeAmt+HelpNonDirectDebitTradeAmt+ProfitNonDirectDebitTradeAmt) desc");
                                    int index = 0;
                                    decimal TradeAmt = 0;
                                    decimal BigTradeAmt = 0;
                                    foreach(DataRow dr in dt.Rows)
                                    {
                                        index += 1;
                                        if(index == 1)
                                        {
                                            BigTradeAmt = decimal.Parse(dr[1].ToString());
                                        }
                                        else if(index > 1)
                                        {
                                            TradeAmt += decimal.Parse(dr[1].ToString());
                                        }
                                    }
                                    if(TradeAmt < 12000000 || BigTradeAmt < 30000000)
                                    {
                                        if(AfterLevel > BeforeLevel && BeforeLevel >= 5) //保级，只升不降
                                        {
                                            AfterLevel = BeforeLevel;
                                        }
                                        else if(AfterLevel > BeforeLevel && BeforeLevel < 5)
                                        {
                                            AfterLevel = 5;
                                        }
                                        else if(BeforeLevel > 5)
                                        {
                                            AfterLevel = 5;
                                        }
                                        else
                                        {
                                            upFlag = false;
                                        }
                                    }
                                }
                                if (AfterLevel > BeforeLevel && AfterLevel > 1 && upFlag)
                                {
                                    Utils.WriteLog("升级：" + user.Id.ToString() + BeforeLevel + "->" + AfterLevel, "创客升级日志");
                                    user.UserLevel = AfterLevel;
                                    DateTime checkTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM") + "-01 00:00:00");
                                    UserRank rank = db.UserRank.FirstOrDefault(m => m.CreateDate >= checkTime && m.UserId == user.Id);
                                    if(rank == null)
                                    {
                                        db.UserRank.Add(new UserRank()
                                        {
                                            CreateDate = DateTime.Now,
                                            UpdateDate = DateTime.Now,
                                            UserId = user.Id, //创客
                                            WhiteRank = BeforeLevel,
                                            Rank = AfterLevel, //当前等级
                                            StatYear = DateTime.Now.Year, //统计年份
                                            StatMonth = DateTime.Now.Month, //统计月份
                                            TradeAmt = TradeAmount, //团队交易总额
                                            UpgradeFlag = 1, //升级标识
                                            OperateDate = DateTime.Now, //操作时间
                                            Status = 1,
                                        });
                                        db.SaveChanges();
                                    }
                                    else
                                    {
                                        rank.TradeAmt = TradeAmount;
                                        rank.Rank = AfterLevel;
                                        db.SaveChanges();
                                    }
                                }
                                // 降级逻辑
                                if(!upFlag && AfterLevel > 5)
                                {
                                    AfterLevel = 5;
                                }
                                if (AfterLevel < BeforeLevel && BeforeLevel > 1)
                                {
                                    Utils.WriteLog(user.MakerCode + "-" + user.RealName + ":K" + BeforeLevel + "->K" + AfterLevel, "创客降级日志");
                                    user.UserLevel = AfterLevel;
                                    DateTime checkTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM") + "-01 00:00:00");
                                    UserRank rank = db.UserRank.FirstOrDefault(m => m.CreateDate >= checkTime && m.UserId == user.Id);
                                    if(rank == null)
                                    {
                                        db.UserRank.Add(new UserRank()
                                        {
                                            CreateDate = DateTime.Now,
                                            UpdateDate = DateTime.Now,
                                            UserId = user.Id, //创客
                                            WhiteRank = BeforeLevel,
                                            Rank = AfterLevel, //当前等级
                                            StatYear = DateTime.Now.Year, //统计年份
                                            StatMonth = DateTime.Now.Month, //统计月份
                                            TradeAmt = TradeAmount, //团队交易总额
                                            UpgradeFlag = 0, //升级标识
                                            OperateDate = DateTime.Now, //操作时间
                                            Status = 1,
                                        });
                                        db.SaveChanges();
                                    }
                                    else
                                    {
                                        rank.TradeAmt = TradeAmount;
                                        rank.Rank = AfterLevel;
                                        rank.Status = 1;
                                        db.SaveChanges();
                                    }
                                }
                            }
                            startid = subuser.Id;
                        }
                        Utils.WriteLog(startid.ToString(), "创客升级日志");
                    }
                    else
                    {
                        op = false;
                    }
                }
                Utils.WriteLog(DateTime.Now.ToString(), "创客升级日志");
            }
            catch (Exception ex)
            {
                Utils.WriteLog(ex.ToString(), "创客升级异常");
            }
            db.Dispose();
            mpmaindb.Dispose();

            RedisDbconn.Instance.AddList("DoTableEveryMonthQueue", "1");
        }

        public void StatUserLevelStartNew()
        {
            WebCMSEntities db = new WebCMSEntities();
            MpMainModels.WebCMSEntities mpmaindb = new MpMainModels.WebCMSEntities();
            MpMainModels2.WebCMSEntities mpmaindb2 = new MpMainModels2.WebCMSEntities();
            try
            {
                OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["Pxc1SqlConnStr"].ToString();
                Utils.WriteLog(DateTime.Now.ToString(), "创客升级日志");
                DateTime start = DateTime.Parse(DateTime.Now.AddMonths(-1).ToString("yyyy-MM") + "-01 00:00:00");
                DateTime end = start.AddDays(1);
                string TradeMonth = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
                List<UserLevelSet> sets = db.UserLevelSet.ToList();
                bool op = true;
                int startid = 138681;
                while(op)
                {
                    var users = db.Users.Select(m => new { m.Id, m.AuthFlag }).Where(m => m.Id > startid && m.AuthFlag == 1).OrderBy(m => m.Id).Take(500).ToList();
                    Utils.WriteLog(users.Count.ToString(), "创客升级日志");
                    if(users.Count > 0)
                    {
                        foreach (var subuser in users)
                        {
                            Users user = db.Users.FirstOrDefault(m => m.Id == subuser.Id);
                            if (user != null)
                            {
                                int BeforeLevel = user.UserLevel;
                                int AfterLevel = 0;
                                decimal TradeAmount = 0;
                                //创客团队交易额
                                bool check = db.TradeDaySummary.Any(m => m.UserId == user.Id && m.TradeMonth == TradeMonth && m.SeoTitle == "team");
                                if (check)
                                {
                                    TradeAmount += db.TradeDaySummary.Where(m => m.UserId == user.Id && m.TradeMonth == TradeMonth && m.SeoTitle == "team").Sum(m => m.HelpNonDirectTradeAmt + m.HelpNonDirectDebitTradeAmt + m.NotHelpNonDirectTradeAmt + m.NotHelpNonDirectDebitTradeAmt + m.ProfitNonDirectTradeAmt + m.ProfitNonDirectDebitTradeAmt);
                                }
                                //助利宝团队交易额
                                DataTable checkdt = OtherMySqlConn.dtable("SELECT SUM(TradeAmount) TradeAmount FROM HelpProfitMerTradeSummay WHERE (MerchantId IN(SELECT MerchantId FROM HelpProfitMerIds WHERE UserId IN(SELECT Id from Users WHERE ParentNav like '%," + user.Id + ",%' OR Id=" + user.Id + "))) AND TradeMonth=" + TradeMonth + "");
                                if (checkdt.Rows.Count > 0)
                                {
                                    TradeAmount += decimal.Parse(function.CheckNum(checkdt.Rows[0]["TradeAmount"].ToString()));
                                }
                                //码牌团队交易额（直联）
                                check = mpmaindb.UserAmountSummary.Any(m => m.UserId == user.Id && m.TradeMonth == TradeMonth && m.SeoTitle == "team");
                                if (check)
                                {
                                    TradeAmount += mpmaindb.UserAmountSummary.Where(m => m.UserId == user.Id && m.TradeMonth == TradeMonth && m.SeoTitle == "team" && m.IsAct == 1).Sum(m => m.TotalAmount) * 4;
                                }
                                //码牌团队交易额（银联）
                                check = mpmaindb2.UserAmountSummary.Any(m => m.UserId == user.Id && m.TradeMonth == TradeMonth && m.SeoTitle == "team");
                                if (check)
                                {
                                    TradeAmount += mpmaindb2.UserAmountSummary.Where(m => m.UserId == user.Id && m.TradeMonth == TradeMonth && m.SeoTitle == "team" && m.IsAct == 1).Sum(m => m.TotalAmount) * 4;
                                }
                                //广电卡扶持期按1万/张计入职级
                                check = db.UserTradeMonthSummary.Any(m => m.UserId == user.Id && m.TradeMonth == TradeMonth && m.SeoTitle == "team" && m.BrandId == 14);
                                if (check)
                                {
                                    TradeAmount += db.UserTradeMonthSummary.Where(m => m.UserId == user.Id && m.TradeMonth == TradeMonth && m.SeoTitle == "team" && m.BrandId == 14).Sum(m => m.ActiveBuddyMerStatus) * 10000;
                                }
                                UserLevelSet set = sets.FirstOrDefault(m => m.UpLevelGrowth <= TradeAmount && m.UpLevelIntegral > TradeAmount);
                                if (set != null)
                                {
                                    AfterLevel = set.Id;
                                }

                                // K6以上计算小市场是否达标
                                // 升级逻辑
                                bool upFlag = true;
                                if(AfterLevel > 5)
                                {
                                    DataTable dt = OtherMySqlConn.dtable("select UserId,sum(HelpNonDirectTradeAmt+NotHelpNonDirectTradeAmt+ProfitNonDirectTradeAmt+HelpNonDirectDebitTradeAmt+NotHelpNonDirectDebitTradeAmt+ProfitNonDirectDebitTradeAmt) from TradeDaySummary where UserId in (select Id from Users where ParentUserId=" + user.Id + ") and TradeMonth='" + TradeMonth + "' and SeoTitle='team' group by UserId order by sum(HelpNonDirectTradeAmt+NotHelpNonDirectTradeAmt+ProfitNonDirectTradeAmt+HelpNonDirectDebitTradeAmt+ProfitNonDirectDebitTradeAmt) desc");
                                    int index = 0;
                                    decimal TradeAmt = 0;
                                    decimal BigTradeAmt = 0;
                                    foreach(DataRow dr in dt.Rows)
                                    {
                                        index += 1;
                                        if(index == 1)
                                        {
                                            BigTradeAmt = decimal.Parse(dr[1].ToString());
                                        }
                                        else if(index > 1)
                                        {
                                            TradeAmt += decimal.Parse(dr[1].ToString());
                                        }
                                    }
                                    if(TradeAmt < 12000000 || BigTradeAmt < 30000000)
                                    {
                                        if(AfterLevel > BeforeLevel && BeforeLevel >= 5) //保级，只升不降
                                        {
                                            AfterLevel = BeforeLevel;
                                        }
                                        else if(AfterLevel > BeforeLevel && BeforeLevel < 5)
                                        {
                                            AfterLevel = 5;
                                        }
                                        else if(BeforeLevel > 5)
                                        {
                                            AfterLevel = 5;
                                        }
                                        else
                                        {
                                            upFlag = false;
                                        }
                                    }
                                }
                                if (AfterLevel > BeforeLevel && AfterLevel > 0 && upFlag)
                                {
                                    Utils.WriteLog("升级：" + user.Id.ToString() + BeforeLevel + "->" + AfterLevel, "创客升级日志");
                                    user.UserLevel = AfterLevel;
                                    DateTime checkTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM") + "-01 00:00:00");
                                    UserRank rank = db.UserRank.FirstOrDefault(m => m.CreateDate >= checkTime && m.UserId == user.Id);
                                    if(rank == null)
                                    {
                                        db.UserRank.Add(new UserRank()
                                        {
                                            CreateDate = DateTime.Now,
                                            UpdateDate = DateTime.Now,
                                            UserId = user.Id, //创客
                                            WhiteRank = BeforeLevel,
                                            Rank = AfterLevel, //当前等级
                                            StatYear = DateTime.Now.Year, //统计年份
                                            StatMonth = DateTime.Now.Month, //统计月份
                                            TradeAmt = TradeAmount, //团队交易总额
                                            UpgradeFlag = 1, //升级标识
                                            OperateDate = DateTime.Now, //操作时间
                                            Status = 1,
                                        });
                                        db.SaveChanges();
                                    }
                                    else
                                    {
                                        rank.TradeAmt = TradeAmount;
                                        rank.Rank = AfterLevel;
                                        db.SaveChanges();
                                    }
                                    UserRankWhite rankWhite = db.UserRankWhite.FirstOrDefault(m => m.Id == user.Id);
                                    if(rankWhite != null)
                                    {
                                        if(Utils.Instance.GetUserLevel(user.Id) >= rankWhite.Rank)
                                        {
                                            user.Version = 0;
                                            db.SaveChanges();
                                        }
                                    }
                                }
                                // 降级逻辑
                                if(!upFlag && AfterLevel > 5)
                                {
                                    AfterLevel = 5;
                                }
                                // 如果是达标创客，只能降级到K1
                                if(AfterLevel == 0 && Utils.Instance.IsStandardUser(user.Id))
                                {
                                    AfterLevel = 1;
                                }
                                if (AfterLevel < BeforeLevel && BeforeLevel > 0)
                                {
                                    Utils.WriteLog(user.MakerCode + "-" + user.RealName + ":K" + BeforeLevel + "->K" + AfterLevel, "创客降级日志");
                                    user.UserLevel = AfterLevel;
                                    DateTime checkTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM") + "-01 00:00:00");
                                    UserRank rank = db.UserRank.FirstOrDefault(m => m.CreateDate >= checkTime && m.UserId == user.Id);
                                    if(rank == null)
                                    {
                                        db.UserRank.Add(new UserRank()
                                        {
                                            CreateDate = DateTime.Now,
                                            UpdateDate = DateTime.Now,
                                            UserId = user.Id, //创客
                                            WhiteRank = BeforeLevel,
                                            Rank = AfterLevel, //当前等级
                                            StatYear = DateTime.Now.Year, //统计年份
                                            StatMonth = DateTime.Now.Month, //统计月份
                                            TradeAmt = TradeAmount, //团队交易总额
                                            UpgradeFlag = 0, //升级标识
                                            OperateDate = DateTime.Now, //操作时间
                                            Status = 1,
                                        });
                                        db.SaveChanges();
                                    }
                                    else
                                    {
                                        rank.TradeAmt = TradeAmount;
                                        rank.Rank = AfterLevel;
                                        rank.Status = 1;
                                        db.SaveChanges();
                                    }
                                    UserRankWhite rankWhite = db.UserRankWhite.FirstOrDefault(m => m.Id == user.Id);
                                    if(rankWhite != null)
                                    {
                                        if(Utils.Instance.GetUserLevel(user.Id) < rankWhite.Rank)
                                        {
                                            user.Version = 3;
                                            db.SaveChanges();
                                        }
                                    }
                                }
                            }
                            startid = subuser.Id;
                        }
                        Utils.WriteLog(startid.ToString(), "创客升级日志");
                    }
                    else
                    {
                        op = false;
                    }
                }
                //查找K0创客，如果商城下单购买一组机具券，则预设为K1
                List<int> productIds = new List<int>();
                productIds.Add(10);
                productIds.Add(11);
                op = true;
                startid = 0;
                while(op)
                {
                    var users = db.Users.Select(m => new { m.Id, m.AuthFlag, m.UserLevel }).Where(m => m.Id > startid && m.AuthFlag == 1 && m.UserLevel == 0).OrderBy(m => m.Id).Take(50).ToList();
                    if(users.Count > 0)
                    {
                        foreach (var subuser in users)
                        {
                            bool hasOrder = db.Orders.Any(m => m.UserId == subuser.Id && m.Status > 0 && productIds.Contains(m.ProductId));
                            if(hasOrder)
                            {
                                Utils.Instance.LeaderPreUserLevel(subuser.Id, 1, DateTime.Parse("2025-01-01 00:00:00"));
                                db.UserRank.Add(new UserRank()
                                {
                                    CreateDate = DateTime.Now,
                                    UpdateDate = DateTime.Now,
                                    UserId = subuser.Id, //创客
                                    WhiteRank = 0,
                                    Rank = 1, //当前等级
                                    StatYear = DateTime.Now.Year, //统计年份
                                    StatMonth = DateTime.Now.Month, //统计月份
                                    TradeAmt = 0, //团队交易总额
                                    UpgradeFlag = 1, //升级标识
                                    OperateDate = DateTime.Now, //操作时间
                                    Status = 1,
                                });
                                Users user = db.Users.FirstOrDefault(m => m.Id == subuser.Id);
                                if(user != null)
                                {
                                    user.Version = 3;
                                }
                                db.SaveChanges();
                            }
                        }
                    }
                    else
                    {
                        op = false;
                    }
                }
                Utils.WriteLog(DateTime.Now.ToString(), "创客升级日志");
            }
            catch (Exception ex)
            {
                Utils.WriteLog(ex.ToString(), "创客升级异常");
            }
            db.Dispose();
            mpmaindb.Dispose();
            mpmaindb2.Dispose();

            RedisDbconn.Instance.AddList("DoTableEveryMonthQueue", "1");
        }


        // 统计创客激活数
        public void StartPosActNum()
        {
            Thread th = new Thread(StartPosActNumFor);
            th.IsBackground = true;
            th.Start();
        }
        public void StartPosActNumFor()
        {
            // DateTime end = DateTime.Parse("2022-06-15 00:00:00");
            // DateTime check = DateTime.Parse("2022-06-14");
            // while (check <= end)
            // {
            //     StartPosActNumDo(check.ToString("yyyy-MM-dd"));
            //     check = check.AddDays(1);
            // }
            while (true)
            {
                if(DateTime.Now.Hour >= 2)
                {
                    StartPosActNumEverTime();
                }
                Thread.Sleep(100);
            }
        }
        public void StartPosActNumDo(object sender)
        {
            string date = sender.ToString();
            Utils.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 + "')");
                Utils.WriteLog("人数:" + userDt.Rows.Count + "\n\n", "执行创客激活数日志");
                foreach (DataRow userDr in userDt.Rows)
                {
                    int UserId = int.Parse(userDr["Id"].ToString());
                    string ParentNav = userDr["ParentNav"].ToString();
                    Utils.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");
                    Utils.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);
                                Utils.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");
                                Utils.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)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "执行创客激活数异常");
            }
            db.Dispose();
            Utils.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行创客激活数日志");
            Thread.Sleep(60000);
        }
        public void StartPosActNumEverTime()
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["Pxc1SqlConnStr"].ToString();
            Utils.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 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,BrandId,DATE_FORMAT(ActivationTime, '%Y%m%d'),count(Id) from PosMachinesTwo where Id in (" + ids.TrimEnd(',') + ") group by BuyUserId,BrandId,DATE_FORMAT(ActivationTime, '%Y%m%d')");
                    if (userDt.Rows.Count > 0)
                    {
                        Utils.WriteLog("人数:" + userDt.Rows.Count + "\n\n", "实时执行创客激活数日志");
                        foreach (DataRow userDr in userDt.Rows)
                        {
                            int UserId = int.Parse(userDr["BuyUserId"].ToString());
                            int BrandId = int.Parse(userDr["BrandId"].ToString());
                            string TradeDate = userDr[2].ToString();
                            int ActCount = int.Parse(function.CheckInt(userDr[3].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;
                            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;
                            ParentNav += "," + UserId + ",";
                            if (!string.IsNullOrEmpty(ParentNav))
                            {
                                string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                                foreach (string NavUserIdString in ParentNavList)
                                {
                                    int NavUserId = int.Parse(NavUserIdString);
                                    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 Id in (" + ids.TrimEnd(',') + ")");
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "实时执行创客激活数异常");
            }
            db.Dispose();
            Utils.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()
        {
            // DateTime end = DateTime.Parse("2022-06-15 00:00:00");
            // DateTime check = DateTime.Parse("2022-06-14");
            // while (check <= end)
            // {
            //     StartNewUserNumDo(check.ToString("yyyy-MM-dd"));
            //     check = check.AddDays(1);
            // }
            while (true)
            {
                if(DateTime.Now.Hour >= 2)
                {
                    StartNewUserNumEverTime();
                }
                Thread.Sleep(120000);
            }
        }
        public void StartNewUserNumDo(object sender)
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["Pxc1SqlConnStr"].ToString();
            string date = sender.ToString();
            Utils.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 + "'");
                Utils.WriteLog("人数:" + userDt.Rows.Count + "\n\n", "执行新增创客数日志");
                foreach (DataRow userDr in userDt.Rows)
                {
                    int UserId = int.Parse(userDr["Id"].ToString());
                    string ParentNav = userDr["ParentNav"].ToString();
                    Utils.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 + "");
                    Utils.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);
                                Utils.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 + ",%'");
                                Utils.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)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "执行新增创客数异常");
            }
            db.Dispose();
            Utils.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行新增创客数日志");
            Thread.Sleep(60000);
        }
        public void StartNewUserNumEverTime()
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["Pxc1SqlConnStr"].ToString();
            Utils.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)
                    {
                        Utils.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)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "实时执行新增创客数异常");
            }
            db.Dispose();
            Utils.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()
        {
            // DateTime end = DateTime.Parse("2022-06-16 00:00:00");
            // DateTime check = DateTime.Parse("2022-06-16");
            // while (check <= end)
            // {
            //     StatProfitEverDay(check.ToString("yyyy-MM-dd"));
            //     Thread.Sleep(1000);
            //     check = check.AddDays(1);
            // }
            while (true)
            {
                if(DateTime.Now.Hour >= 2)
                {
                    StatProfitEverDayEverTime();
                }
                Thread.Sleep(120000);
            }
        }
        public void StatProfitEverDay(object sender)
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["Pxc1SqlConnStr"].ToString();
            string date = sender.ToString();
            Utils.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();
                }
                Utils.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 + "')");
                Utils.WriteLog("交易人数:" + userDt.Rows.Count + "\n\n", "执行昨天收益日志");
                foreach (DataRow userDr in userDt.Rows)
                {
                    int UserId = int.Parse(userDr["Id"].ToString());
                    string ParentNav = userDr["ParentNav"].ToString();
                    Utils.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");
                    Utils.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);
                                Utils.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");
                                Utils.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)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "统计昨天收益异常");
            }
            db.Dispose();
            Utils.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行昨天收益日志");
        }

        public void StatProfitEverDayEverTime()
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["Pxc1SqlConnStr"].ToString();
            Utils.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)
                    {
                        Utils.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)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "实时统计收益异常");
            }
            db.Dispose();
            Utils.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "实时统计收益日志");
        }


        
        //押金奖励发放
        public void StartPreActPrize()
        {
            Thread th = new Thread(StartPreActPrizeDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StartPreActPrizeDo()
        {
            while(true)
            {
                string content = RedisDbconn.Instance.RPop<string>("DepositActPrizeQueue");
                if(!string.IsNullOrEmpty(content))
                {
                    try
                    {
                        int PosId = int.Parse(content);
                        WebCMSEntities db = new WebCMSEntities();
                        PxcModels.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == PosId) ?? new PxcModels.PosMachinesTwo();
                        PxcModels.PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId) ?? new PxcModels.PosMerchantInfo();
                        PreActPrize(db, pos, merchant, pos.SeoKeyword);
                        db.Dispose();
                    }
                    catch(Exception ex)
                    {
                        Utils.WriteLog(DateTime.Now.ToString() + "\nPosId：" + content + "\n" + ex.ToString(), "押金奖励发放异常");
                    }
                }
                else
                {
                    Thread.Sleep(10000);
                }
            }
        }
        public void PreActPrize(WebCMSEntities db, PosMachinesTwo pos, PosMerchantInfo merchant, string Deposit)
        {
            if(Utils.Instance.IsHaoDa(pos.BrandId))
            {
                return;
            }
            if(Utils.Instance.IsWifi(pos.BrandId))
            {
                return;
            }
            Utils.WriteLog(DateTime.Now.ToString() + "\n" + pos.PosSn, "服务费奖励发放日志");
            decimal DepositNumber = decimal.Parse(function.CheckNum(Deposit));
            Utils.WriteLog("DepositNumber:" + DepositNumber, "服务费奖励发放日志");
            Utils.WriteLog("BuyUserId:" + pos.BuyUserId, "服务费奖励发放日志");
            if(DepositNumber > 0 && pos.BuyUserId > 0)
            {
                Utils.WriteLog("满足条件", "服务费奖励发放日志");
                decimal ActPrize = 0;
                if(DepositNumber > 1000)
                {
                    DepositNumber = DepositNumber / 100;
                }
                if(DepositNumber == 199) ActPrize = 100;
                if(DepositNumber == 299) ActPrize = 200;
                if(DepositNumber == 249) ActPrize = 160;
                Utils.WriteLog("ActPrize:" + ActPrize, "服务费奖励发放日志");
                if(ActPrize > 0)
                {
                    Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId) ?? new Users();
                    int GetUserId = user.Id;
                    string ParentNav = user.ParentNav;
                    int TopUserId = 0;
                    if (!string.IsNullOrEmpty(ParentNav))
                    {
                        TopUserId = int.Parse(ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                    }
                    Utils.WriteLog("发放给:" + GetUserId, "服务费奖励发放日志");
                    if((pos.BrandId == 12 || pos.BrandId == 13) && string.IsNullOrEmpty(merchant.KqMerNo))
                    {
                        if(!db.ActiveReward.Any(m => m.KqSnNo == pos.PosSn && m.ActType == 1))
                        {
                            doActiveRewardFunc(db, merchant, pos, GetUserId, user.ParentNav, TopUserId, ActPrize, 0, 1);
                        }
                    }
                    else
                    {
                        doActiveReward(db, merchant, pos, GetUserId, user.ParentNav, TopUserId, ActPrize, 0, 1);
                    }
                    Utils.WriteLog("已发放", "服务费奖励发放日志");
                }
            }
            Utils.WriteLog("\n\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

        #region 开机奖励

        public void PostOpenReward(WebCMSEntities db, PosMachinesTwo pos, PosMerchantInfo merchant, UserRankItem puser, decimal Prize)
        {
            Users machineUser = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId) ?? new Users();
            OpenRewardDetail detail = db.OpenRewardDetail.Add(new OpenRewardDetail()
            {
                CreateDate = DateTime.Now,
                UpdateDate = DateTime.Now,
                TradeMonth = DateTime.Now.ToString("yyyyMM"), //交易月
                TradeDate = DateTime.Now, //达标日期
                UserId = puser.Id, //创客
                BrandId = pos.BrandId, //品牌
                ProductName = RelationClass.GetKqProductsInfo(pos.BrandId), //产品名称
                MerchantId = pos.BindMerchantId, //商户
                DirectUserId = merchant.UserId, //商户直属人
                SnNo = pos.PosSn, //SN号
                MerNo = merchant.KqMerNo, //渠道商户号
                SnType = pos.PosSnType, //机具类型
                StandardDate = pos.ActivationTime, //商户的激活日期
                SnStoreId = pos.StoreId, //SN仓库
                MerBuddyType = puser.MerchantType, //商户创客类型
                RewardType = 1, //奖励类型 1-开机直接奖励，2-开机间接奖励
                RewardTips = "开机奖励", //奖励描述
                CreditTradeAmt = pos.CreditTrade, //贷记卡交易总金额
                DebitTradeAmt = pos.DebitCardTrade, //借记卡交易总金额
                CreditRewardAmount = Prize, //贷记卡交易奖励金额
                RewardDesc = "开机奖励", //奖励描述
                SeoTitle = machineUser.RealName,
            }).Entity;
            db.OpenReward.Add(new OpenReward()
            {
                CreateDate = DateTime.Now,
                UpdateDate = DateTime.Now,
                TradeMonth = DateTime.Now.ToString("yyyyMM"), //交易月
                TradeDate = DateTime.Now, //达标日期
                UserId = puser.Id, //创客
                BrandId = pos.BrandId, //品牌
                RewardType = 2, //奖励类型
                CreditTradeAmt = pos.CreditTrade, //贷记卡交易总金额
                DebitTradeAmt = pos.DebitCardTrade, //借记卡交易总金额
                CreditRewardAmount = Prize, //贷记卡交易奖励金额
                RewardDesc = "开机奖励", //奖励描述
            });
            string IdBrand = puser.Id + "_" + pos.BrandId;
            UserMachineData userData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
            if (userData == null)
            {
                userData = db.UserMachineData.Add(new UserMachineData()
                {
                    IdBrand = IdBrand,
                }).Entity;
                db.SaveChanges();
            }
            userData.OpenProfit += Prize;
            db.SaveChanges();
            //账户入库
            UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == puser.Id);
            if (account == null)
            {
                account = db.UserAccount.Add(new UserAccount()
                {
                    Id = puser.Id,
                    UserId = puser.Id,
                }).Entity;
                db.SaveChanges();
            }
            //收支明细入库
            decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
            decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
            decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
            account.BalanceAmount += Prize;
            account.TotalAmount += Prize;
            decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
            decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
            decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
            UserAccountRecord userAccountRecord = db.UserAccountRecord.Add(new UserAccountRecord()
            {
                CreateDate = DateTime.Now,
                UpdateDate = DateTime.Now,
                UserId = puser.Id, //创客
                ChangeType = 50, //变动类型
                ProductType = pos.BrandId, //产品类型
                ChangeAmount = Prize, //变更金额
                BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                AfterTotalAmount = AfterTotalAmount, //变更后总金额
                BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                QueryCount = pos.Id,
                Kind = 3,
            }).Entity;
            db.SaveChanges();

            //发送APP推送消息
            Utils.Instance.PrizePush(puser.Id, Prize);
        }

        #endregion

    }
}