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

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

        public void Start(JobMqMsg jobInfo)
        {
            string content = "";
            try
            {
                if(DateTime.Now.Hour > 0)
                {
                    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"));
                        // dosomething1(doDate);
                        // dosomething11(doDate);
                        // dosomething2(doDate);
                        StartEverDay(doDate);
                        // StartEverDayV2(doDate);
                        StatMerchantTrade(doDate);
                        // dosomething4(doDate);
                        // ListenFluxRecord(doDate);
                    }
                    // string Msg = "success";
                    // jobInfo.Status = Msg == "success" ? 1 : 0;
                    // jobInfo.Msg = Msg == "success" ? "执行完成" : Msg;
                    // RabbitMQClient.Instance.SendMsg(Newtonsoft.Json.JsonConvert.SerializeObject(jobInfo), "PublicBack");
                }
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrEmpty(content))
                {
                    Dictionary<string, string> data = new Dictionary<string, string>();
                    data.Add("ErrTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    data.Add("ErrMsg", ex.ToString());
                    LogHelper.Instance.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(data), "public_err");
                }
                else
                {
                    LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "public_service");
                }
            }
        }

        public void ActiveReward(JobMqMsg jobInfo)
        {
            string content = "";
            try
            {
                dosomething3();
                activePrizeWithoutDeposit();
                // string Msg = "success";
                // jobInfo.Status = Msg == "success" ? 1 : 0;
                // jobInfo.Msg = Msg == "success" ? "执行完成" : Msg;
                // RabbitMQClient.Instance.SendMsg(Newtonsoft.Json.JsonConvert.SerializeObject(jobInfo), "PublicBack");
                // function.WritePage("/static/", "act.txt", DateTime.Now.ToString());
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrEmpty(content))
                {
                    Dictionary<string, string> data = new Dictionary<string, string>();
                    data.Add("ErrTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    data.Add("ErrMsg", ex.ToString());
                    LogHelper.Instance.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(data), "public_err");
                }
                else
                {
                    LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "public_service");
                }
            }
        }











        public void clear()
        {
            RedisDbconn.Instance.Clear("TotalAmount*");
            RedisDbconn.Instance.Clear("TotalCloudPayAmount*");
            RedisDbconn.Instance.Clear("TotalPosAmount*");
            RedisDbconn.Instance.Clear("TeamTotalAmount*");
            RedisDbconn.Instance.Clear("TeamTotalCloudPayAmount*");
            RedisDbconn.Instance.Clear("TeamTotalPosAmount*");

            // RedisDbconn.Instance.Clear("TotalUser*");
            // RedisDbconn.Instance.Clear("TeamTotalUser*");
            // RedisDbconn.Instance.Clear("AddUser*");
            // RedisDbconn.Instance.Clear("TeamAddUser*");

            // RedisDbconn.Instance.Clear("TotalPosMerchant*");
            // RedisDbconn.Instance.Clear("TeamTotalPosMerchant*");

            RedisDbconn.Instance.Clear("MerTotalAmount*");
        }


        // 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;
                }
                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)
                    {
                        MachineForSnNo forSnNo = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == bind.MerSnNo) ?? new MachineForSnNo();
                        PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == forSnNo.SnId && m.UserId != user.Id);
                        if (pos != null)
                        {
                            pos.UserId = user.Id;
                            user.MerchantType = 1;
                            PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.KqMerNo == MerNo) ?? new 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)
        {
            WebCMSEntities db = new WebCMSEntities();
            DateTime yesterday = DateTime.Now.AddDays(-1);
            DateTime today = DateTime.Now;
            IQueryable<PosMachinesTwo> posList = db.PosMachinesTwo.Where(m => m.ActivationState == 1 && !string.IsNullOrEmpty(m.SeoKeyword));
            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 && !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 && pos.ActivationTime.Value <= pos.BindingTime.Value.AddDays(30))
                {
                    // PosMerchantOtherInfo otherInfo = db.PosMerchantOtherInfo.FirstOrDefault(m => m.CertId == merchant.MerIdcardNo && m.PrizeFlag1 == 0);
                    // if (otherInfo != null)
                    // {
                    //     otherInfo.PrizeFlag1 = 1;
                    //     db.SaveChanges();
                    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));
                        if (pos.BrandId == 1 || pos.BrandId == 3 || pos.BrandId == 4 || pos.BrandId == 5 || pos.BrandId == 6 || pos.BrandId == 8 || pos.BrandId == 9)
                        {
                            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;
                            }
                            if (GetUserId > 0)
                            {
                                doActiveReward(db, merchant, pos, GetUserId, ParentNav, TopUserId, ActPrize);
                                doJk30(db, pos, merchant, GetUserId, ParentNav, TopUserId);
                            }
                        }
                        else if(ActPrize == 0)
                        {
                            if(pos.BrandId == 6)
                            {
                                doActiveReward(db, merchant, pos, GetUserId, ParentNav, TopUserId, 50);
                            }
                        }
                    }
                    // }
                }
            }
            db.Dispose();
        }
        //金控活动机返奖励
        private void doJk30(WebCMSEntities db, PosMachinesTwo pos, PosMerchantInfo merchant, int GetUserId, string ParentNav, int TopUserId)
        {
            DateTime check = DateTime.Parse("2022-06-01 00:00:00");
            if((pos.BrandId == 1 || pos.BrandId == 3) && pos.CreateDate < check)
            {
                decimal amt = 0;
                if(DateTime.Now > DateTime.Parse("2022-10-01 00:00:00") && DateTime.Now < DateTime.Parse("2022-11-01 00:00:00"))
                {
                    amt = 30;
                }
                else if(DateTime.Now > DateTime.Parse("2022-11-01 00:00:00") && DateTime.Now < DateTime.Parse("2022-12-01 00:00:00"))
                {
                    amt = 20;
                }
                else if(DateTime.Now > DateTime.Parse("2022-12-01 00:00:00") && DateTime.Now < DateTime.Parse("2023-04-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(-1);
            DateTime today = DateTime.Now.AddMinutes(-5);
            IQueryable<PosMachinesTwo> posList = db.PosMachinesTwo.Where(m => m.ActivationState == 1 && string.IsNullOrEmpty(m.SeoKeyword));
            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]);
                        }
                        if(pos.BrandId == 6) //首台无押金机返50
                        {
                            doActiveReward(db, merchant, pos, GetUserId, ParentNav, TopUserId, 50);
                        }
                        else if((pos.BrandId == 10 || pos.BrandId == 11) && pos.IsFirst == 1) //首台无押金机返50
                        {
                            doActiveReward(db, merchant, pos, GetUserId, ParentNav, TopUserId, 50);
                        }
                        else
                        {
                            //金控活动机返奖励
                            doJk30(db, pos, merchant, GetUserId, ParentNav, TopUserId);
                        }
                    }
                }
            }
            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)
        {
            bool check = db.ActiveReward.Any(m => m.KqMerNo == merchant.KqMerNo && m.RewardAmount == ActPrize);
            bool check1 = db.ActiveReward.Any(m => m.KqSnNo == pos.PosSn && m.RewardAmount == ActPrize);
            if (!check && !check1)
            {
                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, //变更后余额
                }).Entity;
                db.SaveChanges();

                string dateString = pos.ActivationTime.Value.ToString("yyyyMMdd");
                string monthString = pos.ActivationTime.Value.ToString("yyyyMM");
                // 激活奖励列表
                List<string> dates = RedisDbconn.Instance.GetList<string>("ActiveRewardDay:" + GetUserId + ":" + pos.BrandId);
                if (!dates.Contains(dateString))
                {
                    RedisDbconn.Instance.AddList("ActiveRewardDay:" + GetUserId + ":" + pos.BrandId, dateString);
                }
                RedisDbconn.Instance.AddNumber("ActiveRewardAmt:" + GetUserId + ":" + pos.BrandId + ":" + dateString, ActPrize);

                List<string> months = RedisDbconn.Instance.GetList<string>("ActiveRewardMonth:" + GetUserId + ":" + pos.BrandId);
                if (!months.Contains(monthString))
                {
                    RedisDbconn.Instance.AddList("ActiveRewardMonth:" + GetUserId + ":" + pos.BrandId, monthString);
                }
                RedisDbconn.Instance.AddNumber("ActiveRewardAmt:" + GetUserId + ":" + pos.BrandId + ":" + monthString, ActPrize);

                // 激活奖励详情
                List<int> actPrizeList = RedisDbconn.Instance.GetList<int>("ActiveRewardDetail:" + GetUserId + ":" + pos.BrandId + ":" + dateString);
                if (!actPrizeList.Contains(pos.BindMerchantId))
                {
                    RedisDbconn.Instance.AddList("ActiveRewardDetail:" + GetUserId + ":" + pos.BrandId + ":" + dateString, pos.BindMerchantId);
                }
                RedisDbconn.Instance.AddNumber("ActiveRewardAmt:mer:" + pos.BindMerchantId + ":" + pos.BrandId + ":" + dateString, ActPrize);

                //收支明细
                RedisDbconn.Instance.Clear("UserAccount:Income:" + GetUserId + ":" + monthString);
            }
        }


        //根据商户信息发放激活奖励
        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));
                    if (pos.BrandId == 1 || pos.BrandId == 3 || pos.BrandId == 4 || pos.BrandId == 5 || pos.BrandId == 6 || pos.BrandId == 8 || pos.BrandId == 9)
                    {
                        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();

                            string dateString = pos.ActivationTime.Value.ToString("yyyyMMdd");
                            string monthString = pos.ActivationTime.Value.ToString("yyyyMM");
                            // 激活奖励列表
                            List<string> dates = RedisDbconn.Instance.GetList<string>("ActiveRewardDay:" + GetUserId + ":" + pos.BrandId);
                            if (!dates.Contains(dateString))
                            {
                                RedisDbconn.Instance.AddList("ActiveRewardDay:" + GetUserId + ":" + pos.BrandId, dateString);
                            }
                            RedisDbconn.Instance.AddNumber("ActiveRewardAmt:" + GetUserId + ":" + pos.BrandId + ":" + dateString, ActPrize);

                            List<string> months = RedisDbconn.Instance.GetList<string>("ActiveRewardMonth:" + GetUserId + ":" + pos.BrandId);
                            if (!months.Contains(monthString))
                            {
                                RedisDbconn.Instance.AddList("ActiveRewardMonth:" + GetUserId + ":" + pos.BrandId, monthString);
                            }
                            RedisDbconn.Instance.AddNumber("ActiveRewardAmt:" + GetUserId + ":" + pos.BrandId + ":" + monthString, ActPrize);

                            // 激活奖励详情
                            List<int> actPrizeList = RedisDbconn.Instance.GetList<int>("ActiveRewardDetail:" + GetUserId + ":" + pos.BrandId + ":" + dateString);
                            if (!actPrizeList.Contains(pos.BindMerchantId))
                            {
                                RedisDbconn.Instance.AddList("ActiveRewardDetail:" + GetUserId + ":" + pos.BrandId + ":" + dateString, pos.BindMerchantId);
                            }
                            RedisDbconn.Instance.AddNumber("ActiveRewardAmt:mer:" + pos.BindMerchantId + ":" + pos.BrandId + ":" + dateString, ActPrize);
                        }
                    }
                }
                // }
            }
            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();

                                                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 = 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
                    {
                        int PosId = int.Parse(content);
                        WebCMSEntities db = new WebCMSEntities();
                        List<PosMachinesTwo> posList = db.PosMachinesTwo.Where(m => m.Id == PosId && m.ActivationState == 1 && !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);
                                    if (merchant != null)
                                    {
                                        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 = 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 = "开机奖励", //奖励描述
                                                                TopUserId = pTopUserId, //顶级创客
                                                                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 = "开机奖励", //奖励描述
                                                                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 = DateTime.Now.ToString("yyyyMMdd");
                                                            string monthString = DateTime.Now.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 = 0;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        // }
                                    }
                                }
                            }
                        }
                        db.Dispose();
                    }
                    catch(Exception ex)
                    {
                        LogHelper.Instance.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()
        {
            LogHelper.Instance.WriteLog(DateTime.Now.ToString(), "执行流量费返佣");
            SpModels.WebCMSEntities spdb = new SpModels.WebCMSEntities();
            WebCMSEntities db = new WebCMSEntities();
            DateTime start = DateTime.Now.AddDays(-2);
            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; //流量费
                    if (trade.ProductType == "1" || trade.ProductType == "4" || trade.ProductType == "6" || trade.ProductType == "8" || trade.ProductType == "9")
                    {
                        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;
                    }
                    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)
                {
                    LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n$" + trade.Id + "$\n" + ex.ToString(), "流量卡分佣异常");
                }
            }
            spdb.Dispose();
            db.Dispose();
            LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n", "执行流量费返佣");
        }
        public void CheckFluxForTrade()
        {
            LogHelper.Instance.WriteLog(DateTime.Now.ToString(), "扫描交易记录中的流量费");
            SpModels.WebCMSEntities spdb = new SpModels.WebCMSEntities();
            DateTime start = DateTime.Now.AddDays(-1);
            int StartId = int.Parse(function.CheckInt(function.ReadInstance("/SycnSp/TradeRecordId.txt")));
            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 && (m.ProductType == "1" || m.ProductType == "10")).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") //联动
                        {
                            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)
                {
                    LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n$" + sub.Id + "$\n" + ex.ToString(), "扫描交易记录中的流量费异常");
                }
            }
            spdb.Dispose();
            LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n", "扫描交易记录中的流量费");

            doFluxRecord();
        }






        // 每天统计头一天的交易额
        public void StartEverDay(string date)
        {
            string TradeMonth = DateTime.Now.ToString("yyyyMM");
            if(DateTime.Now.Day == 1)
            {
                TradeMonth = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            }
            else if(DateTime.Now.Day == 2)
            {
                OtherMySqlConn.op("update Users set ThisMonthTrade=0 where ThisMonthTrade>0");
            }
            DataTable list = OtherMySqlConn.dtable("select UserId,sum(HelpNonDirectTradeAmt+HelpNonDirectDebitTradeAmt+NotHelpNonDirectTradeAmt+NotHelpNonDirectDebitTradeAmt+ProfitNonDirectTradeAmt+ProfitNonDirectDebitTradeAmt) from (select UserId,HelpNonDirectTradeAmt,HelpNonDirectDebitTradeAmt,NotHelpNonDirectTradeAmt,NotHelpNonDirectDebitTradeAmt,ProfitNonDirectTradeAmt,ProfitNonDirectDebitTradeAmt from TradeDaySummary where Id>=3348887 and TradeMonth='" + TradeMonth + "' and SeoTitle='team' and UserId>0) tb group by UserId");
            foreach (DataRow dr in list.Rows)
            {
                string UserId = dr["UserId"].ToString();
                string ThisMonthTrade = dr[1].ToString();
                OtherMySqlConn.op("update Users set ThisMonthTrade=" + ThisMonthTrade + " where Id=" + UserId);
            }
            // Thread th = new Thread(StatTradeAmountEverDay);
            // th.IsBackground = true;
            // th.Start(date);
        }
        public void StatTradeAmountEverDay(object sender)
        {
            string date = sender.ToString();
            LogHelper.Instance.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();
                }
                LogHelper.Instance.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 + "')");
                LogHelper.Instance.WriteLog("交易人数:" + userDt.Rows.Count + "\n\n", "执行昨天交易额日志");
                foreach (DataRow userDr in userDt.Rows)
                {
                    int UserId = int.Parse(userDr["Id"].ToString());
                    string ParentNav = userDr["ParentNav"].ToString();
                    LogHelper.Instance.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");
                    LogHelper.Instance.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);
                                LogHelper.Instance.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");
                                LogHelper.Instance.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)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "统计昨天的交易额异常");
            }
            db.Dispose();
            LogHelper.Instance.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行昨天交易额日志");

            StatMerchantTrade(date);
        }









        //统计商户交易额
        private void StatMerchantTrade(string date)
        {
            LogHelper.Instance.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "执行商户交易额日志");
            // WebCMSEntities db = new WebCMSEntities();
            try
            {
                string start = date + " 00:00:00";
                string end = DateTime.Parse(date).AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00";
                OtherMySqlConn.op("insert into PosMerchantTradeSummay (MerchantId,BrandId,TradeDate,TradeMonth,TradeAmount,CreateDate)  select *,now() from (select MerchantId,BrandId,DATE_FORMAT(CreateDate,'%Y%m%d') as TradeDate,DATE_FORMAT(CreateDate,'%Y%m') as TradeMonth,sum(TradeAmount) as TradeAmount from TradeRecord where CreateDate>='" + start + "' and CreateDate<'" + end + "' group by MerchantId,BrandId,DATE_FORMAT(CreateDate,'%Y%m%d'),TradeDate,DATE_FORMAT(CreateDate,'%Y%m') order by MerchantId,BrandId,DATE_FORMAT(CreateDate,'%Y%m%d')) tb");
                RedisDbconn.Instance.Clear("PosMerchantAmount:*");
                RedisDbconn.Instance.Clear("PosMerchantAmount:*:" + date.Replace("-", "").Substring(0, 6)); //商户当月交易
                RedisDbconn.Instance.Clear("PosMerchantAmount:*:" + date.Replace("-", "")); //商户当日交易
                // foreach (DataRow selfDr in selfdt.Rows)
                // {
                //     int BrandId = int.Parse(selfDr["BrandId"].ToString());
                //     int MerchantId = int.Parse(selfDr["MerchantId"].ToString());
                //     string TradeDate = selfDr["TradeDate"].ToString();
                //     TradeDate = TradeDate.Replace("-", "");
                //     string TradeMonth = TradeDate.Substring(0, 6);
                //     decimal TradeAmount = decimal.Parse(selfDr["TradeAmount"].ToString());
                //     PosMerchantTradeSummay merStat = db.PosMerchantTradeSummay.FirstOrDefault(m => m.MerchantId == MerchantId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId);
                //     if (merStat == null)
                //     {
                //         merStat = db.PosMerchantTradeSummay.Add(new PosMerchantTradeSummay()
                //         {
                //             MerchantId = MerchantId,
                //             TradeMonth = TradeMonth,
                //             TradeDate = TradeDate,
                //             BrandId = BrandId,
                //         }).Entity;
                //         db.SaveChanges();
                //     }
                //     merStat.TradeAmount += TradeAmount;
                //     db.SaveChanges();                    
                // }
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "统计商户的交易额");
            }
            // db.Dispose();
            LogHelper.Instance.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 == 1 && DateTime.Now.Hour > 1)
                {
                    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"));
                        StatUserLevelStart();
                    }
                }
                Thread.Sleep(600000);
            }
        }
        public void StatUserLevelStart()
        {
            WebCMSEntities db = new WebCMSEntities();
            try
            {
                OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
                LogHelper.Instance.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();
                    LogHelper.Instance.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()));
                                }
                                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+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)
                                {
                                    LogHelper.Instance.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)
                                {
                                    LogHelper.Instance.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;
                        }
                        LogHelper.Instance.WriteLog(startid.ToString(), "创客升级日志");
                    }
                    else
                    {
                        op = false;
                    }
                }
                LogHelper.Instance.WriteLog(DateTime.Now.ToString(), "创客升级日志");
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(ex.ToString(), "创客升级异常");
            }
            db.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();
            LogHelper.Instance.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 + "')");
                LogHelper.Instance.WriteLog("人数:" + userDt.Rows.Count + "\n\n", "执行创客激活数日志");
                foreach (DataRow userDr in userDt.Rows)
                {
                    int UserId = int.Parse(userDr["Id"].ToString());
                    string ParentNav = userDr["ParentNav"].ToString();
                    LogHelper.Instance.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");
                    LogHelper.Instance.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);
                                LogHelper.Instance.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");
                                LogHelper.Instance.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)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "执行创客激活数异常");
            }
            db.Dispose();
            LogHelper.Instance.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行创客激活数日志");
            Thread.Sleep(60000);
        }
        public void StartPosActNumEverTime()
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            LogHelper.Instance.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)
                    {
                        LogHelper.Instance.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)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "实时执行创客激活数异常");
            }
            db.Dispose();
            LogHelper.Instance.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["SqlConnStr"].ToString();
            string date = sender.ToString();
            LogHelper.Instance.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 + "'");
                LogHelper.Instance.WriteLog("人数:" + userDt.Rows.Count + "\n\n", "执行新增创客数日志");
                foreach (DataRow userDr in userDt.Rows)
                {
                    int UserId = int.Parse(userDr["Id"].ToString());
                    string ParentNav = userDr["ParentNav"].ToString();
                    LogHelper.Instance.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 + "");
                    LogHelper.Instance.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);
                                LogHelper.Instance.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 + ",%'");
                                LogHelper.Instance.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)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "执行新增创客数异常");
            }
            db.Dispose();
            LogHelper.Instance.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行新增创客数日志");
            Thread.Sleep(60000);
        }
        public void StartNewUserNumEverTime()
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            LogHelper.Instance.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)
                    {
                        LogHelper.Instance.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)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "实时执行新增创客数异常");
            }
            db.Dispose();
            LogHelper.Instance.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["SqlConnStr"].ToString();
            string date = sender.ToString();
            LogHelper.Instance.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();
                }
                LogHelper.Instance.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 + "')");
                LogHelper.Instance.WriteLog("交易人数:" + userDt.Rows.Count + "\n\n", "执行昨天收益日志");
                foreach (DataRow userDr in userDt.Rows)
                {
                    int UserId = int.Parse(userDr["Id"].ToString());
                    string ParentNav = userDr["ParentNav"].ToString();
                    LogHelper.Instance.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");
                    LogHelper.Instance.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);
                                LogHelper.Instance.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");
                                LogHelper.Instance.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)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "统计昨天收益异常");
            }
            db.Dispose();
            LogHelper.Instance.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "执行昨天收益日志");
        }

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







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

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

            return false;
        }

        #endregion

    }
}