using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using MySystem.Models;
using Library;
using LitJson;
using System.Threading;
using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;

namespace MySystem
{
    public class ProfitHelper
    {
        public readonly static ProfitHelper Instance = new ProfitHelper();
        private ProfitHelper()
        {
        }
        
        #region 激活队列
        public void StartActive()
        { 
            Thread th = new Thread(StartListenActive);
            th.IsBackground = true;
            th.Start();
        }
        public void StartListenActive()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("ActProfitQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    StartListenActiveDo(content);
                }
                else
                {
                    Thread.Sleep(60000);
                }
            }
        }
        public void StartListenActiveDo(string content)
        { 
            try
            {
                int MerchantId = int.Parse(content);
                KxsMainModels.WebCMSEntities kxsdb = new KxsMainModels.WebCMSEntities();
                WebCMSEntities db = new WebCMSEntities();
                bool check = db.ActiveReward.Any(m => m.MerchantId == MerchantId);
                if (!check)
                {
                    decimal ActPrize = 50;
                    MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new MerchantInfo();
                    PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == MerchantId) ?? new PosMachinesTwo();
                    db.ActiveReward.Add(new ActiveReward()
                    {
                        CreateDate = DateTime.Now,
                        UpdateDate = DateTime.Now,
                        UserId = merchant.UserId, //创客
                        MerchantId = merchant.Id, //商户
                        StandardDate = DateTime.Now, //达标日期
                        RewardAmount = ActPrize, //奖励金额
                        DirectBuddyNo = merchant.UserId, //商户直属创客
                        KqSnNo = pos.PosSn, //渠道SN号
                        SnType = pos.PosSnType, //机具类型
                        SnApplyUserId = pos.BuyUserId, //机具申请创客
                        SnStoreId = pos.StoreId, //SN仓库
                        RewardTips = "达标奖励", //奖励描述
                        Remark = "达标奖励", //备注
                        ActDate = pos.ActivationTime, //激活时间
                    });
                    db.SaveChanges();

                    string IdBrand = merchant.UserId + "_0";
                    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();

                    int GetUserId = merchant.UserId;
                    KxsMainModels.UserAccount account = kxsdb.UserAccount.FirstOrDefault(m => m.Id == GetUserId);
                    if (account == null)
                    {
                        account = kxsdb.UserAccount.Add(new KxsMainModels.UserAccount()
                        {
                            Id = GetUserId,
                            UserId = GetUserId,
                        }).Entity;
                        kxsdb.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; //变更后余额
                    KxsMainModels.UserAccountRecord userAccountRecord = kxsdb.UserAccountRecord.Add(new KxsMainModels.UserAccountRecord()
                    {
                        CreateDate = DateTime.Now,
                        UpdateDate = DateTime.Now,
                        UserId = GetUserId, //创客
                        ChangeType = 131, //变动类型
                        ChangeAmount = ActPrize, //变更金额
                        BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                        AfterTotalAmount = AfterTotalAmount, //变更后总金额
                        BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                        AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                        BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                        AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                    }).Entity;
                    kxsdb.SaveChanges();
                }
                kxsdb.Dispose();
                db.Dispose();
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + ex.ToString(), "激活奖励服务异常");
            }
        }
        #endregion

        #region 消费队列(执行消费退款金额的统计)
        public void StartListenTrade()
        {
            Thread th = new Thread(StartListenTradeDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StartListenTradeDo()
        {
            while (true)
            {
                string orderidstring = RedisDbconn.Instance.RPop<string>("ConsumerOrders:Divi:1:List");
                if (!string.IsNullOrEmpty(orderidstring))
                {
                    ReturnStat(orderidstring, 1);
                }
                else
                {
                    Thread.Sleep(60000);
                }
            }
        }

        public void StartListenWxTrade()
        {
            Thread th = new Thread(StartListenWxTradeDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StartListenWxTradeDo()
        {
            while (true)
            {
                string orderidstring = RedisDbconn.Instance.RPop<string>("ConsumerOrders:Divi:2:List");
                if (!string.IsNullOrEmpty(orderidstring))
                {
                    ReturnStat(orderidstring, 2);
                }
                else
                {
                    Thread.Sleep(10000);
                }
            }
        }

        public void ReturnStat(string orderidstring, int PayMode)
        { 
            int OrderId = int.Parse(function.CheckInt(orderidstring));
            WebCMSEntities db = new WebCMSEntities();
            using (var tran = db.Database.BeginTransaction())
            {
                try
                {
                    ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == OrderId);
                    if (order != null)
                    {
                        decimal PayMoney = order.PayMoney;
                        int MerchantId = order.MerchantId;
                        MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId);
                        if (merchant != null)
                        {
                            int UserId = merchant.UserId;
                            List<CustomTagSet> customTagSets = db.CustomTagSet.ToList(); //获取公用配置参数集和
                            //获取参数
                            CustomTagSet profitPercentSet = customTagSets.FirstOrDefault(m => m.Tags == "CusumerProfitPercent") ?? new CustomTagSet();
                            decimal profitPercent = decimal.Parse(function.CheckNum(profitPercentSet.Contents)); //基于收款金额的总分润比例;
                            CustomTagSet cusumerFeePercentSet = customTagSets.FirstOrDefault(m => m.Tags == "CusumerFeePercent") ?? new CustomTagSet();
                            decimal cusumerFeePercent = decimal.Parse(function.CheckNum(cusumerFeePercentSet.Contents)); //费率;
                            CustomTagSet minProfitSet = customTagSets.FirstOrDefault(m => m.Tags == "MinProfit") ?? new CustomTagSet();
                            decimal minProfit = decimal.Parse(function.CheckNum(minProfitSet.Contents)); //最小分润值;

                            MerchantParamSet set = Newtonsoft.Json.JsonConvert.DeserializeObject<MerchantParamSet>(order.SeoDescription);
                            int DiviPersons = set.DiviPersons; //单笔订单分红人数
                            decimal DiviPercent = set.DiviPercent; //单人最大分红比例
                            int ProfitDays = set.ProfitDays; //分红期限（天）
                            decimal GetPercent = set.GetPercent / 100; //商家实收比例
                            decimal MinPayMoney = set.MinPayMoney; //订单参与门槛
                            int IsAll = set.IsAll; //是否收全额
                            // decimal TotalActual = 0;
                            if (IsAll == 0 && PayMoney >= MinPayMoney && GetPercent < 1)
                            {
                                decimal DiviMoney = PayMoney * (1 - GetPercent - cusumerFeePercent - profitPercent);
                                if (DiviMoney > 0)
                                {
                                    order.ReturnFlag = 1;
                                    RedisDbconn.Instance.AddRightList("ConsumerOrders:Divi:" + PayMode + ":" + order.MerchantId, order);
                                    db.SaveChanges();
                                    DiviMoney = DiviMoney / DiviPersons;
                                    DiviMoney = Math.Round(DiviMoney, 2);
                                    List<int> deletes = new List<int>();
                                    long CurDiviPersons = DiviPersons;
                                    long QueueCount = RedisDbconn.Instance.Count("ConsumerOrders:Divi:" + PayMode + ":" + MerchantId);
                                    long CurQueueCount = QueueCount;
                                    // int CheckNum = 0; //判断活动人数是否大于当前队列订单数来确认while循环的数量，如果是就少循环一次，判处自己的订单名额
                                    if (CurDiviPersons >= CurQueueCount)
                                    {
                                        CurDiviPersons = CurQueueCount;
                                    }
                                    if (DiviPersons < QueueCount)
                                    {
                                        QueueCount = DiviPersons;
                                    }
                                    decimal OtherMoney = 0; // 退款金额>最大退款金额-当前退款金额，次金额应归还给商户

                                    // List<ConsumerOrders> orders = RedisDbconn.Instance.GetList<ConsumerOrders>("ConsumerOrders:Divi:" + PayMode + ":" + MerchantId);
                                    // foreach(ConsumerOrders sub in orders)
                                    // {
                                    //     LogHelper.Instance.WriteLog(sub.Id.ToString(), "返现队列");
                                    // }
                                    // LogHelper.Instance.WriteLog("\n\n", "返现队列");

                                    // 减去自己付的订单
                                    // CurDiviPersons = CurDiviPersons - 1;
                                    List<int> orderids = new List<int>();
                                    while (CurDiviPersons > 0)
                                    {
                                        ConsumerOrders suborder = RedisDbconn.Instance.RPopLPush<ConsumerOrders>("ConsumerOrders:Divi:" + PayMode + ":" + MerchantId, "ConsumerOrders:Divi:" + PayMode + ":" + MerchantId);
                                        if (suborder != null)
                                        {
                                            decimal TmpCurDivi = suborder.CurDivi;
                                            MerchantParamSet subset = Newtonsoft.Json.JsonConvert.DeserializeObject<MerchantParamSet>(order.SeoDescription);
                                            int subProfitDays = subset.ProfitDays; //分红期限（天）
                                            bool IsOut = suborder.UpdateDate.Value.AddDays(subProfitDays) < DateTime.Now ? true : false;
                                            if (suborder.CurDivi < suborder.MaxDivi && suborder.MaxDivi - suborder.CurDivi >= 0.01M && !IsOut)
                                            {
                                                //如果没过期并且当前退款金额没超过最大退款金额，就执行
                                                decimal GetMoney = suborder.MaxDivi - suborder.CurDivi;
                                                decimal DiffMoney = 0;
                                                if (GetMoney >= DiviMoney)
                                                {
                                                    GetMoney = DiviMoney;
                                                }
                                                else
                                                {
                                                    DiffMoney = DiviMoney - GetMoney;
                                                }
                                                if (GetMoney > minProfit)
                                                {
                                                    suborder.CurDivi += GetMoney;
                                                    if (DiffMoney > 0)
                                                    {
                                                        OtherMoney += DiffMoney;
                                                    }
                                                    MerchantAddInfo merchantAdd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == suborder.MerchantId) ?? new MerchantAddInfo();
                                                    if(!orderids.Contains(suborder.Id))
                                                    {
                                                        string RefundNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
                                                        int Status = 1;
                                                        if(order.PayMode == 1)
                                                        {
                                                            string result = AlipayFunction.Instance.Refund(suborder.SeoTitle, RefundNo, Math.Round(GetMoney, 2).ToString(), "门店消费补贴", merchantAdd.AlipayAuthToken);
                                                        }
                                                        else
                                                        {
                                                            Dictionary<string, string> dic = WeChatFunction.Instance.Refund(merchantAdd.SubMchid, Math.Round(GetMoney, 2), suborder.PayMoney, suborder.OrderNo, RefundNo, "门店消费补贴");
                                                        }
                                                        if(Status == 1)
                                                        {
                                                            db.ConsumerProfit.Add(new ConsumerProfit()
                                                            {
                                                                CreateDate = DateTime.Now,
                                                                ConsumerId = suborder.ConsumerId,
                                                                MerchantId = suborder.MerchantId,
                                                                OrderId = suborder.Id,
                                                                GetMoney = Math.Round(GetMoney, 2),
                                                                QueryCount = PayMode,
                                                                Sort = OrderId,
                                                                SeoTitle = suborder.OrderNo,
                                                                SeoKeyword = suborder.PayMoney.ToString(),
                                                                SeoDescription = RefundNo,
                                                            });
                                                            db.SaveChanges();
                                                        }
                                                        orderids.Add(suborder.Id);
                                                    }
                                                    merchant.ActCurrentAmount += Math.Round(GetMoney, 2); //活动已返金额
                                                    db.SaveChanges();

                                                    if (suborder.CurDivi < suborder.MaxDivi)
                                                    {
                                                        // RedisDbconn.Instance.AddList("ConsumerOrders:Divi:" + PayMode + ":" + MerchantId, suborder);
                                                        RedisDbconn.Instance.SetList("ConsumerOrders:Divi:" + PayMode + ":" + MerchantId, 0, suborder);
                                                        RedisDbconn.Instance.AddList("ConsumerOrdersSetDivi", "{\"OrderId\":\"" + suborder.Id + "\",\"DiviAmt\":\"" + suborder.CurDivi + "\"}");
                                                    }
                                                    else
                                                    {
                                                        suborder.CurDivi = TmpCurDivi;                                         
                                                        ConsumerOrders editOrder = db.ConsumerOrders.FirstOrDefault(m => m.Id == suborder.Id);
                                                        if (editOrder != null)
                                                        {
                                                            editOrder.ReturnFlag = 0;
                                                            db.SaveChanges();
                                                            RedisDbconn.Instance.AddList("ConsumerOrdersSetDiviHd", "{\"OrderId\":\"" + suborder.Id + "\",\"DiviAmt\":\"" + suborder.MaxDivi + "\"}");
                                                        }
                                                        RedisDbconn.Instance.RemoveFromList("ConsumerOrders:Divi:" + PayMode + ":" + MerchantId, suborder);               
                                                    }
                                                }
                                            }
                                            else
                                            { 
                                                //否者计算人数不计入退款名额
                                                suborder.CurDivi = TmpCurDivi;                                                   
                                                ConsumerOrders editOrder = db.ConsumerOrders.FirstOrDefault(m => m.Id == suborder.Id);
                                                if (editOrder != null)
                                                {
                                                    editOrder.ReturnFlag = 0;
                                                    db.SaveChanges();
                                                    RedisDbconn.Instance.AddList("ConsumerOrdersSetDiviHd", "{\"OrderId\":\"" + suborder.Id + "\",\"DiviAmt\":\"" + suborder.MaxDivi + "\"}");
                                                }
                                                RedisDbconn.Instance.RemoveFromList("ConsumerOrders:Divi:" + PayMode + ":" + MerchantId, suborder);
                                                CurDiviPersons += 1;
                                            }
                                        }
                                        CurDiviPersons -= 1;
                                        QueueCount = RedisDbconn.Instance.Count("ConsumerOrders:Divi:" + PayMode + ":" + MerchantId);
                                        if (QueueCount == 0)
                                        {
                                            CurDiviPersons = 0;
                                        }
                                    }
                                    // long DoCount = DiviPersons > (QueueCount + OutCount) ? DiviPersons - QueueCount : 0;
                                    // decimal MerchantGetMoney = PayMoney * GetPercent;
                                    // decimal DoMoney = DoCount * DiviMoney;
                                    // TotalActual = PayMoney * GetPercent + DoCount * DiviMoney + OtherMoney;
                                    // LogHelper.Instance.WriteLog("返现金额：" + DiviMoney + ";返现人数：" + DiviPersons + ";返现商户：" + TotalActual + ";返现溢出：" + OtherMoney + ";商户应得金额：" + MerchantGetMoney + ";返现差额：" + DoMoney + ";", "消费者返现日志");


                                    //代理商分润
                                    // AgentProfit(db, order);
                                }
                            }
                        }
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    LogHelper.Instance.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + ex.ToString(), "分红返现异常");
                    tran.Rollback();
                }
            }
            db.Dispose();
        }

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

        public void StartListenProfitDo()
        {
            while(true)
            {
                if(DateTime.Now.Day < 10 && DateTime.Now.Hour > 2 && DateTime.Now.Hour < 23)
                {
                    try
                    {
                        DoProfit();
                    }
                    catch(Exception ex)
                    {
                        LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "来客吧分润异常");
                    }
                    Thread.Sleep(600000);
                }
                else
                {
                    Thread.Sleep(3600000);
                }
            }
        }

        //分润算法
        public void DoProfit()
        {
            string TradeMonth = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            string check = function.ReadInstance("/ProfitFlag/" + TradeMonth + ".txt");
            if(!string.IsNullOrEmpty(check))
            {
                return;
            }
            function.WritePage("/ProfitFlag/", TradeMonth + ".txt", DateTime.Now.ToString());
            KxsMainModels.WebCMSEntities kxsdb = new KxsMainModels.WebCMSEntities();
            WebCMSEntities dbnew = new WebCMSEntities();
            DataTable dt = CustomerSqlConn.dtable("select IsAct,UserId,sum(TotalAmount) from UserAmountSummary where TradeMonth='" + TradeMonth + "' and SeoTitle='self' group by IsAct,UserId", MysqlConn.SqlConnStr);
            foreach(DataRow dr in dt.Rows)
            {
                int UserId = int.Parse(dr["UserId"].ToString());
                bool IsActive = dr["IsAct"].ToString() == "1";
                decimal TotalAmount = decimal.Parse(dr[2].ToString());
                List<ProfitUsers> users = new List<ProfitUsers>();
                int TopUserId = 0; //顶级创客Id
                KxsMainModels.Users us = kxsdb.Users.FirstOrDefault(a => a.Id == UserId);
                if (us != null)
                {
                    string uidstring = us.Id.ToString();
                    if (!string.IsNullOrEmpty(us.ParentNav))
                    {
                        uidstring = us.ParentNav.Trim(',').Replace(",,", ",") + "," + uidstring;
                        string[] parents = us.ParentNav.Trim(',').Replace(",,", ",").Split(',');
                        if(parents.Length > 1)
                        {
                            TopUserId = int.Parse(function.CheckInt(parents[1]));
                        }
                        else
                        {
                            TopUserId = int.Parse(function.CheckInt(parents[0]));
                        }
                    }
                    string[] uidlist = uidstring.Split(',');
                    Array.Reverse(uidlist);
                    foreach (string uidstr in uidlist)
                    {
                        int puid = int.Parse(function.CheckInt(uidstr));
                        KxsMainModels.Users pus = kxsdb.Users.FirstOrDefault(a => a.Id == puid);
                        if (pus != null)
                        {
                            users.Add(new ProfitUsers()
                            {
                                UserId = pus.Id,
                                MakerCode = pus.MakerCode,
                                RealName = pus.RealName,
                                UserNav = pus.ParentNav,
                                UserLevel = pus.UserLevel,
                                CreateDate = pus.CreateDate.Value,
                            });
                        }
                    }
                }
                KxsMainModels.Users topUser = kxsdb.Users.FirstOrDefault(a => a.Id == TopUserId) ?? new KxsMainModels.Users();
                List<ProfitResult> list = new List<ProfitResult>();
                list = StartProft(TotalAmount, 1, users, IsActive);
                try
                {
                    foreach (ProfitResult sub in list)
                    {
                        int ProfitType = sub.UserId == UserId ? 0 : 1;
                        ProfitRewardRecord editprofitrecord = dbnew.ProfitRewardRecord.FirstOrDefault(m => m.UserId == sub.UserId && m.BrandId == 1 && m.ProfitType == ProfitType && m.TradeMonth == TradeMonth);
                        if (editprofitrecord == null)
                        {
                            editprofitrecord = dbnew.ProfitRewardRecord.Add(new ProfitRewardRecord()
                            {
                                CreateDate = DateTime.Now,
                                UserId = sub.UserId, //创客
                                BrandId = 1, //品牌
                                ProfitType = ProfitType, //创客分润类型
                                TradeMonth = TradeMonth, //交易月
                                TopUserId = TopUserId, //顶级创客
                                CreateMan = sub.MakerCode, //创客编号
                                UpdateMan = topUser.MakerCode, //顶级编号
                                SeoTitle = sub.RealName, //创客姓名
                                SeoKeyword = topUser.RealName, //创客姓名
                            }).Entity;
                            dbnew.SaveChanges();
                            string RecordNo = "KPM";
                            int RecordId = editprofitrecord.Id;
                            string RecordIdString = RecordId.ToString();
                            for (int i = 0; i < 14 - RecordId.ToString().Length; i++)
                            {
                                RecordIdString = "0" + RecordIdString;
                            }
                            RecordNo += RecordIdString;
                            editprofitrecord.RecordNo = RecordNo;
                            dbnew.SaveChanges();
                        }
                        if(IsActive)
                        {
                            editprofitrecord.CreditTradeAmt += TotalAmount;
                            editprofitrecord.CreditTradeProfit += sub.Money;
                        }
                        else
                        {
                            editprofitrecord.TradeAmt += TotalAmount;
                            editprofitrecord.TradeProfit += sub.Money;
                        }
                        dbnew.SaveChanges();
                    }
                    dbnew.SaveChanges();
                }
                catch (Exception ex)
                { 
                    LogHelper.Instance.WriteLog(ex.ToString(), "分润异常");
                }
            }
            dbnew.Dispose();
            kxsdb.Dispose();
        }

        public void DoActives(WebCMSEntities dbnew, TradeRecord trade_record)
        {
            if (RedisDbconn.Instance.CheckKey("pobjact" + trade_record.Sort))
            {
                List<ProfitObjectsActives> objactives = RedisDbconn.Instance.GetList<ProfitObjectsActives>("pobjact" + trade_record.Sort);
                if (objactives.Count > 0)
                {
                    string OtherCondition = " and Type=1";
                    if (trade_record.Sort == 1) OtherCondition = " and Type<>1";
                    else if (trade_record.Sort == 2) OtherCondition = " and Type<>1";
                    else if (trade_record.Sort == 4) OtherCondition = " and Type=2";
                    else if (trade_record.Sort == 11) OtherCondition = " and Type=2";
                    else if (trade_record.Sort == 14) OtherCondition = " and (Type=1 or Type=3)";
                    else if (trade_record.Sort == 6 || trade_record.Sort == 7 || trade_record.Sort == 18) OtherCondition = "";
                    else if (trade_record.Sort == 29) OtherCondition = " and Type=2";
                    PosMachinesTwo machine = dbnew.PosMachinesTwo.FirstOrDefault(m => m.PosSn == trade_record.SnNo) ?? new PosMachinesTwo();
                    if (machine.ActivationState == 0)
                    {
                        return;
                    }
                    if (machine.BrandId == 0)
                    {
                        return;
                    }
                    Users user = dbnew.Users.FirstOrDefault(m => m.Id == machine.UserId) ?? new Users();
                    Users buyuser = dbnew.Users.FirstOrDefault(m => m.Id == machine.BuyUserId) ?? new Users();
                    Dictionary<string, ProfitUsers> Users = new Dictionary<string, ProfitUsers>();
                    Users.Add("UserId", new ProfitUsers()
                    {
                        UserId = user.Id,
                        UserNav = user.ParentNav,
                        UserLevel = user.UserLevel,
                    });
                    Users.Add("BuyUserId", new ProfitUsers()
                    {
                        UserId = buyuser.Id,
                        UserNav = buyuser.ParentNav,
                        UserLevel = buyuser.UserLevel,
                    });
                    List<ProfitResult> list = StartActiveProft(dbnew, machine, trade_record.SnNo, trade_record.Sort, Users, new ActiveCheckData()
                    {
                        TableName = "TransactionRecord",
                        StatField = "Money",
                        CheckField = "pos_sn",
                        OtherCondition = OtherCondition,
                    });
                    foreach (ProfitResult sub in list)
                    {
                        // dbnew.MybillTable.Add(new MybillTable()
                        // {
                        //     Content = sub.Message,
                        //     Money = sub.Money,
                        //     Type = 1,
                        //     UserId = sub.UserId,
                        //     UserNav = sub.UserNav,
                        //     Kind = 2,
                        //     CreateDate = DateTime.Now,
                        //     SeoTitle = trade_record.SeoTitle,
                        //     SeoKeyword = trade_record.SnNo,
                        //     Sort = trade_record.Sort,
                        //     Status = -3,
                        // });
                    }
                    dbnew.SaveChanges();
                }
            }
        }

        //代理商分润算法
        public void AgentProfit(WebCMSEntities db, ConsumerOrders order)
        {
            int MerchantId = order.MerchantId;
            decimal PayMoney = order.PayMoney;
            MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId);
            if (merchant != null)
            {
                List<CustomTagSet> customTagSets = RedisDbconn.Instance.GetList<CustomTagSet>("CustomTagSet", 1, 1000); //获取公用配置参数集和 // TODO: 后台配置
                //获取代理商参数
                CustomTagSet profitPercentSet = customTagSets.FirstOrDefault(m => m.Tags == "AgentProfitPercent") ?? new CustomTagSet();
                decimal profitPercent = decimal.Parse(function.CheckNum(profitPercentSet.Contents)); //基于收款金额的总分润比例;
                CustomTagSet makerProfitSet = customTagSets.FirstOrDefault(m => m.Tags == "AgentMakerProfit") ?? new CustomTagSet();
                decimal makerProfit = decimal.Parse(function.CheckNum(makerProfitSet.Contents)); //创客分润比例;
                CustomTagSet directProfitSet = customTagSets.FirstOrDefault(m => m.Tags == "AgentDirectProfit") ?? new CustomTagSet();
                decimal directProfit = decimal.Parse(function.CheckNum(directProfitSet.Contents)); //直推分润比例;
                CustomTagSet minProfitSet = customTagSets.FirstOrDefault(m => m.Tags == "MinProfit") ?? new CustomTagSet();
                decimal minProfit = decimal.Parse(function.CheckNum(minProfitSet.Contents)); //最小分润值;

                string MerAreas = merchant.Areas;
                MerchantParamSet set = Newtonsoft.Json.JsonConvert.DeserializeObject<MerchantParamSet>(order.SeoDescription);
                decimal ProfitMoney = PayMoney * (1 - set.DiviPercent) * profitPercent;
                Users user = db.Users.FirstOrDefault(m => m.Id == merchant.UserId);
                if (user != null)
                {
                    decimal ProfitAmount = ProfitMoney * makerProfit;
                    if (ProfitAmount >= minProfit)
                    {
                        db.ProfitRecord.Add(new ProfitRecord()
                        {
                            CreateDate = DateTime.Now,
                            UpdateDate = DateTime.Now,
                            Remark = "分润奖励",
                            UserId = user.Id, //创客
                            MerchantId = MerchantId, //商户
                            SnNo = order.SnNo, //SN号
                            TradeDate = order.CreateDate, //交易日期
                            ProfitAmount = ProfitAmount, //分润金额
                            BrandId = 1, //品牌
                            ParentNav = user.ParentNav, //上级创客集
                            TradeId = order.Id, //交易记录Id
                        });
                        db.SaveChanges();
                    }
                }
                Users puser = db.Users.FirstOrDefault(m => m.Id == user.ParentUserId);
                if (puser != null)
                {
                    decimal ProfitAmount = ProfitMoney * directProfit;
                    if (ProfitAmount >= minProfit)
                    {
                        db.ProfitRecord.Add(new ProfitRecord()
                        {
                            CreateDate = DateTime.Now,
                            UpdateDate = DateTime.Now,
                            Remark = "分润奖励",
                            UserId = puser.Id, //创客
                            MerchantId = MerchantId, //商户
                            SnNo = order.SnNo, //SN号
                            TradeDate = order.CreateDate, //交易日期
                            ProfitAmount = ProfitAmount, //分润金额
                            BrandId = 1, //品牌
                            ParentNav = puser.ParentNav, //上级创客集
                            TradeId = order.Id, //交易记录Id
                        });
                        db.SaveChanges();
                    }
                }
                string[] areaList = MerAreas.Split(',');
                decimal GetMoneyFlag = 0;
                for (int i = 0; i < areaList.Length; i++)
                {
                    string CurAreas = "";
                    for (int j = 0; j < areaList.Length - i; j++)
                    {
                        CurAreas += areaList[j] + ",";
                    }
                    CurAreas = CurAreas.TrimEnd(',');
                    int AgentLevel = CurAreas.Split(',').Length;
                    Users areaUser = db.Users.FirstOrDefault(m => m.AgentAreas == CurAreas && m.AgentLevel > AgentLevel);
                    if (areaUser != null)
                    {
                        AgentLevelSet agentset = db.AgentLevelSet.FirstOrDefault(m => m.Id == AgentLevel) ?? new AgentLevelSet();
                        decimal ProfitAmount = ProfitMoney * agentset.ProfitPercent;
                        if (agentset.LevelDiff == 1)
                        {
                            ProfitAmount -= GetMoneyFlag;
                        }
                        if (ProfitAmount >= minProfit)
                        {
                            db.ProfitRecord.Add(new ProfitRecord()
                            {
                                CreateDate = DateTime.Now,
                                UpdateDate = DateTime.Now,
                                Remark = "分润奖励",
                                UserId = puser.Id, //创客
                                MerchantId = MerchantId, //商户
                                SnNo = order.SnNo, //SN号
                                TradeDate = order.CreateDate, //交易日期
                                ProfitAmount = ProfitAmount, //分润金额
                                BrandId = 1, //品牌
                                ParentNav = puser.ParentNav, //上级创客集
                                TradeId = order.Id, //交易记录Id
                            });
                            db.SaveChanges();
                            GetMoneyFlag = ProfitAmount;
                        }
                        ProfitAmount = ProfitMoney * agentset.AreasProfitPercent;
                        if (ProfitAmount >= minProfit)
                        {
                            db.ProfitRecord.Add(new ProfitRecord()
                            {
                                CreateDate = DateTime.Now,
                                UpdateDate = DateTime.Now,
                                Remark = "分润奖励",
                                UserId = puser.Id, //创客
                                MerchantId = MerchantId, //商户
                                SnNo = order.SnNo, //SN号
                                TradeDate = order.CreateDate, //交易日期
                                ProfitAmount = ProfitAmount, //分润金额
                                BrandId = 1, //品牌
                                ParentNav = puser.ParentNav, //上级创客集
                                TradeId = order.Id, //交易记录Id
                            });
                            db.SaveChanges();
                        }
                    }
                }
            }
        }

        // 收款金额：100
        // 单笔退款金额 = (收款金额*返现比例 - 已返现金额) > (收款金额 - 收款金额*商家实收比例 - 收款金额*(1 - 商家实收比例)*10% - 手续费（收款金额*0.38%） ) / 返现人数 ? (收款金额 - 收款金额*商家实收比例 - 收款金额*(1 - 商家实收比例)*10% - 手续费（收款金额*0.38%）) / 返现人数 : (收款金额*返现比例 - 已返现金额)
        // 分账金额: 收款金额*(1 - 商家实收比例)*10%
        // 代理分润金额：   省：75%    市：65%    区县：55%   创客：30%    直推创客：5%
        // 区域保护分润金额：省：5%     市：5%     区县：5%
        // QE:
        /*
        条件1(跨区域开发商家)：
            A为四川省成都市金牛区代理，B为金牛区创客，C为B推荐的金牛区创客，D为四川省成都市代理，E为四川省代理，F为广东省深圳市南山区代理，G为广东省深圳市代理，H为广东省代理。
            C推荐一个广东省深圳市南山区商家，交易金额1000元。
        则：
            C可得分润 = 分账金额 * 30%
            B可得直推分润 = 分账金额 * 5%
            A可得分润 = 分账金额 * (55% - 30%)
            G可得分润 = 分账金额 * (65% - 55%)
            H可得分润 = 分账金额 * (75% - 65%) 
            F、G、H可再得区域保护分润 = 分账金额 * 5%

            
        条件2(同区域)：
            A为四川省成都市金牛区代理，B为金牛区创客，C为B推荐的金牛区创客，D为四川省成都市代理，E为四川省代理
            C推荐一个四川省成都市金牛区商家，交易金额1000元。
        则：
            C可得分润 = 分账金额 * 30%
            B可得直推分润 = 分账金额 * 5%
            A可得分润 = 分账金额 * (55% - 30%)
            D可得分润 = 分账金额 * (65% - 55%)
            E可得分润 = 分账金额 * (75% - 65%) 
            A、D、E可再得区域保护分润 = 分账金额 * 5%


        条件3(代理断级)：
            B为金牛区创客，C为B推荐的金牛区创客，D为四川省成都市代理，E为四川省代理，F为广东省深圳市南山区代理，G为广东省深圳市代理，H为广东省代理。
            C推荐一个广东省深圳市南山区商家，交易金额1000元。
        则：
            C可得分润 = 分账金额 * 30%
            B可得直推分润 = 分账金额 * 5%
            D可得分润 = 分账金额 * (65% - 30%)
            H可得分润 = 分账金额 * (75% - 65%) 
            F、G、H可再得区域保护分润 = 分账金额 * 5%

        */

        #endregion

        #region 商户队列

        public void StartListenMerchantDo(Dictionary<string, string> data, bool bind = false)
        {
            
        }

        #endregion

        #region 绑定队列

        public void StartListenBindDo(Dictionary<string, string> data)
        {
        }

        #endregion      




        #region 分润算法
        public List<ProfitResult> StartProft(decimal TotalAmount, int LevelKindId, List<ProfitUsers> users, bool IsActive = true)
        {
            LogHelper.Instance.WriteLog("\n\nTotalAmount：" + TotalAmount + "；", "来客吧分润日志");
            string Month = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            WebCMSEntities db = new WebCMSEntities();
            List<UserLevelSet> levels = db.UserLevelSet.ToList();
            List<ProfitResult> result = new List<ProfitResult>();
            ProfitObjects obj = db.ProfitObjects.FirstOrDefault();
            if (obj.Status == 1) //判断分润是否开启
            {
                int maxLevel = obj.MaxLevel; //最大等级
                int maxFloor = obj.MaxFloor; //最大层级
                decimal diffLevelProfit = 0;  //等级级差
                ProfitObjectLevels maxlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == 9) ?? new ProfitObjectLevels(); //获取最高等级参数
                decimal maxPercent = IsActive ? maxlevel.DebitPercents : maxlevel.Percents;
                LogHelper.Instance.WriteLog("maxPercent：" + maxPercent + "；", "来客吧分润日志");
                decimal maxLevelProfit = TotalAmount * maxPercent;
                LogHelper.Instance.WriteLog("maxLevelProfit：" + maxLevelProfit + "；", "来客吧分润日志");
                maxLevelProfit = PublicFunction.NumberFormat(maxLevelProfit);
                LogHelper.Instance.WriteLog("maxLevelProfit：" + maxLevelProfit + "；", "来客吧分润日志");
                // decimal diffDiviProfit = 0; //分红级差
                int curLevel = 0; //当前层级的会员等级
                for (int curFloor = 1; curFloor <= users.Count; curFloor++)
                {
                    ProfitUsers user = new ProfitUsers();
                    if (curFloor <= users.Count)
                    {
                        user = users[curFloor - 1];
                    }
                    SubUser selfUser = GetUser(user.UserId, Month) ?? new SubUser();
                    int UserLevel = GetUserLevel(selfUser); //当前会员等级
                    //判断当前创客是否有直推的激活机具，并且在活动时间内
                    if (curLevel == maxLevel)
                    {
                        break;
                    }
                    if (UserLevel <= maxLevel && UserLevel >= curLevel)
                    {
                        ProfitObjectLevels objlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == UserLevel); //获取当前等级参数
                        if (objlevel != null)
                        {
                            decimal getLevelProfit = 0;  //等级分润
                            UserProfitSet profitSet = new UserProfitSet();
                            decimal profitPercent = IsActive ? objlevel.DebitPercents : objlevel.Percents;
                            LogHelper.Instance.WriteLog("money：" + UserLevel + "：" + profitPercent + "；", "来客吧分润日志");
                            if (profitPercent > 0)
                            {
                                decimal profitTmp = TotalAmount * profitPercent;
                                getLevelProfit += profitTmp;
                                LogHelper.Instance.WriteLog("money：" + UserLevel + "：" + profitTmp + "；", "来客吧分润日志");
                            }
                            decimal money = getLevelProfit;
                            getLevelProfit -= diffLevelProfit;
                            if (objlevel.LevelDiff == 1)  //判断是否有级差
                            {
                                diffLevelProfit = money;
                            }
                            if (getLevelProfit >= obj.MinProfitVal)
                            {
                                result.Add(new ProfitResult()
                                {
                                    UserId = user.UserId,
                                    MakerCode = user.MakerCode,
                                    RealName = user.RealName,
                                    UserNav = user.UserNav,
                                    Money = PublicFunction.NumberFormat(getLevelProfit),
                                    ProfitRate = profitSet.ProfitRate,
                                    ProfitPercent = profitSet.ProfitPercent,
                                    AddOrSubRate = profitSet.AddOrSubRate,
                                    ProfitRateBase = profitSet.ProfitRateBase,
                                });
                                LogHelper.Instance.WriteLog("money：" + UserLevel + "：" + PublicFunction.NumberFormat(getLevelProfit) + "；", "来客吧分润日志");
                            }
                        }
                    }
                    if(curLevel < UserLevel)
                    {
                        curLevel = UserLevel;
                    }
                }
            }
            db.Dispose();
            return result;
        }

        public SubUser GetUser(int UserId, string Month)
        {
            SubUser user = new SubUser();
            DataTable dt = GetDataTable("select * from Users" + Month + " where Id=" + UserId);
            if(dt.Rows.Count > 0)
            {
                user.Id = int.Parse(dt.Rows[0]["Id"].ToString());
                user.ParentUserId = int.Parse(dt.Rows[0]["ParentUserId"].ToString());
                user.ParentNav = dt.Rows[0]["ParentNav"].ToString();
                user.UserLevel = int.Parse(dt.Rows[0]["UserLevel"].ToString());
                user.PreUserLevel = int.Parse(dt.Rows[0]["PreUserLevel"].ToString());
                user.PreLeaderLevel = int.Parse(dt.Rows[0]["PreLeaderLevel"].ToString());
                user.PreOpLevel = int.Parse(dt.Rows[0]["PreOpLevel"].ToString());
            }
            return user;
        }

        public int GetUserLevel(SubUser user)
        {
            int level = user.UserLevel;
            if(user.PreUserLevel > level) level = user.PreUserLevel;
            if(user.PreLeaderLevel > level) level = user.PreLeaderLevel;
            if(user.PreOpLevel > level) level = user.PreOpLevel;
            return level;
        }

        public DataTable GetDataTable(string sqlstr)
        {
            DataTable dt = CustomerSqlConn.dtable(sqlstr, Library.ConfigurationManager.AppSettings["KxsStatSqlConnStr"].ToString());
            return dt;
        }
        #endregion

        #region 活动奖励算法
        public List<ProfitResult> StartActiveProft(WebCMSEntities dbnew, PosMachinesTwo machine, string CheckObject, int ObjectId, Dictionary<string, ProfitUsers> Users, ActiveCheckData StatParam)
        {
            DateTime Start = machine.ActivationTime.Value;
            List<ProfitResult> result = new List<ProfitResult>();
            ProfitObjects obj = RedisDbconn.Instance.Get<ProfitObjects>("pobj" + ObjectId);
            if (obj.Status == 1) //判断分润是否开启
            {
                List<ProfitObjectsActives> objactives = RedisDbconn.Instance.GetList<ProfitObjectsActives>("pobjact" + ObjectId);
                foreach (ProfitObjectsActives objactive in objactives)
                {
                    if (objactive.StartDate <= DateTime.Now && objactive.EndDate >= DateTime.Now)
                    {
                        string UserKey = "UserId";
                        decimal ProfitMoney = objactive.ProfitNumber;  //获得数
                        decimal FinishNumber = objactive.FinishNumber; //完成数
                        string CheckKey = CheckObject + "-" + objactive.Id;
                        ProfitObjectsActiveCheck check = dbnew.ProfitObjectsActiveCheck.FirstOrDefault(m => m.CheckData == CheckKey);
                        if (ProfitMoney > 0 && check == null)
                        {
                            int LimitDateKind = objactive.LimitDateKind; //时间限制类型 日月年/自定义
                            if (LimitDateKind == 4)
                            {
                                DateTime LimitCustomerDate = objactive.LimitCustomerDate.Value; //过期时间
                                if (LimitCustomerDate >= DateTime.Now)
                                {
                                    decimal totalTradeMoney = 0;
                                    OtherMySqlConn.connstr = ConfigurationManager.AppSettings["OldSqlConnStr"].ToString();
                                    string sqlstr = "select sum(" + StatParam.StatField + ") from " + StatParam.TableName + " where Id>=" + StatParam.StartId + " and " + StatParam.CheckField + "='" + CheckObject + "'" + StatParam.OtherCondition + " and CreateDate>='" + Start.ToString("yyyy-MM-dd HH:mm:ss") + "' and CreateDate<='" + LimitCustomerDate.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                                    DataTable dt = OtherMySqlConn.dtable(sqlstr);
                                    if (dt.Rows.Count > 0)
                                    {
                                        totalTradeMoney = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString()));
                                    }
                                    // OtherMySqlConn.connstr = ;
                                    if (totalTradeMoney >= FinishNumber && ProfitMoney >= obj.MinProfitVal)  //达到完成数，发放奖励
                                    {
                                        result.Add(new ProfitResult()
                                        {
                                            UserId = Users[UserKey].UserId,
                                            UserNav = Users[UserKey].UserNav,
                                            Money = ProfitMoney,
                                        });
                                        dbnew.ProfitObjectsActiveCheck.Add(new ProfitObjectsActiveCheck()
                                        {
                                            CheckData = CheckKey
                                        });
                                        dbnew.SaveChanges();
                                    }
                                }
                            }
                            else
                            {
                                int LimitDateVal = objactive.LimitDateVal; //时间限制值 日月年
                                DateTime checkDate = Start;
                                if (LimitDateKind == 1)
                                {
                                    checkDate = checkDate.AddDays(LimitDateVal);
                                }
                                else if (LimitDateKind == 2)
                                {
                                    checkDate = checkDate.AddMonths(LimitDateVal);
                                }
                                else if (LimitDateKind == 3)
                                {
                                    checkDate = checkDate.AddYears(LimitDateVal);
                                }
                                if (checkDate >= DateTime.Now)
                                {
                                    decimal totalTradeMoney = 0;
                                    OtherMySqlConn.connstr = ConfigurationManager.AppSettings["OldSqlConnStr"].ToString();
                                    string sql = "select sum(" + StatParam.StatField + ") from " + StatParam.TableName + " where Id>=" + StatParam.StartId + " and " + StatParam.CheckField + "='" + CheckObject + "'" + StatParam.OtherCondition + " and CreateDate>='" + Start.ToString("yyyy-MM-dd HH:mm:ss") + "' and CreateDate<='" + checkDate.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                                    DataTable dt = OtherMySqlConn.dtable(sql);
                                    if (dt.Rows.Count > 0)
                                    {
                                        totalTradeMoney = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString()));
                                    }
                                    // OtherMySqlConn.connstr = ;
                                    if (totalTradeMoney >= FinishNumber && ProfitMoney >= obj.MinProfitVal)  //达到完成数，发放奖励
                                    {
                                        result.Add(new ProfitResult()
                                        {
                                            UserId = Users[UserKey].UserId,
                                            UserNav = Users[UserKey].UserNav,
                                            Money = ProfitMoney,
                                        });
                                        dbnew.ProfitObjectsActiveCheck.Add(new ProfitObjectsActiveCheck()
                                        {
                                            CheckData = CheckKey
                                        });
                                        dbnew.SaveChanges();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return result;
        }
        #endregion

        #region 激活奖励算法
        public ProfitResult ActivationProft(PosMachinesTwo machine, ProfitUsers User)
        {
            int BrandId = machine.BrandId;
            DateTime Start = machine.ActivationTime.Value;
            ProfitResult result = new ProfitResult();
            if (machine.PosSnType == 1 && machine.UserId != machine.BuyUserId) //循环机具，划拨给其他人，没有激活返现没有循环
            { 
                return result;
            }
            ProfitObjects obj = RedisDbconn.Instance.Get<ProfitObjects>("pobj" + BrandId);
            if (obj.Status == 1) //判断分润是否开启
            {
                ProfitObjectActivations objact = RedisDbconn.Instance.Get<ProfitObjectActivations>("pobjacti" + BrandId);
                if (objact.StartDate <= DateTime.Now && objact.EndDate >= DateTime.Now)
                {
                    int LimitDateKind = objact.LimitDateKind; //时间限制类型 日月年/自定义
                    int LimitDateVal = objact.LimitDateVal; //时间限制值 日月年
                    decimal ProfitMoney = objact.ProfitNumber;
                    int MachineCount = objact.MachineCount;
                    DateTime checkDate = Start;
                    if (LimitDateKind == 1)
                    {
                        checkDate = checkDate.AddDays(LimitDateVal);
                    }
                    else if (LimitDateKind == 2)
                    {
                        checkDate = checkDate.AddMonths(LimitDateVal);
                    }
                    else if (LimitDateKind == 3)
                    {
                        checkDate = checkDate.AddYears(LimitDateVal);
                    }
                    else if (LimitDateKind == 4)
                    {
                        checkDate = objact.LimitCustomerDate.Value;
                    }
                    // if (DateTime.Now > checkDate && ProfitMoney > objact.ExpiredNumber)
                    // {
                    //     ProfitMoney = objact.ExpiredNumber;
                    // }
                    if (ProfitMoney >= obj.MinProfitVal)
                    {
                        result = new ProfitResult()
                        {
                            UserId = User.UserId,
                            UserNav = User.UserNav,
                            Money = ProfitMoney,
                            MachineCount = MachineCount,
                        };
                    }
                }
            }
            return result;
        }
        #endregion

        #region 获取分润规则Id

        private int GetLevelKindId(int BrandId, int Help, int BankCardType)
        {
            return RedisDbconn.Instance.Get<int>("pobjlv:kid:" + BrandId + ":" + Help + ":" + BankCardType);
        }

        #endregion








        #region POS统计交易额
        public void StartListenTradeDo(int tradeId, bool profit = true)
        {
            try
            {
                WebCMSEntities dbnew = new WebCMSEntities();
                TradeRecord trade_record = dbnew.TradeRecord.FirstOrDefault(m => m.Id == tradeId);
                if (trade_record != null)
                {
                    int BrandId = trade_record.BrandId;
                    decimal TradeAmt = trade_record.TradeAmount;
                    int BankCardTypeNum = trade_record.BankCardType; //1-贷记卡，0-借记卡，2-准贷记卡

                    DateTime TradeDateTime = trade_record.CreateDate.Value;
                    string monthString = TradeDateTime.ToString("yyyyMM");
                    string dayString = TradeDateTime.ToString("yyyyMMdd");
                    string NaturalMonthString = RedisDbconn.Instance.Get<string>("pobjrule:" + BrandId + ":HelpPolicy:NaturalMonth");
                    int NaturalMonth = int.Parse(NaturalMonthString); //自然月

                    MachineForSnNo machinefor = dbnew.MachineForSnNo.FirstOrDefault(m => m.SnNo == trade_record.SnNo) ?? new MachineForSnNo();
                    PosMachinesTwo machine = dbnew.PosMachinesTwo.FirstOrDefault(m => m.Id == machinefor.SnId) ?? new PosMachinesTwo();
                    Users user = dbnew.Users.FirstOrDefault(m => m.Id == machine.UserId) ?? new Users();
                    int TopUserId = 0;
                    if (!string.IsNullOrEmpty(user.ParentNav))
                    {
                        string[] navList = user.ParentNav.Trim(',').Replace(",,", ",").Split(',');
                        if (navList.Length > 1)
                        {
                            TopUserId = int.Parse(navList[1]);
                        }
                        else
                        { 
                            TopUserId = int.Parse(navList[0]);
                        }
                    }
                    PosMerchantInfo merchant = dbnew.PosMerchantInfo.FirstOrDefault(m => m.Id == machine.BindMerchantId) ?? new PosMerchantInfo();
                    List<UserLevelSet> levels = dbnew.UserLevelSet.ToList();

                    using (var tran = dbnew.Database.BeginTransaction())
                    {
                        try
                        {
                            ulong DirectFlag = merchant.UserId == machine.UserId ? 1u : 0u; //是否直营
                            ulong MerHelpFlag = 1; //扶持期、稳定期
                            if (merchant.CreateDate.Value < DateTime.Now.AddMonths(-NaturalMonth))
                            {
                                MerHelpFlag = 0;
                            }
                            int HelpMonthCount = DateTime.Now.Month - merchant.CreateDate.Value.Month; //扶持期第几月
                            if (HelpMonthCount < 0)
                            {
                                HelpMonthCount = 12 + DateTime.Now.Month - merchant.CreateDate.Value.Month;
                            }
                            int QrPayFlag = trade_record.QrPayFlag;
                            decimal CreditTradeAmt = 0;
                            decimal DebitNotCapTradeAmt = 0;
                            decimal DebitCapTradeAmt = 0;
                            int DebitCapTradeNum = 0;
                            if (BankCardTypeNum == 1)
                            {
                                CreditTradeAmt = TradeAmt;
                            }
                            else if (BankCardTypeNum == 0)
                            {
                                //累计借记卡封顶或非封顶交易 // TODO:需优化，判断不太科学
                                // decimal profitrate = 0;
                                // if (user.CreateDate.Value.AddMonths(NaturalMonth) >= DateTime.Now)
                                // {
                                //     UserProfitSet profitSet = dbnew.UserProfitSet.FirstOrDefault(m => m.UserId == user.Id && m.BrandId == BrandId && m.CardType == BankCardTypeNum && m.HelpFlag == 1) ?? new UserProfitSet(); //获取创客分润规则-扶持期
                                //     profitrate = profitSet.ProfitRate;
                                // }
                                // else
                                // {
                                //     UserProfitSet profitSet = dbnew.UserProfitSet.FirstOrDefault(m => m.UserId == user.Id && m.BrandId == BrandId && m.CardType == BankCardTypeNum && m.HelpFlag == 0) ?? new UserProfitSet(); //获取创客分润规则-非扶持期
                                //     profitrate = profitSet.ProfitRate;
                                // }
                                // profitrate = profitrate / 100;
                                // int UserLevel = user.UserLevel; //当前会员等级
                                // decimal utrade = RedisDbconn.Instance.Get<decimal>("TeamTradeStat:" + user.Id + ":" + BrandId + ":" + DateTime.Now.ToString("yyMM"));
                                // UserLevelSet checklevel = levels.Where(m => m.UpLevelIntegral < utrade).OrderBy(m => m.Id).FirstOrDefault();
                                // if (checklevel != null)
                                // {
                                //     UserLevel = checklevel.Id + 1;
                                // }
                                // ProfitObjectLevels objlevel = RedisDbconn.Instance.Get<ProfitObjectLevels>("pobjlv" + GetLevelKindId(BrandId) + ":" + UserLevel); //获取当前等级参数
                                // decimal getLevelProfit = TradeAmt * objlevel.Percents * profitrate;
                                // if (getLevelProfit < 1)
                                // {
                                //     DebitNotCapTradeAmt = TradeAmt;
                                // }
                                // else
                                // {
                                //     DebitCapTradeAmt = TradeAmt;
                                //     DebitCapTradeNum = 1;
                                //     trade_record.CapFlag = 1;
                                //     dbnew.SaveChanges();
                                // }
                                DebitNotCapTradeAmt = TradeAmt;
                            }
                            UserTradeMonthSummary editsummary = dbnew.UserTradeMonthSummary.FirstOrDefault(m => m.UserId == user.Id && m.TradeMonth == monthString && m.BrandId == BrandId && m.StatType == 0);
                            if (editsummary == null)
                            {
                                dbnew.UserTradeMonthSummary.Add(new UserTradeMonthSummary()
                                {
                                    CreateDate = DateTime.Now,
                                    UserId = user.Id, //创客
                                    TradeMonth = monthString, //交易月
                                    BrandId = BrandId, //品牌
                                    StatType = 0, //交易统计类型
                                    TradeAmt = TradeAmt, //商户交易总额
                                    CreditTradeAmt = CreditTradeAmt, //商户贷记卡交易总金额
                                    DebitNotCapTradeAmt = DebitNotCapTradeAmt, //商户非封顶借记卡交易总金额
                                    DebitCapTradeAmt = DebitCapTradeAmt, //商户借记卡封顶交易总额
                                    DebitCapTradeNum = DebitCapTradeNum, //商户借记卡封顶交易总笔数
                                    MallPosOrderStatus = machine.PosSnType == 1 ? 0 : 1, //商城兑换机具状态
                                    ActiveBuddyMerStatus = user.RealName == merchant.MerchantName ? 0 : 1, //激活创客同名商户
                                });
                            }
                            else
                            {
                                editsummary.TradeAmt += TradeAmt;
                                editsummary.CreditTradeAmt += CreditTradeAmt;
                                editsummary.DebitNotCapTradeAmt += DebitNotCapTradeAmt;
                                editsummary.DebitCapTradeAmt += DebitCapTradeAmt;
                                editsummary.DebitCapTradeNum += DebitCapTradeNum;
                            }
                            TradeDaySummary editdaysum = dbnew.TradeDaySummary.FirstOrDefault(m => m.UserId == user.Id && m.TradeDate == dayString && m.BrandId == BrandId);
                            if (editdaysum == null)
                            {
                                editdaysum = dbnew.TradeDaySummary.Add(new TradeDaySummary()
                                {
                                    CreateDate = DateTime.Now,
                                    UserId = user.Id, //创客
                                    TradeDate = dayString, //交易日
                                    TradeMonth = monthString, //交易月
                                    BrandId = BrandId, //品牌
                                    TopUserId = TopUserId, //顶级创客
                                }).Entity;
                                dbnew.SaveChanges();
                            }
                            //分类统计交易额
                            if (MerHelpFlag == 0)
                            {
                                if (DirectFlag == 1)
                                {
                                    editdaysum.NotHelpDirectTradeAmt = TradeAmt; //直营商户交易总额(非扶持期)
                                    if (BankCardTypeNum == 1)
                                    {
                                        editdaysum.NotHelpDirectCreditTradeAmt += TradeAmt; //直营贷记卡交易总额(非扶持期)
                                        if (QrPayFlag == 1)
                                        {
                                            editdaysum.NotHelpDirectQrCreditTradeAmt += TradeAmt; //直营云闪付贷记卡交易额(非扶持期)
                                        }
                                        else
                                        {
                                            editdaysum.NotHelpDirectNonQrCreditTradeAmt += TradeAmt; //直营非云闪付贷记卡交易额(非扶持期)
                                        }
                                    }
                                    else
                                    {
                                        editdaysum.NotHelpDirectDebitTradeAmt += TradeAmt; //直营商户借记卡交易总额(非扶持期)
                                        if (DebitCapTradeNum > 0)
                                        {
                                            editdaysum.NotHelpDirectDebitCapTradeAmt += TradeAmt; //直营商户借记卡封顶交易总金额(非扶持期)
                                            editdaysum.NotHelpDirectDebitCapNum += 1; //直营商户借记卡封顶交易总数(非扶持期)
                                        }
                                        else
                                        {
                                            if (QrPayFlag == 1)
                                            {
                                                editdaysum.NotHelpDirectQrDebitTradeAmt += TradeAmt; //直营云闪付非封顶借记卡(非扶持期)
                                            }
                                            else
                                            {
                                                editdaysum.NotHelpDirectNonQrDebitTradeAmt += TradeAmt; //直营非云闪付非封顶借记卡(非扶持期)
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    editdaysum.NotHelpNonDirectTradeAmt += TradeAmt; //非直营商户交易总额(非扶持期)
                                    if (BankCardTypeNum == 1)
                                    {
                                        editdaysum.NotHelpNonDirectCreditTradeAmt += TradeAmt; //非直营贷记卡交易总额(非扶持期)
                                        if (QrPayFlag == 1)
                                        {
                                            editdaysum.NotHelpNonDirectQrCreditTradeAmt += TradeAmt; //非直营云闪付贷记卡交易额(非扶持期)
                                        }
                                        else
                                        {
                                            editdaysum.NotHelpNonDirectNonQrCreditTradeAmt += TradeAmt; //非直营非云闪付贷记卡交易额(非扶持期)
                                        }
                                    }
                                    else
                                    {
                                        editdaysum.NotHelpNonDirectDebitTradeAmt += TradeAmt; //非直营商户借记卡交易总额(非扶持期)
                                        if (DebitCapTradeNum > 0)
                                        {
                                            editdaysum.NotHelpNonDirectDebitCapTradeAmt += TradeAmt; //非直营商户借记卡封顶交易总金额(非扶持期)
                                            editdaysum.NotHelpNonDirectDebitCapNum += 1; //非直营商户借记卡封顶交易总数(非扶持期)
                                        }
                                        else
                                        {
                                            if (QrPayFlag == 1)
                                            {
                                                editdaysum.NotHelpNonDirectQrDebitTradeAmt += TradeAmt; //非直营云闪付非封顶借记卡(非扶持期)
                                            }
                                            else
                                            {
                                                editdaysum.NotHelpNonDirectNonQrDebitTradeAmt += TradeAmt; //非直营非云闪付非封顶借记卡(非扶持期)
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (DirectFlag == 1)
                                {
                                    editdaysum.HelpDirectTradeAmt += TradeAmt; //直营商户交易总额(扶持期)
                                    if (BankCardTypeNum == 1)
                                    {
                                        editdaysum.HelpDirectCreditTradeAmt += TradeAmt; //直营贷记卡交易总额(扶持期)
                                        if (QrPayFlag == 1)
                                        {
                                            editdaysum.HelpDirectQrCreditTradeAmt += TradeAmt; //直营云闪付贷记卡交易额(扶持期)
                                        }
                                        else
                                        {
                                            editdaysum.HelpDirectNonQrCreditTradeAmt += TradeAmt; //直营非云闪付贷记卡交易额(扶持期)
                                        }
                                    }
                                    else
                                    {
                                        editdaysum.HelpDirectDebitTradeAmt += TradeAmt; //直营商户借记卡交易总额(扶持期)
                                        if (DebitCapTradeNum > 0)
                                        {
                                            editdaysum.HelpDirectDebitCapTradeAmt += TradeAmt; //直营商户借记卡封顶交易总金额(扶持期)
                                            editdaysum.HelpDirectDebitCapNum += 1; //直营商户借记卡封顶交易总数(扶持期)
                                        }
                                        else
                                        {
                                            if (QrPayFlag == 1)
                                            {
                                                editdaysum.HelpDirectQrDebitTradeAmt += TradeAmt; //直营云闪付非封顶借记卡(扶持期)
                                            }
                                            else
                                            {
                                                editdaysum.HelpDirectNonQrDebitTradeAmt += TradeAmt; //直营非云闪付非封顶借记卡(扶持期)
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    editdaysum.HelpNonDirectTradeAmt += TradeAmt; //非直营商户交易总额(扶持期)
                                    if (BankCardTypeNum == 1)
                                    {
                                        editdaysum.HelpNonDirectCreditTradeAmt += TradeAmt; //非直营贷记卡交易总额(扶持期)
                                        if (QrPayFlag == 1)
                                        {
                                            editdaysum.HelpNonDirectQrCreditTradeAmt += TradeAmt; //非直营云闪付贷记卡交易额(扶持期)
                                        }
                                        else
                                        {
                                            editdaysum.HelpNonDirectNonQrCreditTradeAmt += TradeAmt; //非直营非云闪付贷记卡交易额(扶持期)
                                        }
                                    }
                                    else
                                    {
                                        editdaysum.HelpNonDirectDebitTradeAmt += TradeAmt; //非直营商户借记卡交易总额(扶持期)
                                        if (DebitCapTradeNum > 0)
                                        {
                                            editdaysum.HelpNonDirectDebitCapTradeAmt += TradeAmt; //非直营商户借记卡封顶交易总金额(扶持期)
                                            editdaysum.HelpNonDirectDebitCapNum += 1; //非直营商户借记卡封顶交易总数(扶持期)
                                        }
                                        else
                                        {
                                            if (QrPayFlag == 1)
                                            {
                                                editdaysum.HelpNonDirectQrDebitTradeAmt += TradeAmt; //非直营云闪付非封顶借记卡(扶持期)
                                            }
                                            else
                                            {
                                                editdaysum.HelpNonDirectNonQrDebitTradeAmt += TradeAmt; //非直营非云闪付非封顶借记卡(扶持期)
                                            }
                                        }
                                    }
                                }
                            }
                            UserTradeDaySummary userdaysum = dbnew.UserTradeDaySummary.FirstOrDefault(m => m.UserId == user.Id && m.TradeDate == dayString && m.BrandId == BrandId);
                            if (userdaysum == null)
                            {
                                userdaysum = dbnew.UserTradeDaySummary.Add(new UserTradeDaySummary()
                                {
                                    CreateDate = DateTime.Now,
                                    UserId = user.Id, //创客
                                    TradeDate = dayString, //交易日
                                    TradeMonth = monthString, //交易月
                                    BrandId = BrandId, //品牌
                                }).Entity;
                                dbnew.SaveChanges();
                            }
                            if (DirectFlag == 1)
                            {
                                userdaysum.DirectTradeAmt += TradeAmt; //直营商户交易总额
                                if (BankCardTypeNum == 0)
                                {
                                    userdaysum.DirectDebitTradeAmt += TradeAmt; //直营商户借记卡交易总额
                                }
                            }
                            else
                            {
                                userdaysum.NonDirectTradeAmt += TradeAmt; //非直营商户交易总额
                                if (BankCardTypeNum == 0)
                                {
                                    userdaysum.NonDirectDebitTradeAmt += TradeAmt; //非直营商户借记卡交易总额
                                }
                            }
                            dbnew.SaveChanges();
                            if (profit)
                            {
                                DoProfitForPos(dbnew, trade_record);
                            }
                            tran.Commit();
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Instance.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + ex.ToString(), "自定义分润程序监听队列异常");
                            tran.Rollback();
                        }
                    }
                }
                dbnew.Dispose();
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + ex.ToString(), "自定义分润程序监听队列异常");
            }
        }

        public void DoProfitForPos(WebCMSEntities dbnew, TradeRecord trade_record)
        { 
            List<ProfitUsers> users = new List<ProfitUsers>();
            int TopUserId = 0; //顶级创客Id
            Users us = dbnew.Users.FirstOrDefault(a => a.Id == trade_record.UserId);
            if (us != null)
            {
                string uidstring = us.Id.ToString();
                string[] uidlist = { };
                if (!string.IsNullOrEmpty(us.ParentNav))
                {
                    uidstring = us.ParentNav.Trim(',').Replace(",,", ",") + "," + uidstring;
                    uidlist = uidstring.Split(',');
                    if (uidlist.Length > 1)
                    {
                        TopUserId = int.Parse(function.CheckInt(uidlist[1]));
                    }
                    else
                    { 
                        TopUserId = int.Parse(function.CheckInt(uidlist[0]));
                    }
                }
                Array.Reverse(uidlist);
                foreach (string uidstr in uidlist)
                {
                    int puid = int.Parse(function.CheckInt(uidstr));
                    Users pus = dbnew.Users.FirstOrDefault(a => a.Id == puid);
                    if (pus != null)
                    {
                        users.Add(new ProfitUsers()
                        {
                            UserId = pus.Id,
                            UserNav = pus.ParentNav,
                            UserLevel = pus.UserLevel,
                            CreateDate = pus.CreateDate.Value,
                        });
                    }
                }
            }
            string TradeMonth = trade_record.TradeDate.Value.ToString("yyyyMM");
            List<ProfitResult> list = new List<ProfitResult>();
            list = StartProftForPos(dbnew, trade_record, users);
            using (var tran = dbnew.Database.BeginTransaction())
            {
                try
                {
                    foreach (ProfitResult sub in list)
                    {
                        if (sub.Message == "分红奖励")
                        { 
                            UserAccountRecord accountRecord = dbnew.UserAccountRecord.Add(new UserAccountRecord()
                            {
                                CreateDate = DateTime.Now,
                                UpdateDate = DateTime.Now,
                                UserId = sub.UserId, //创客
                                ChangeType = 11, //变动类型
                                ProductType = trade_record.BrandId, //产品类型
                                ChangeAmount = sub.Money, //变更金额
                                Status = -1,
                            }).Entity;
                            dbnew.SaveChanges();
                        }
                        else
                        {
                            int ProfitType = sub.UserId == trade_record.UserId ? 0 : 1;
                            ProfitRewardRecord editprofitrecord = dbnew.ProfitRewardRecord.FirstOrDefault(m => m.UserId == sub.UserId && m.MerchantId == trade_record.MerchantId && m.BrandId == trade_record.BrandId && m.ProfitType == ProfitType && m.TradeMonth == TradeMonth);
                            if (editprofitrecord == null)
                            {
                                editprofitrecord = dbnew.ProfitRewardRecord.Add(new ProfitRewardRecord()
                                {
                                    CreateDate = DateTime.Now,
                                    UserId = sub.UserId, //创客
                                    MerchantId = trade_record.MerchantId, //商户
                                    BrandId = trade_record.BrandId, //品牌
                                    ProfitType = ProfitType, //创客分润类型
                                    TradeMonth = TradeMonth, //交易月
                                    TopUserId = TopUserId, //顶级创客
                                }).Entity;
                                dbnew.SaveChanges();
                                string RecordNo = "KPM";
                                int RecordId = editprofitrecord.Id;
                                string RecordIdString = RecordId.ToString();
                                for (int i = 0; i < 14 - RecordId.ToString().Length; i++)
                                {
                                    RecordIdString = "0" + RecordIdString;
                                }
                                RecordNo += RecordIdString;
                                editprofitrecord.RecordNo = RecordNo;
                                dbnew.SaveChanges();
                            }
                            // editprofitrecord.OtherTradeAmt = 0; //其他产品交易总金额
                            // editprofitrecord.OtherCreditTradeAmt = 0; //其他产品贷记卡交易总金额
                            // editprofitrecord.OtherDebitNotCapTradeAmt = 0; //其他产品借记卡非封顶交易总金额
                            decimal TradeAmount = trade_record.TradeAmount;
                            editprofitrecord.TradeAmt += TradeAmount; //商户交易总额
                            if (trade_record.BankCardType == 0) editprofitrecord.CreditTradeAmt += TradeAmount; //贷记卡交易总金额
                            if (trade_record.QrPayFlag == 1 && trade_record.BankCardType == 0) editprofitrecord.QrCreditTradeAmt += TradeAmount; //(云闪付)贷记卡交易总金额
                            if (trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NonQrCreditTradeAmt += TradeAmount; //(非云闪付)贷记卡交易总金额
                            if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NotHelpCreditTradeAmt += TradeAmount; //(非扶持期)(非云闪付)贷记卡交易总金额
                            if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.HelpCreditTradeAmt += TradeAmount; //(扶持期)(非云闪付)贷记卡交易总金额
                            if (sub.Money < 1 && trade_record.BankCardType == 1) editprofitrecord.DebitNonCapTradeAmt += TradeAmount; //商户非封顶借记卡交易总额
                            if (sub.Money < 1 && trade_record.QrPayFlag == 1 && trade_record.BankCardType == 1) editprofitrecord.QrDebitNotCapTradeAmt += TradeAmount; //(云闪付)商户非封顶借记卡交易总额
                            if (sub.Money < 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NonQrDebitNotCapTradeAmt += TradeAmount; //(非云闪付)商户非封顶借记卡交易总额
                            if (sub.Money < 1 && trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NotHelpDebitNonCapTradeAmt += TradeAmount; //(非扶持期)(非云闪付)借记卡非封顶交易总金额
                            if (sub.Money < 1 && trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.HelpDebitNonCapTradeAmt += TradeAmount; //(扶持期)(非云闪付)借记卡非封顶交易总金额
                            if (sub.Money == 1 && trade_record.BankCardType == 1) editprofitrecord.DebitCapTradeAmt = TradeAmount; //商户借记卡封顶交易总额
                            editprofitrecord.DebitCapTradeNum += 1; //商户借记卡封顶交易总笔数

                            decimal ProfitMoney = sub.Money;
                            ulong DirectFlag = trade_record.DirectFlag;
                            editprofitrecord.TradeProfit += ProfitMoney; //交易分润
                            if (trade_record.BankCardType == 0) editprofitrecord.CreditTradeProfit += ProfitMoney; //贷记卡分润总金额
                            if (trade_record.QrPayFlag == 1 && trade_record.BankCardType == 0) editprofitrecord.QrCreditTradeProfit += ProfitMoney; //(云闪付)贷记卡交易分润
                            if (trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NonQrCreditTradeProfit += ProfitMoney; //(非云闪付)贷记卡交易分润
                            if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NotHelpCreditTradeProfit += ProfitMoney; //(非扶持期)(非云闪付)贷记卡分润总金额
                            if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.HelpCreditTradeProfit += ProfitMoney; //(扶持期)(非云闪付)贷记卡分润总金额
                            if (sub.Money < 1 && trade_record.BankCardType == 1) editprofitrecord.DebitNonTradeCapProfit += ProfitMoney; //借记卡非封顶交易分润总金额
                            if (sub.Money < 1 && trade_record.QrPayFlag == 1 && trade_record.BankCardType == 1) editprofitrecord.QrDebitNonTradeCapProfit += ProfitMoney; //(云闪付)借记卡非封顶交易分润总金额
                            if (sub.Money < 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NonQrDebitNonTradeCapProfit += ProfitMoney; //(非云闪付)借记卡非封顶交易分润总金额
                            if (sub.Money < 1 && trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NotHelpDebitNonTradeCapProfit += ProfitMoney; //(非扶持期)(非云闪付)借记卡非封顶交易分润总金额
                            if (sub.Money < 1 && trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.HelpDebitNonTradeCapProfit += ProfitMoney; //(扶持期)(非云闪付)借记卡非封顶交易分润总金额
                            if (sub.Money == 1 && trade_record.BankCardType == 1) editprofitrecord.DebitTradeCapProfit += ProfitMoney; //借记卡封顶交易分润总金额
                            if (sub.Money < 1 && DirectFlag == 1 && trade_record.BankCardType == 1) editprofitrecord.DebitCapSingleReward += ProfitMoney; //借记卡合伙人直营封顶交易奖励金额

                            if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NotHelpCreditProfitRate = sub.ProfitRate; //(非扶持期)(非云闪付)贷记卡商户交易对应分润比例
                            if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NotHelpCreditProfitStandardRate = sub.ProfitPercent; //(非扶持期)(非云闪付)贷记卡标准分润比例
                            if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.NotHelpCreditAddOrSubRate = sub.AddOrSubRate; //(非扶持期)(非云闪付)贷记卡成本或增或减比例
                            if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.HelpCreditProfitRate = sub.ProfitRate; //(扶持期)(非云闪付)贷记卡商户交易对应分润比例
                            if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.HelpCreditProfitStandardRate = sub.ProfitPercent; //(扶持期)(非云闪付)贷记卡-标准分润比例
                            if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 0) editprofitrecord.HelpCreditAddOrSubRate = sub.AddOrSubRate; //(扶持期)(非云闪付)贷记卡成本或增或减比例
                            if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NotHelpDebitProfitRate = sub.ProfitRate; //(非扶持期)(非云闪付)借记卡商户交易对应分润比例
                            if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NotHelpDebitProfitStandardRate = sub.ProfitPercent; //(非扶持期)(非云闪付)借记卡标准分润比例
                            if (trade_record.MerHelpFlag == 0 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.NotHelpDebitAddOrSubRate = sub.AddOrSubRate; //(非扶持期)(非云闪付)借记卡成本或增或减比例
                            if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.HelpDebitProfitRate = sub.ProfitRate; //(扶持期)(非云闪付)借记卡商户交易对应分润比例
                            if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.HelpDebitProfitStandardRate = sub.ProfitPercent; //(扶持期)(非云闪付)借记卡-标准分润比例
                            if (trade_record.MerHelpFlag == 1 && trade_record.QrPayFlag == 0 && trade_record.BankCardType == 1) editprofitrecord.HelpDebitAddOrSubRate = sub.AddOrSubRate; //(扶持期)(非云闪付)借记卡成本或增或减比例
                            if (trade_record.QrPayFlag == 1 && trade_record.BankCardType == 0) editprofitrecord.QrCreditProfitRate = sub.ProfitRate; //(云闪付)贷记卡交易分润比例
                            if (trade_record.QrPayFlag == 1 && trade_record.BankCardType == 0) editprofitrecord.QrCreditProfitStandardRate = sub.ProfitRateBase; //(云闪付)贷记卡分润基准
                            editprofitrecord.QrCreditAddOrSubRate = sub.AddOrSubRate; //(云闪付)贷记卡分润比例或增或减
                            if (sub.Money < 1 && trade_record.QrPayFlag == 1 && trade_record.BankCardType == 1) editprofitrecord.QrDebitProfitRate = sub.ProfitRate; //(云闪付)借记卡非封顶交易分润比例
                            if (sub.Money < 1 && trade_record.QrPayFlag == 1 && trade_record.BankCardType == 1) editprofitrecord.QrDebitProfitStandardRate = sub.ProfitRateBase; //(云闪付)借记卡非封顶交易分润基准
                            if (sub.Money < 1 && trade_record.QrPayFlag == 1 && trade_record.BankCardType == 1) editprofitrecord.QrDebitAddOrSubRate = sub.AddOrSubRate; //(云闪付)借记卡非封顶交易分润比例或增或减
                            dbnew.SaveChanges();

                            dbnew.ProfitRecord.Add(new ProfitRecord()
                            {
                                CreateDate = DateTime.Now,
                                UpdateDate = DateTime.Now,
                                UserId = sub.UserId, //创客
                                MerchantId = trade_record.MerchantId, //商户
                                MerNo = trade_record.MerNo, //渠道商户编号
                                MerHelpFlag = trade_record.MerHelpFlag, //是否属于扶持周期内商户
                                HelpMonthCount = trade_record.HelpMonthCount, //扶持第几个月
                                MerBuddyType = trade_record.MerBuddyType, //商户创客类型
                                SnNo = trade_record.SnNo, //SN号
                                TradeDate = trade_record.TradeDate, //交易日期
                                ProfitAmount = sub.Money, //分润金额
                                QrPayFlag = trade_record.QrPayFlag, //云闪付标识
                                CapFlag = trade_record.CapFlag, //借记卡封顶交易标志
                                DirectFlag = trade_record.DirectFlag, //是否直营
                                BrandId = trade_record.BrandId, //品牌
                                ParentNav = us.ParentNav, //上级创客集
                                TradeId = trade_record.Id, //交易记录Id
                            });
                            dbnew.SaveChanges();

                            // Users user = dbnew.Users.FirstOrDefault(m => m.Id == sub.UserId);
                            // if (user != null)
                            // {
                                // if (!string.IsNullOrEmpty(user.CloudPushDeviceId))
                                // {
                                //     new AliyunPushOld().Push("鑫创客通知", "您有一笔分润收益：" + sub.Money.ToString("f2"), "30", "NOTICE", user.DeviceType, user.CloudPushDeviceId, "1");
                                // }
                                // TODO:发送阿里云推送消息
                            // }
                        }
                    }
                    dbnew.SaveChanges();
                    tran.Commit();
                }
                catch (Exception ex)
                { 
                    tran.Rollback();
                    LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "POS分润异常");
                }
            }
        }

        #endregion
        
        #region POS分润算法
        public List<ProfitResult> StartProftForPos(WebCMSEntities dbnew, TradeRecord trade, List<ProfitUsers> users)
        {
            // 级差
            /*   
                
                K1 - K5：无大小市场要求，无押机分润比例为有押金机的70%，如K1的有押金机分润比例为万6，则无押机的分润比例为万4.2
                                      机具激活大于90天，分润比例为原比例的70%

                        if(is0y){
                            分润比例为原比例的70%
                        }
                        if(ActivityDate > now - 90){
                            分润比例为原比例的70%
                        }
                K6 - K9：
                    K6：至少有1个直推大于3000万，且总交易额减去3000万大于1200万，则获得分红奖（月月红）直接级差
                    K7：总交易额减去最大交易额的直推，大于4000万，则获得分红奖（月月红）直接级差
                    K8：总交易额减去最大交易额的直推，大于12000万，则获得分红奖（月月红）直接级差
                    K9：总交易额减去最大交易额的直推，大于32000万，则获得分红奖（月月红）直接级差

                补贴：
                    0押金无补贴
                    机具激活90天内，机具所属创客获得万10置顶
                    若创客为商户型创客，则机具UserId的创客获得万4分润

            */


            List<ProfitResult> result = new List<ProfitResult>();
            int BrandId = trade.BrandId;
            ProfitObjects obj = RedisDbconn.Instance.Get<ProfitObjects>("pobj" + BrandId);
            if (obj.Status == 1) //判断分润是否开启
            {
                decimal TradeMoney = trade.TradeAmount;
                int BankCardType = trade.BankCardType; //银行卡类型：贷记卡-1，借记卡-0
                int MerHelpFlag = (int)trade.MerHelpFlag; //扶持期-1，稳定期=0
                List<UserLevelSet> levels = dbnew.UserLevelSet.ToList();
                int IncludeCurrentMonth = int.Parse(RedisDbconn.Instance.Get<string>("pobjrule:" + trade.BrandId + ":HelpPolicy:IncludeCurrentMonth")); //是否包含当前月
                int NaturalMonth = int.Parse(RedisDbconn.Instance.Get<string>("pobjrule:" + trade.BrandId + ":HelpPolicy:NaturalMonth")); //自然月
                if(IncludeCurrentMonth == 1) NaturalMonth -= 1;
                if (BankCardType == 0)
                {
                    Users user = dbnew.Users.FirstOrDefault(m => m.Id == trade.UserId) ?? new Users();
                    // UserProfitSet profitSet = profitSet = dbnew.UserProfitSet.FirstOrDefault(m => m.UserId == user.Id && m.BrandId == BrandId && m.CardType == BankCardType && m.HelpFlag == MerHelpFlag) ?? new UserProfitSet(); //获取创客分润规则-扶持期
                    // profitrate = profitSet.ProfitRate;
                    // profitrate = profitrate / 100;
                    int UserLevel = user.UserLevel; //当前会员等级
                    int HelpTime = 0;
                    if (user.CreateDate.Value.AddMonths(NaturalMonth) > DateTime.Now)
                    {
                        HelpTime = 1;
                    }
                    int LevelKindId = GetLevelKindId(trade.BrandId, HelpTime, BankCardType);
                    ProfitObjectLevels objlevel = RedisDbconn.Instance.Get<ProfitObjectLevels>("pobjlv" + LevelKindId + ":" + UserLevel); //获取当前等级参数
                    decimal getLevelProfit = TradeMoney * objlevel.Percents;
                    if(getLevelProfit > 1) getLevelProfit = 1;
                    result.Add(new ProfitResult()
                    {
                        UserId = user.Id,
                        UserNav = user.ParentNav,
                        Money = getLevelProfit,
                        ProfitRate = objlevel.Percents,
                        // ProfitPercent = profitSet.ProfitPercent,
                        // AddOrSubRate = profitSet.AddOrSubRate,
                        // ProfitRateBase = profitSet.ProfitRateBase,
                    });
                    return result;
                }
                int maxLevel = obj.MaxLevel; //最大等级
                int maxFloor = obj.MaxFloor; //最大层级
                int maxContinueFloor = RedisDbconn.Instance.Get<int>("pobjconc" + BrandId); //最大继续分润层级
                decimal diffLevelProfit = 0;  //等级级差
                decimal diffDiviProfit = 0; //分红级差
                // decimal diffFloorProfit = 0;  //层级级差
                // int continueFloor = 0; //继续分润层级
                int curLevel = 0; //当前层级的会员等级
                for (int curFloor = 1; curFloor <= users.Count; curFloor++)
                {
                    ProfitUsers user = new ProfitUsers();
                    if (curFloor <= users.Count)
                    {
                        user = users[curFloor - 1];
                    }
                    int UserLevel = user.UserLevel; //当前会员等级
                    //判断当前创客是否有直推的激活机具，并且在活动时间内
                    if (UserLevel == maxLevel && UserLevel == curLevel)
                    {
                        break;
                    }
                    if (UserLevel <= maxLevel && UserLevel > curLevel)
                    {
                        int HelpTime = 0;
                        if (user.CreateDate.AddMonths(NaturalMonth) > DateTime.Now)
                        {
                            HelpTime = 1;
                        }
                        int LevelKindId = GetLevelKindId(trade.BrandId, HelpTime, BankCardType);
                        ProfitObjectLevels objlevel = RedisDbconn.Instance.Get<ProfitObjectLevels>("pobjlv" + LevelKindId + ":" + UserLevel); //获取当前等级参数
                        if (objlevel != null)
                        {
                            decimal getLevelProfit = 0;  //等级分润
                            // UserProfitSet profitSet = new UserProfitSet();
                            if (objlevel.Percents > 0)
                            {
                                //获取创客分润规则，注册日开始算起，3个自然月内算扶持期
                                decimal profitrate = objlevel.Percents;
                                // profitSet = dbnew.UserProfitSet.FirstOrDefault(m => m.UserId == user.UserId && m.BrandId == BrandId && m.CardType == BankCardType && m.HelpFlag == MerHelpFlag) ?? new UserProfitSet(); //获取创客分润规则-扶持期
                                // profitrate = profitSet.ProfitRate;
                                // profitrate = profitrate / 100;
                                getLevelProfit += TradeMoney * objlevel.Percents * profitrate;
                            }
                            if (objlevel.AddProfitVal > 0)
                            {
                                //分红奖励:一个3000万，3000万以下市场总和大于1200万
                                bool bigMarket = false;
                                decimal smallMarket = 0;
                                List<Users> directs = dbnew.Users.Where(m => m.ParentUserId == user.UserId).ToList();
                                decimal BigMarketTradeAmt = int.Parse(RedisDbconn.Instance.Get<string>("pobjrule:" + trade.BrandId + ":Dividends:BigMarketTradeAmt")); //大市场交易额
                                decimal PassTradeAmt = int.Parse(RedisDbconn.Instance.Get<string>("pobjrule:" + trade.BrandId + ":Dividends:PassTradeAmt")); //小市场交易超越额
                                decimal UnitPrize = int.Parse(RedisDbconn.Instance.Get<string>("pobjrule:" + trade.BrandId + ":Dividends:UnitPrize")); //单位奖励基数
                                foreach (Users direct in directs)
                                {
                                    UserData userData = dbnew.UserData.FirstOrDefault(m => m.UserId == direct.Id) ?? new UserData();
                                    if (userData.TotalOrderMoney >= BigMarketTradeAmt)
                                    {
                                        bigMarket = true;
                                    }
                                    else
                                    {
                                        smallMarket += userData.TotalOrderMoney;
                                    }
                                }
                                if (bigMarket && smallMarket >= PassTradeAmt)
                                { 
                                    decimal DiviPrize = objlevel.AddProfitVal * TradeMoney / UnitPrize;
                                    decimal checkmoney = DiviPrize;
                                    DiviPrize -= diffDiviProfit;
                                    if (objlevel.LevelDiff == 1)  //判断是否有级差
                                    {
                                        diffDiviProfit = checkmoney;
                                    }
                                    if (DiviPrize >= obj.MinProfitVal)
                                    {
                                        result.Add(new ProfitResult()
                                        {
                                            UserId = user.UserId,
                                            UserNav = user.UserNav,
                                            Money = DiviPrize,
                                            Message = "分红奖励",
                                        });
                                    }
                                }
                            }
                            decimal money = getLevelProfit;
                            getLevelProfit -= diffLevelProfit;
                            if (objlevel.LevelDiff == 1)  //判断是否有级差
                            {
                                diffLevelProfit = money;
                            }
                            if (getLevelProfit >= obj.MinProfitVal)
                            {
                                result.Add(new ProfitResult()
                                {
                                    UserId = user.UserId,
                                    UserNav = user.UserNav,
                                    Money = getLevelProfit,
                                    ProfitRate = objlevel.Percents,
                                    // ProfitPercent = profitSet.ProfitPercent,
                                    // AddOrSubRate = profitSet.AddOrSubRate,
                                    // ProfitRateBase = profitSet.ProfitRateBase,
                                });
                            }
                        }
                    }
                    curLevel = UserLevel;
                }
            }
            return result;
        }
        public void StatProfit()
        {
            Thread th = new Thread(StatProfitDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StatProfitDo()
        {
            string Month = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            string check = function.ReadInstance("/ProfitStat/" + Month + ".txt");
            if (!string.IsNullOrEmpty(check))
            {
                return;
            }
            function.WritePage("/ProfitStat/", Month + ".txt", DateTime.Now.ToString());
            WebCMSEntities db = new WebCMSEntities();
            for (int i = 1; i <= 9; i++) //品牌
            {
                for (int j = 0; j <= 1; j++) //卡类型
                {
                    int PageNum = 1;
                    bool op = true;
                    while(op)
                    {
                        List<ProfitResult> result = StartProftForPosByMonth(i, j, Month, PageNum);
                        if(result.Count > 0)
                        {
                            foreach (ProfitResult sub in result)
                            {
                                int TopUserId = 0;
                                if (!string.IsNullOrEmpty(sub.UserNav))
                                {
                                    string[] UserNavList = sub.UserNav.Trim(',').Replace(",,", ",").Split(',');
                                    if (UserNavList.Length > 1)
                                    {
                                        TopUserId = int.Parse(UserNavList[1]);
                                    }
                                    else
                                    {
                                        TopUserId = int.Parse(UserNavList[0]);
                                    }
                                }
                                string RecordNo = "P" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
                                decimal ProfitAmt = sub.Money;
                                decimal TradeAmt = sub.TradeAmount;
                                decimal ProfitRate = sub.ProfitRate;
                                if (sub.IsSubsidy == 1 && j == 1)
                                {
                                    decimal CreditTradeAmt = TradeAmt; //商户贷记卡交易总金额
                                    decimal QrCreditTradeAmt = 0; //商户(云闪付)贷记卡交易总金额
                                    decimal NonQrCreditTradeAmt = 0; //商户(非云闪付)贷记卡交易总金额
                                    decimal CreditProfitRate = 0; //(非云闪付)贷记卡交易分润比例
                                    decimal SubsidyProfit = 0; //商户(非云闪付)贷记卡交易分润补贴金额
                                    if (sub.QrPayFlag == 1)
                                    {
                                        QrCreditTradeAmt = TradeAmt; //商户(云闪付)贷记卡交易总金额
                                    }
                                    else
                                    { 
                                        NonQrCreditTradeAmt = TradeAmt; //商户(非云闪付)贷记卡交易总金额
                                        CreditProfitRate = ProfitRate; //(非云闪付)贷记卡交易分润比例
                                        SubsidyProfit = ProfitAmt; //商户(非云闪付)贷记卡交易分润补贴金额
                                    }
                                    MachineForSnNo forSnNo = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == sub.PosSn) ?? new MachineForSnNo();
                                    PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == forSnNo.SnId) ?? new PosMachinesTwo(); 
                                    PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == sub.MerchantId) ?? new PosMerchantInfo();
                                    db.ProfitSubsidyDetail.Add(new ProfitSubsidyDetail()
                                    {
                                        CreateDate = DateTime.Now,
                                        UpdateDate = DateTime.Now,
                                        RecordNo = RecordNo, //流水号
                                        BrandId = sub.BrandId, //品牌
                                        ProductName = RelationClass.GetKqProductBrandInfo(sub.BrandId), //产品名称
                                        TradeMonth = Month, //交易月份
                                        MerchantId = sub.MerchantId, //商户
                                        MerNo = merchant.KqMerNo, //渠道商户编号
                                        SnNo = sub.PosSn, //渠道SN号
                                        MerRegTime = pos.BindingTime, //渠道注册时间
                                        MerStandardDate = merchant.MerStandardDate, //商户激活时间
                                        BelongUserId = merchant.UserId, //商户归属人
                                        MerHelpFlag = sub.HelpFlag == 1 ? 1u : 0u, //是否属于扶持周期内商户
                                        SubsidyUserId = sub.UserId, //补贴人
                                        SubsidyType = sub.DirectFlag, //分润补贴类型
                                        SubsidyProfitRate = sub.Money, //创客活动期内直营商户分润万分之十
                                        CreditTradeAmt = CreditTradeAmt, //商户贷记卡交易总金额
                                        QrCreditTradeAmt = QrCreditTradeAmt, //商户(云闪付)贷记卡交易总金额
                                        NonQrCreditTradeAmt = NonQrCreditTradeAmt, //商户(非云闪付)贷记卡交易总金额
                                        CreditProfitRate = CreditProfitRate, //(非云闪付)贷记卡交易分润比例
                                        SubsidyProfit = SubsidyProfit, //商户(非云闪付)贷记卡交易分润补贴金额
                                    });
                                }
                            }
                            db.SaveChanges();
                            PageNum += 1;
                        }
                        else
                        {
                            op = false;
                        }
                    }
                }
            }
            db.Dispose();

            HelpProfitHelper.Instance.StatProfitEveryDay(DateTime.Now.AddMonths(-1).ToString("yyyyMM")); //助利宝分润
            ProfitCheckHelper.Instance.Start();
        }
        public List<ProfitResult> StartProftForPosByMonth(int BrandId, int BankCardType, string Month, int PageNum = 1)
        {
            // 级差
            /*   
                
                K1 - K5：无大小市场要求，无押机分润比例为有押金机的70%，如K1的有押金机分润比例为万6，则无押机的分润比例为万4.2
                                      机具激活大于90天，分润比例为原比例的70%

                        if(is0y){
                            分润比例为原比例的70%
                        }
                        if(ActivityDate > now - 90){
                            分润比例为原比例的70%
                        }
                K6 - K9：
                    K6：至少有1个直推大于3000万，且总交易额减去3000万大于1200万，则获得分红奖（月月红）直接级差
                    K7：总交易额减去最大交易额的直推，大于4000万，则获得分红奖（月月红）直接级差
                    K8：总交易额减去最大交易额的直推，大于12000万，则获得分红奖（月月红）直接级差
                    K9：总交易额减去最大交易额的直推，大于32000万，则获得分红奖（月月红）直接级差

                补贴：
                    0押金无补贴
                    机具激活90天内，机具所属创客获得万10置顶
                    若创客为商户型创客，则机具UserId的创客获得万4分润

                    //查分润
                    select u.MakerCode,u.RealName,u.UserLevel,r.Rank,pos.SeoKeyword,p.KqSnNo,(case when ProfitType=1 then '直营' else '团队' end) as DirectFlag,
                    k.Name,CreditTradeAmt,CreditTradeProfit,DebitTradeAmt,DebitTradeProfit,QrCreditTradeAmt,QrCreditTradeProfit from (
                    select UserId,ProfitType,BrandId,MerchantId,
                    sum(CreditTradeAmt) as CreditTradeAmt,
                    sum(CreditTradeProfit) as CreditTradeProfit,
                    sum(DebitNonCapTradeAmt+DebitCapTradeAmt) as DebitTradeAmt,
                    sum(DebitNonTradeCapProfit+DebitTradeCapProfit) as DebitTradeProfit,
                    sum(QrCreditTradeAmt) as QrCreditTradeAmt,
                    sum(QrCreditTradeProfit) as QrCreditTradeProfit
                    from ProfitRewardRecord where MerchantId>0
                    GROUP BY UserId,ProfitType,BrandId,MerchantId
                    ) tb 
                    left join Users u on tb.UserId=u.Id 
                    LEFT JOIN KqProducts k ON k.Id=tb.BrandId 
                    left join PosMerchantInfo p on tb.MerchantId=p.Id 
                    left join MachineForSnNo fp on fp.SnNo=p.KqSnNo 
                    left join PosMachinesTwo pos on pos.Id=fp.SnId 
                    left join UserRankWhite r on u.Id=r.Id 
                    ORDER BY p.KqSnNo,u.MakerCode

                    //查补贴
                    select u.MakerCode,u.RealName,u.UserLevel,r.Rank,m.KqSnNo,m.MerchantName,(case when SubsidyType=1 then '直营' else '团队' end) as DirectFlag,
                    k.Name,CreditTradeAmt,SubsidyProfit from (
                    select SubsidyUserId,MerchantId,BrandId,SubsidyType,
                    sum(CreditTradeAmt) as CreditTradeAmt,
                    sum(SubsidyProfitRate) as SubsidyProfit
                    from ProfitSubsidyDetail where TradeMonth='202208' 
                    GROUP BY SubsidyUserId,MerchantId,BrandId,SubsidyType
                    ) tb 
                    left join Users u on tb.SubsidyUserId=u.Id 
                    LEFT JOIN KqProducts k ON k.Id=tb.BrandId 
                    left join PosMerchantInfo m on tb.MerchantId=m.Id 
                    left join UserRankWhite r on u.Id=r.Id and r.CreateDate<'2022-09-01 00:00:00' and r.UpdateDate>'2022-09-01 00:00:00'

                    // TODO:做到后台查询，换绑机器遗漏交易额补差
                    select UserId,sum(TradeAmount) from TradeRecord where SnNo in (
                    select PosSn from PosMachinesTwo where UserId=0 and BuyUserId=0 and CreditTrade>0
                    ) and CreateDate>='2022-04-01 00:00:00' and CreateDate<'2022-05-01 00:00:00' and UserId>0 group by UserId

            */

            int PageSize = 200;
            int SkipNum = (PageNum - 1) * PageSize;
            string LimitString = " limit " + PageSize;
            if(PageNum > 1)
            {
                LimitString = " limit " + SkipNum + "," + PageSize;
            }
            LogHelper.Instance.WriteLog(DateTime.Now.ToString(), "老规则分润日志");
            LogHelper.Instance.WriteLog(BankCardType.ToString(), "老规则分润日志");
            LogHelper.Instance.WriteLog(BrandId.ToString(), "老规则分润日志");
            List<ProfitResult> result = new List<ProfitResult>();
            ProfitObjects obj = RedisDbconn.Instance.Get<ProfitObjects>("pobj" + BrandId);
            if (obj.Status == 1) //判断分润是否开启
            {
                string start = Month.Substring(0, 4) + "-" + Month.Substring(4, 2) + "-01 00:00:00";
                string end = DateTime.Parse(start).AddMonths(1).ToString("yyyy-MM-dd HH:mm:ss");
                DataTable dt = new DataTable();
                if (BankCardType == 1)
                {
                    dt = ProfitHelperV2.Instance.GetDataTable("select SnNo,UserId,QrPayFlag,MerHelpFlag,TradeAmount,Version from TradeRecord" + Month + " where MerHelpFlag=1 and Version=0 and BrandId=" + BrandId + LimitString);
                }
                LogHelper.Instance.WriteLog("记录页数：" + PageNum.ToString(), "老规则分润日志");
                LogHelper.Instance.WriteLog("记录条数：" + dt.Rows.Count.ToString(), "老规则分润日志");
                foreach (DataRow dr in dt.Rows)
                {
                    WebCMSEntities dbnew = new WebCMSEntities();
                    try
                    {
                        string SnNo = dr["SnNo"].ToString();
                        int UserId = int.Parse(dr["UserId"].ToString());
                        int HelpTime = int.Parse(dr["Version"].ToString()) == 1 ? 2 : int.Parse(dr["MerHelpFlag"].ToString());
                        LogHelper.Instance.WriteLog("SnNo:" + SnNo, "老规则分润日志");
                        LogHelper.Instance.WriteLog("UserId:" + UserId, "老规则分润日志");
                        LogHelper.Instance.WriteLog("HelpTime:" + HelpTime, "老规则分润日志");
                        MachineForSnNo forSnNo = dbnew.MachineForSnNo.FirstOrDefault(m => m.SnNo == SnNo) ?? new MachineForSnNo();
                        PosMachinesTwo pos = dbnew.PosMachinesTwo.FirstOrDefault(m => m.Id == forSnNo.SnId) ?? new PosMachinesTwo();
                        decimal Deposit = decimal.Parse(function.CheckNum(pos.SeoKeyword));
                        if (pos.BindingState == 1)
                        {
                            LogHelper.Instance.WriteLog("BindingState:" + pos.BindingState, "老规则分润日志");
                            int QrPayFlag = int.Parse(dr["QrPayFlag"].ToString());
                            decimal TradeAmt = decimal.Parse(dr[4].ToString());
                            List<UserLevelSet> levels = dbnew.UserLevelSet.ToList();
                            SubUser selfUser = ProfitHelperV2.Instance.GetUser(UserId, Month) ?? new SubUser();
                            int Days = int.Parse(RedisDbconn.Instance.Get<string>("pobjrule:" + BrandId + ":HelpPolicy:Days")); //天数
                            if (BankCardType == 0)
                            {
                            }
                            else
                            {
                                int maxLevel = obj.MaxLevel; //最大等级
                                decimal diffLevelProfit = 0;  //等级级差
                                int curLevel = 0; //当前层级的会员等级
                                string ParentNav = selfUser.ParentNav;
                                if (string.IsNullOrEmpty(ParentNav) && pos.BuyUserId == 1 && pos.UserId == 1)
                                {
                                    ParentNav = ",0,";
                                }
                                if (!string.IsNullOrEmpty(ParentNav))
                                {
                                    ParentNav += "," + UserId + ",";
                                    string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                                    Array.Reverse(ParentNavList); //反转顺序
                                    int level = 0;
                                    DateTime now = DateTime.Now;
                                    DateTime ThisMonth = DateTime.Parse(DateTime.Now.ToString("yyyy-MM") + "-01 00:00:00");
                                    foreach (string UserIdString in ParentNavList)
                                    {
                                        level += 1;
                                        int uid = int.Parse(UserIdString);
                                        SubUser user = ProfitHelperV2.Instance.GetUser(uid, Month) ?? new SubUser();
                                        int UserLevel = user.PreUserLevel > user.UserLevel ? user.PreUserLevel : user.UserLevel; //当前会员等级
                                        if (curLevel == maxLevel) //判断当前创客是否有直推的激活机具，并且在活动时间内
                                        {
                                            break;
                                        }
                                        if (UserLevel <= maxLevel && UserLevel > curLevel)
                                        {
                                            LogHelper.Instance.WriteLog("UserLevel:" + UserLevel, "老规则分润日志");
                                            LogHelper.Instance.WriteLog("curLevel:" + curLevel, "老规则分润日志");
                                            int LevelKindId = GetLevelKindId(BrandId, HelpTime, 1);
                                            ProfitObjectLevels objlevel = RedisDbconn.Instance.Get<ProfitObjectLevels>("pobjlv" + LevelKindId + ":" + UserLevel); //获取当前等级参数
                                            if (objlevel != null)
                                            {
                                                decimal getLevelProfit = 0;  //等级分润
                                                if (objlevel.Percents > 0)
                                                {
                                                    //获取创客分润规则，注册日开始算起，3个自然月内算扶持期
                                                    getLevelProfit += TradeAmt * objlevel.Percents;
                                                }
                                                if (objlevel.AddProfitVal > 0)
                                                {
                                                    getLevelProfit += objlevel.AddProfitVal;
                                                }
                                                decimal money = getLevelProfit;
                                                getLevelProfit -= diffLevelProfit;
                                                if (objlevel.LevelDiff == 1)  //判断是否有级差
                                                {
                                                    diffLevelProfit = money;
                                                }

                                                // 分润补贴
                                                if (HelpTime == 1 && level == 1)
                                                {
                                                    LogHelper.Instance.WriteLog("ok", "老规则分润日志");
                                                    int SubsidyUserId = pos.BuyUserId;
                                                    SubUser subuser = ProfitHelperV2.Instance.GetUser(SubsidyUserId, Month) ?? new SubUser();
                                                    int subUserLevel = subuser.PreUserLevel > subuser.UserLevel ? subuser.PreUserLevel : subuser.UserLevel;
                                                    LogHelper.Instance.WriteLog("subUserLevel:" + subUserLevel, "老规则分润日志");
                                                    if(subUserLevel < 5)
                                                    {
                                                        LogHelper.Instance.WriteLog("sub:ok:", "老规则分润日志");
                                                        ProfitObjectLevels sublevel = RedisDbconn.Instance.Get<ProfitObjectLevels>("pobjlv" + LevelKindId + ":" + subUserLevel); //获取当前等级参数
                                                        if (sublevel != null)
                                                        {
                                                            decimal otherPercent = 0.001M - sublevel.Percents;
                                                            decimal otherMoney = TradeAmt * otherPercent;
                                                            LogHelper.Instance.WriteLog("otherPercent:" + otherPercent, "老规则分润日志");
                                                            LogHelper.Instance.WriteLog("otherMoney:" + otherMoney, "老规则分润日志");
                                                            if (otherMoney >= obj.MinProfitVal)
                                                            {
                                                                LogHelper.Instance.WriteLog("finish:" + SnNo, "老规则分润日志");
                                                                result.Add(new ProfitResult()
                                                                {
                                                                    UserId = subuser.Id,
                                                                    UserNav = subuser.ParentNav,
                                                                    Money = PublicFunction.NumberFormat(otherMoney),
                                                                    ProfitRate = otherPercent,
                                                                    Message = "分润补贴",
                                                                    BankCardType = BankCardType,
                                                                    QrPayFlag = QrPayFlag,
                                                                    DirectFlag = 1,
                                                                    BrandId = pos.BrandId,
                                                                    IsSubsidy = 1,
                                                                    MerchantId = pos.BindMerchantId,
                                                                    TradeAmount = TradeAmt,
                                                                    HelpFlag = HelpTime,
                                                                    PosSn = pos.PosSn,
                                                                });
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        curLevel = UserLevel;
                                    }
                                }
                            }
                        }
                        LogHelper.Instance.WriteLog("\n\n", "老规则分润日志");
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "每月统计分润异常");
                    }
                    dbnew.Dispose();
                }
            }
            LogHelper.Instance.WriteLog(DateTime.Now.ToString(), "老规则分润日志");
            LogHelper.Instance.WriteLog("\r\n\r\n", "老规则分润日志");
            return result;
        }
        #endregion







        public void StartSetDivi()
        {
            Thread th = new Thread(StartSetDiviDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StartSetDiviDo()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("ConsumerOrdersSetDivi");
                if (!string.IsNullOrEmpty(content))
                {
                    SetDivi(content);
                }
                else
                {
                    Thread.Sleep(10000);
                }
            }
        }

        public void SetDivi(string content)
        { 
            try
            {
                JsonData jsonObj = JsonMapper.ToObject(content);
                int orderId = int.Parse(function.CheckInt(jsonObj["OrderId"].ToString()));
                decimal diviAmt = decimal.Parse(function.CheckNum(jsonObj["DiviAmt"].ToString()));
                WebCMSEntities db = new WebCMSEntities();
                ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == orderId);
                if(order != null)
                {
                    order.CurDivi = diviAmt;
                    db.SaveChanges();
                }
                db.Dispose();
            }
            catch(Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "设置订单当前返现金额异常");
            }
        }

    }
}