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

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


        public void Start()
        {
            Thread th = new Thread(ready);
            th.IsBackground = true;
            th.Start();
        }
        
        private void ready()
        { 
            bool op = true;
            while (op)
            {
                string content = RedisDbconn.Instance.RPop<string>("PosCouponPrizeQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    try
                    {
                        dosomething(int.Parse(function.CheckInt(content)));
                    }
                    catch(Exception ex)
                    {
                        Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "商城下单机具券发奖异常");
                    }
                }
                else
                {
                    Thread.Sleep(2000);
                }
            }
        }

        public void dosomething(int OrderId)
        { 
            WebCMSEntities db = new WebCMSEntities();
            OpModels.WebCMSEntities opdb = new OpModels.WebCMSEntities();
            Orders order = db.Orders.FirstOrDefault(m => m.Id == OrderId);
            if(order != null)
            {
                List<int> ChkIds = new List<int>(); //机具券商品Id集合
                ChkIds.Add(10);
                ChkIds.Add(11);
                ChkIds.Add(77);
                ChkIds.Add(78);
                ChkIds.Add(79);
                ChkIds.Add(92);
                Utils.Instance.PrizeRecord(2, order.OrderNo, "条件:商品id是（10,11,77,78,79,91）;当前订单商品Id:" + order.ProductId + "");
                //判断是否是指定商品
                if(ChkIds.Contains(order.ProductId))
                {
                    Utils.Instance.PrizeRecord(2, order.OrderNo, "满足条件");
                    int Kind = 0;
                    if (order.ProductId == 10)
                    {
                        Kind = 1;
                    }
                    else if (order.ProductId == 11)
                    {
                        Kind = 2;
                    }
                    int CouponCount = 0;
                    if(Kind == 1)
                    {
                        CouponCount = 3 * order.BuyCount;
                    }
                    else if(Kind == 2)
                    {
                        CouponCount = 2 * order.BuyCount;
                    }


                    UserRankItem orderUser = GetUserLevel(order.UserId, false);
                    if(orderUser.UserLevel == 0) 
                    {
                        PreUserLevel(db, order.UserId, 1, DateTime.Parse("2025-01-01 00:00:00"));
                    }
                    List<string> codes = function.CheckNull(order.SnNos).Split(',').ToList();
                    string ParentNav = orderUser.ParentNav + "," + orderUser.Id + ",";
                    string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                    Array.Reverse(ParentNavList);
                    int index = 0;
                    bool DirectPrizeFlag = false; //推荐奖励发放标识
                    int BuyPrizeFlag = 0; //购机奖励发放标识
                    bool BackAccountFlag = false; //备用金返余额标识
                    bool BigLeaderFlag = false; //大盟主标记
                    decimal BuyPrize = 0; //购机奖励
                    Utils.Instance.PrizeRecord(2, order.OrderNo, "开始向上递归查找");
                    foreach(string ParentId in ParentNavList)
                    {
                        UserRankItem parentUser = GetUserLevel(int.Parse(ParentId), index > 0);
                        if(parentUser.Id > 0)
                        {
                            Utils.Instance.PrizeRecord(2, order.OrderNo, "创客编号:" + parentUser.MakerCode + ";创客姓名:" + parentUser.RealName + ";");
                            index += 1;
                            if(index == 1)
                            {
                                Utils.Instance.PrizeRecord(2, order.OrderNo, "条件:下单人是盟主;下单人盟主等级:" + orderUser.LeaderLevel + "");
                                Utils.Instance.PrizeRecord(2, order.OrderNo, "条件:下单人是运营中心或合伙人;下单人合伙人等级:" + orderUser.OperateLevel + "");
                                Utils.Instance.PrizeRecord(2, order.OrderNo, "条件:推荐奖励是否已发放;当前状态:" + DirectPrizeFlag + "");
                            }
                            if(index == 1 && (orderUser.LeaderLevel > 0 || orderUser.OperateLevel > 0) && !DirectPrizeFlag)
                            {
                                Utils.Instance.PrizeRecord(2, order.OrderNo, "满足条件，发放推荐奖励给下单人");
                                DirectPrize(db, order.Id, order.UserId, order.BuyCount);
                                DirectPrizeFlag = true;
                            }
                            if(index > 1)
                            {
                                bool IsStandardUser = Utils.Instance.IsStandardUser(parentUser.Id);
                                Utils.Instance.PrizeRecord(2, order.OrderNo, "条件:上级是有效创客;是否有效创客:" + IsStandardUser + "");
                                Utils.Instance.PrizeRecord(2, order.OrderNo, "条件:推荐奖励是否已发放;当前状态:" + DirectPrizeFlag + "");
                                if(IsStandardUser && !DirectPrizeFlag)
                                {
                                    Utils.Instance.PrizeRecord(2, order.OrderNo, "满足条件，发放推荐奖励给上级");
                                    DirectPrize(db, order.Id, parentUser.Id, order.BuyCount);
                                    DirectPrizeFlag = true;
                                }
                            }
                            Utils.Instance.PrizeRecord(2, order.OrderNo, "条件:创客是盟主;创客盟主等级:" + parentUser.AgoLeaderLevel + "");
                            Utils.Instance.PrizeRecord(2, order.OrderNo, "条件:盟主储备金是否充足;");
                            Utils.Instance.PrizeRecord(2, order.OrderNo, "条件:创客是运营中心或合伙人;合伙人等级:" + parentUser.AgoLeaderLevel + "");
                            Utils.Instance.PrizeRecord(2, order.OrderNo, "条件:合伙人未使用额度是否充足;");
                            if(parentUser.AgoLeaderLevel > 0 && CheckLeaderReserve(db, order.BuyCount, parentUser.Id))
                            {
                                Utils.Instance.PrizeRecord(2, order.OrderNo, "满足条件，发放购机奖");
                                //购机奖
                                if(parentUser.LeaderLevel > 0)
                                {
                                    decimal CurBuyPrize = GetBuyPrize(parentUser, order);
                                    decimal GetPrize = CurBuyPrize - BuyPrize;
                                    Utils.Instance.PrizeRecord(2, order.OrderNo, "发放金额:" + GetPrize);
                                    if(GetPrize > 0 && BuyPrizeFlag < 2)
                                    {
                                        bool PrizeFlag = true;
                                        int ChangeType = 118;
                                        if(parentUser.OperateLevel == 1)
                                        {
                                            ChangeType = 120;
                                        }
                                        if(parentUser.OperateLevel > 1)
                                        {
                                            ChangeType = 128;
                                            if(function.CheckNull(RedisDbconn.Instance.Get<string>("YingXunUser")).Contains("," + orderUser.Id + ","))
                                            {
                                                PrizeFlag = false;
                                            }
                                        }
                                        if(PrizeFlag)
                                        {
                                            OpAccount(db, order.Id, parentUser.Id, CurBuyPrize - BuyPrize, order.BuyCount, ChangeType);
                                            if(GetPrize == 160) BuyPrizeFlag = 2;
                                            else if(GetPrize == 60) BuyPrizeFlag = 2;
                                            else BuyPrizeFlag = 1;
                                        }
                                        BuyPrize = CurBuyPrize;
                                    }
                                    if(parentUser.OperateLevel == 2 && CurBuyPrize == 100) BuyPrizeFlag = 2;
                                }
                                else if(parentUser.OperateLevel > 0 && CheckOpReserve(opdb, order.BuyCount, parentUser.Id) && BuyPrizeFlag < 2)
                                {
                                    Utils.Instance.PrizeRecord(2, order.OrderNo, "满足条件，发放购机奖");
                                    //购机奖
                                    decimal CurBuyPrize = GetBuyPrize(parentUser, order);
                                    decimal GetPrize = CurBuyPrize - BuyPrize;
                                    Utils.Instance.PrizeRecord(2, order.OrderNo, "发放金额:" + GetPrize);
                                    if(GetPrize > 0)
                                    {
                                        int ChangeType = 120;
                                        if(parentUser.OperateLevel > 1)
                                        {
                                            ChangeType = 128;
                                        }
                                        OpAccount(db, order.Id, parentUser.Id, GetPrize, order.BuyCount, ChangeType);
                                        BuyPrize = CurBuyPrize;
                                        if(GetPrize == 160) BuyPrizeFlag = 2;
                                        else if(GetPrize == 60) BuyPrizeFlag = 2;
                                        else BuyPrizeFlag = 1;
                                    }
                                    if(parentUser.OperateLevel == 2 && CurBuyPrize == 100) BuyPrizeFlag = 2; 

                                    if(!BackAccountFlag)
                                    {
                                        BackAccountFlag = true;
                                        decimal GetAmount = GetWithdrawMoney(parentUser) * order.BuyCount;
                                        //扣减备用金
                                        // OperateAmountChange(opdb, parentUser.Id, GetAmount, 2, 1, "商城购机", true, order.Id);
                                        // //返回到余额
                                        // OperateAmountChange(opdb, parentUser.Id, GetAmount, 1, 2, "商城购机", true, order.Id);

                                        OpAmountItem item = new OpAmountItem()
                                        {
                                            UserId = parentUser.Id,
                                            OperateType = 0,
                                            ChangeType = 5,
                                            Remark = "商城购机",
                                            UseAmount = GetAmount,
                                            UseValidForGetAmount = GetAmount,
                                            UseTotalAmt = GetAmount,
                                            DataType = 1,
                                            DataId = order.Id,
                                        };
                                        RedisDbconn.Instance.AddList("OperateAmountRecordServiceQueue", item);
                                    }
                                }

                                if(!BackAccountFlag)
                                {
                                    BackAccountFlag = true;
                                    //扣减备用金
                                    int ReserveRecordId = OpReserve(db, order.Id, parentUser.Id, GetWithdrawMoney(parentUser) * order.BuyCount, 2, order.UserId, "购机奖励");
                                    //返回到余额
                                    OpLeaderAccount(db, order, parentUser.Id, GetWithdrawMoney(parentUser), order.BuyCount, ReserveRecordId);
                                }

                                //给券打大盟主标记
                                Utils.Instance.PrizeRecord(2, order.OrderNo, "条件:创客是盟主;创客盟主等级:" + parentUser.LeaderLevel + "");
                                Utils.Instance.PrizeRecord(2, order.OrderNo, "条件:盟主储备金是否充足;");
                                if(parentUser.LeaderLevel == 1 && CheckLeaderReserve(db, order.BuyCount, parentUser.Id) && !BigLeaderFlag)
                                {
                                    Utils.Instance.PrizeRecord(2, order.OrderNo, "满足小盟主条件，开始检查大盟主关联的额度");
                                    int LeaderId = CheckPosCouponLeaderFlag(db, parentUser.Id, order.BuyCount, codes);
                                    if(LeaderId > 0)
                                    {
                                        BigLeaderFlag = true;
                                        Utils.Instance.PrizeRecord(2, order.OrderNo, "满足条件，大盟主标记打给" + LeaderId);
                                    }
                                }
                                else if(parentUser.LeaderLevel == 2 && !BigLeaderFlag)
                                {
                                    Utils.Instance.PrizeRecord(2, order.OrderNo, "满足大盟主条件，大盟主标记打给" + parentUser.Id + ",对应机具券:" + order.SnNos);
                                    BigLeaderFlag = true;
                                    if(!string.IsNullOrEmpty(order.SnNos))
                                    {
                                        List<int> couponIds = db.PosCoupons.Where(m => codes.Contains(m.ExchangeCode)).OrderBy(m => m.Id).Take(CouponCount).ToList().Select(m => m.Id).ToList();
                                        Utils.Instance.PrizeRecord(2, order.OrderNo, "开始打标记，数量:" + couponIds.Count);
                                        SetPosCouponLeaderFlag(db, parentUser.Id, order.BuyCount, couponIds);
                                        Utils.Instance.PrizeRecord(2, order.OrderNo, "结束打标记");
                                    }
                                }
                            }
                            else if(parentUser.OperateLevel > 0 && CheckOpReserve(opdb, order.BuyCount, parentUser.Id) && BuyPrizeFlag < 2)
                            {
                                Utils.Instance.PrizeRecord(2, order.OrderNo, "满足条件，发放购机奖");
                                //购机奖
                                decimal CurBuyPrize = GetBuyPrize(parentUser, order);
                                decimal GetPrize = CurBuyPrize - BuyPrize;
                                Utils.Instance.PrizeRecord(2, order.OrderNo, "发放金额:" + GetPrize);
                                if(GetPrize > 0)
                                {
                                    int ChangeType = 120;
                                    if(parentUser.OperateLevel > 1)
                                    {
                                        ChangeType = 128;
                                    }
                                    OpAccount(db, order.Id, parentUser.Id, GetPrize, order.BuyCount, ChangeType);
                                    BuyPrize = CurBuyPrize;
                                    if(GetPrize == 160) BuyPrizeFlag = 2;
                                    else if(GetPrize == 60) BuyPrizeFlag = 2;
                                    else BuyPrizeFlag = 1;
                                }
                                if(parentUser.OperateLevel == 2 && CurBuyPrize == 100) BuyPrizeFlag = 2; 

                                if(!BackAccountFlag)
                                {
                                    BackAccountFlag = true;
                                    decimal GetAmount = GetWithdrawMoney(parentUser) * order.BuyCount;
                                    //扣减备用金
                                    // OperateAmountChange(opdb, parentUser.Id, GetAmount, 2, 1, "商城购机", true, order.Id);
                                    // //返回到余额
                                    // OperateAmountChange(opdb, parentUser.Id, GetAmount, 1, 2, "商城购机", true, order.Id);

                                    OpAmountItem item = new OpAmountItem()
                                    {
                                        UserId = parentUser.Id,
                                        OperateType = 0,
                                        ChangeType = 5,
                                        Remark = "商城购机",
                                        UseAmount = GetAmount,
                                        UseValidForGetAmount = GetAmount,
                                        UseTotalAmt = GetAmount,
                                        DataType = 1,
                                        DataId = order.Id,
                                    };
                                    RedisDbconn.Instance.AddList("OperateAmountRecordServiceQueue", item);
                                }
                            }
                        }
                    }

                    //发放奖励MQ
                    PrizeSetHelper.Do("3", order.OrderNo);
                }
            }
            db.Dispose();
            opdb.Dispose();
        }



        public void AddPrize(int OrderId)
        { 
            WebCMSEntities db = new WebCMSEntities();
            OpModels.WebCMSEntities opdb = new OpModels.WebCMSEntities();
            Orders order = db.Orders.FirstOrDefault(m => m.Id == OrderId);
            if(order != null)
            {
                List<int> ChkIds = new List<int>(); //机具券商品Id集合
                ChkIds.Add(10);
                ChkIds.Add(11);
                ChkIds.Add(77);
                ChkIds.Add(78);
                ChkIds.Add(79);
                ChkIds.Add(92);
                
                //判断是否是指定商品
                if(ChkIds.Contains(order.ProductId))
                {
                    
                    int Kind = 0;
                    if (order.ProductId == 10)
                    {
                        Kind = 1;
                    }
                    else if (order.ProductId == 11)
                    {
                        Kind = 2;
                    }
                    int CouponCount = 0;
                    if(Kind == 1)
                    {
                        CouponCount = 3 * order.BuyCount;
                    }
                    else if(Kind == 2)
                    {
                        CouponCount = 2 * order.BuyCount;
                    }


                    UserRankItem orderUser = GetUserLevel(order.UserId, false);
                    if(orderUser.UserLevel == 0) 
                    {
                        PreUserLevel(db, order.UserId, 1, DateTime.Parse("2025-01-01 00:00:00"));
                    }
                    List<string> codes = function.CheckNull(order.SnNos).Split(',').ToList();
                    string ParentNav = orderUser.ParentNav + "," + orderUser.Id + ",";
                    string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                    Array.Reverse(ParentNavList);
                    int index = 0;
                    bool DirectPrizeFlag = false; //推荐奖励发放标识
                    int BuyPrizeFlag = 0; //购机奖励发放标识
                    bool BackAccountFlag = false; //备用金返余额标识
                    bool BigLeaderFlag = false; //大盟主标记
                    decimal BuyPrize = 0; //购机奖励
                    
                    foreach(string ParentId in ParentNavList)
                    {
                        UserRankItem parentUser = GetUserLevel(int.Parse(ParentId), index > 0);
                        if(parentUser.Id > 0)
                        {
                            
                            index += 1;
                            if(index == 1)
                            {
                                
                                
                                
                            }
                            if(index == 1 && (orderUser.LeaderLevel > 0 || orderUser.OperateLevel > 0) && !DirectPrizeFlag)
                            {
                                
                                DirectPrize(db, order.Id, order.UserId, order.BuyCount);
                                DirectPrizeFlag = true;
                            }
                            if(index > 1)
                            {
                                bool IsStandardUser = Utils.Instance.IsStandardUser(parentUser.Id);
                                
                                
                                if(IsStandardUser && !DirectPrizeFlag)
                                {
                                    
                                    DirectPrize(db, order.Id, parentUser.Id, order.BuyCount);
                                    DirectPrizeFlag = true;
                                }
                            }
                            
                            
                            
                            
                            if(parentUser.AgoLeaderLevel > 0 && CheckLeaderReserve(db, order.BuyCount, parentUser.Id))
                            {
                                
                                //购机奖
                                if(parentUser.LeaderLevel > 0)
                                {
                                    decimal CurBuyPrize = GetBuyPrize(parentUser, order);
                                    decimal GetPrize = CurBuyPrize - BuyPrize;
                                    
                                    if(GetPrize > 0 && BuyPrizeFlag < 2)
                                    {
                                        bool PrizeFlag = true;
                                        int ChangeType = 118;
                                        if(parentUser.OperateLevel == 1)
                                        {
                                            ChangeType = 120;
                                        }
                                        if(parentUser.OperateLevel > 1)
                                        {
                                            ChangeType = 128;
                                            if(function.CheckNull(RedisDbconn.Instance.Get<string>("YingXunUser")).Contains("," + orderUser.Id + ","))
                                            {
                                                PrizeFlag = false;
                                            }
                                        }
                                        if(PrizeFlag)
                                        {
                                            OpAccount(db, order.Id, parentUser.Id, CurBuyPrize - BuyPrize, order.BuyCount, ChangeType);
                                            if(GetPrize == 160) BuyPrizeFlag = 2;
                                            else if(GetPrize == 60) BuyPrizeFlag = 2;
                                            else BuyPrizeFlag = 1;
                                        }
                                        BuyPrize = CurBuyPrize;
                                    }
                                    if(parentUser.OperateLevel == 2 && CurBuyPrize == 100) BuyPrizeFlag = 2;
                                }
                                else if(parentUser.OperateLevel > 0 && CheckOpReserve(opdb, order.BuyCount, parentUser.Id) && BuyPrizeFlag < 2)
                                {
                                    
                                    //购机奖
                                    decimal CurBuyPrize = GetBuyPrize(parentUser, order);
                                    decimal GetPrize = CurBuyPrize - BuyPrize;
                                    
                                    if(GetPrize > 0)
                                    {
                                        int ChangeType = 120;
                                        if(parentUser.OperateLevel > 1)
                                        {
                                            ChangeType = 128;
                                        }
                                        OpAccount(db, order.Id, parentUser.Id, GetPrize, order.BuyCount, ChangeType);
                                        BuyPrize = CurBuyPrize;
                                        if(GetPrize == 160) BuyPrizeFlag = 2;
                                        else if(GetPrize == 60) BuyPrizeFlag = 2;
                                        else BuyPrizeFlag = 1;
                                    }
                                    if(parentUser.OperateLevel == 2 && CurBuyPrize == 100) BuyPrizeFlag = 2; 

                                    if(!BackAccountFlag)
                                    {
                                        BackAccountFlag = true;
                                        decimal GetAmount = GetWithdrawMoney(parentUser) * order.BuyCount;
                                        OpAmountItem item = new OpAmountItem()
                                        {
                                            UserId = parentUser.Id,
                                            OperateType = 0,
                                            ChangeType = 5,
                                            Remark = "商城购机",
                                            UseAmount = GetAmount,
                                            UseValidForGetAmount = GetAmount,
                                            UseTotalAmt = GetAmount,
                                            DataType = 1,
                                            DataId = order.Id,
                                        };
                                        RedisDbconn.Instance.AddList("OperateAmountRecordServiceQueue", item);
                                    }
                                }

                                if(!BackAccountFlag)
                                {
                                    BackAccountFlag = true;
                                    //扣减备用金
                                    int ReserveRecordId = OpReserve(db, order.Id, parentUser.Id, GetWithdrawMoney(parentUser) * order.BuyCount, 2, order.UserId, "购机奖励");
                                    //返回到余额
                                    OpLeaderAccount(db, order, parentUser.Id, GetWithdrawMoney(parentUser), order.BuyCount, ReserveRecordId);
                                }

                                //给券打大盟主标记
                                // if(parentUser.LeaderLevel == 1 && CheckLeaderReserve(db, order.BuyCount, parentUser.Id) && !BigLeaderFlag)
                                // {
                                    
                                //     int LeaderId = CheckPosCouponLeaderFlag(db, parentUser.Id, order.BuyCount, codes);
                                //     if(LeaderId > 0)
                                //     {
                                //         BigLeaderFlag = true;
                                        
                                //     }
                                // }
                                // else if(parentUser.LeaderLevel == 2 && !BigLeaderFlag)
                                // {
                                    
                                //     BigLeaderFlag = true;
                                //     if(!string.IsNullOrEmpty(order.SnNos))
                                //     {
                                //         List<int> couponIds = db.PosCoupons.Where(m => codes.Contains(m.ExchangeCode)).OrderBy(m => m.Id).Take(CouponCount).ToList().Select(m => m.Id).ToList();
                                        
                                //         SetPosCouponLeaderFlag(db, parentUser.Id, order.BuyCount, couponIds);
                                        
                                //     }
                                // }
                            }
                            else if(parentUser.OperateLevel > 0 && CheckOpReserve(opdb, order.BuyCount, parentUser.Id) && BuyPrizeFlag < 2)
                            {
                                
                                //购机奖
                                decimal CurBuyPrize = GetBuyPrize(parentUser, order);
                                decimal GetPrize = CurBuyPrize - BuyPrize;
                                
                                if(GetPrize > 0)
                                {
                                    int ChangeType = 120;
                                    if(parentUser.OperateLevel > 1)
                                    {
                                        ChangeType = 128;
                                    }
                                    OpAccount(db, order.Id, parentUser.Id, GetPrize, order.BuyCount, ChangeType);
                                    BuyPrize = CurBuyPrize;
                                    if(GetPrize == 160) BuyPrizeFlag = 2;
                                    else if(GetPrize == 60) BuyPrizeFlag = 2;
                                    else BuyPrizeFlag = 1;
                                }
                                if(parentUser.OperateLevel == 2 && CurBuyPrize == 100) BuyPrizeFlag = 2; 

                                if(!BackAccountFlag)
                                {
                                    BackAccountFlag = true;
                                    decimal GetAmount = GetWithdrawMoney(parentUser) * order.BuyCount;

                                    OpAmountItem item = new OpAmountItem()
                                    {
                                        UserId = parentUser.Id,
                                        OperateType = 0,
                                        ChangeType = 5,
                                        Remark = "商城购机",
                                        UseAmount = GetAmount,
                                        UseValidForGetAmount = GetAmount,
                                        UseTotalAmt = GetAmount,
                                        DataType = 1,
                                        DataId = order.Id,
                                    };
                                    RedisDbconn.Instance.AddList("OperateAmountRecordServiceQueue", item);
                                }
                            }
                        }
                    }
                }
            }
            db.Dispose();
            opdb.Dispose();
        }





        public void Start2()
        {
            Thread th = new Thread(ready2);
            th.IsBackground = true;
            th.Start();
        }
        
        private void ready2()
        { 
            bool op = true;
            while (op)
            {
                string content = RedisDbconn.Instance.RPop<string>("PosCouponPrizeQueue2");
                if (!string.IsNullOrEmpty(content))
                {
                    try
                    {
                        dosomething2(int.Parse(function.CheckInt(content)));
                    }
                    catch
                    {
                    }
                }
                else
                {
                    Thread.Sleep(5000);
                }
            }
        }

        public void dosomething2(int OrderId)
        { 
            WebCMSEntities db = new WebCMSEntities();
            OpModels.WebCMSEntities opdb = new OpModels.WebCMSEntities();
            Orders order = db.Orders.FirstOrDefault(m => m.Id == OrderId);
            if(order != null)
            {
                List<int> ChkIds = new List<int>(); //机具券商品Id集合
                ChkIds.Add(10);
                ChkIds.Add(11);
                ChkIds.Add(77);
                ChkIds.Add(78);
                ChkIds.Add(79);
                //判断是否是指定商品
                if(ChkIds.Contains(order.ProductId))
                {
                    int Kind = 0;
                    if (order.ProductId == 10)
                    {
                        Kind = 1;
                    }
                    else if (order.ProductId == 11)
                    {
                        Kind = 2;
                    }
                    int CouponCount = 0;
                    if(Kind == 1)
                    {
                        CouponCount = 3 * order.BuyCount;
                    }
                    else if(Kind == 2)
                    {
                        CouponCount = 2 * order.BuyCount;
                    }


                    UserRankItem orderUser = GetUserLevel(order.UserId, false);
                    if(orderUser.UserLevel == 0) 
                    {
                    }
                    string ParentNav = orderUser.ParentNav + "," + orderUser.Id + ",";
                    string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                    Array.Reverse(ParentNavList);
                    int index = 0;
                    bool DirectPrizeFlag = false; //推荐奖励发放标识
                    bool BackAccountFlag = false; //备用金返余额标识
                    bool BigLeaderFlag = false; //大盟主标记
                    decimal BuyPrize = 0; //购机奖励
                    foreach(string ParentId in ParentNavList)
                    {
                        UserRankItem parentUser = GetUserLevel(int.Parse(ParentId), index > 0);
                        index += 1;
                        if(index == 1 && (orderUser.LeaderLevel > 0 || orderUser.OperateLevel > 0) && !DirectPrizeFlag)
                        {
                            DirectPrizeFlag = true;
                        }
                        if(index > 1)
                        {
                            if(Utils.Instance.IsStandardUser(parentUser.Id) && !DirectPrizeFlag)
                            {
                                DirectPrizeFlag = true;
                            }
                        }
                        if(parentUser.AgoLeaderLevel > 0 && CheckLeaderReserve(db, order.BuyCount, parentUser.Id))
                        {
                            //购机奖
                            if(parentUser.LeaderLevel > 0)
                            {
                                decimal CurBuyPrize = GetBuyPrize(parentUser, order);
                                decimal GetPrize = CurBuyPrize - BuyPrize;
                                if(GetPrize > 0) 
                                {
                                    bool PrizeFlag = true;
                                    int ChangeType = 118;
                                    if(parentUser.OperateLevel == 1)
                                    {
                                        ChangeType = 120;
                                    }
                                    if(parentUser.OperateLevel > 1)
                                    {
                                        ChangeType = 128;
                                        if(function.CheckNull(RedisDbconn.Instance.Get<string>("YingXunUser")).Contains("," + orderUser.Id + ","))
                                        {
                                            PrizeFlag = false;
                                        }
                                    }
                                    if(PrizeFlag && !db.UserAccountRecord.Any(m => m.QueryCount == order.Id && m.ChangeType == ChangeType))
                                    {
                                        // OpAccount(db, order.Id, parentUser.Id, GetPrize, order.BuyCount, ChangeType);
                                        if(GetPrize == 60) Utils.WriteLog(order.Id + " " + parentUser.Id + " " + GetPrize, "补60购机奖励");
                                    }
                                    BuyPrize = CurBuyPrize;
                                }
                            }

                            if(!BackAccountFlag)
                            {
                                BackAccountFlag = true;
                            }

                        }
                        else if(parentUser.OperateLevel > 0 && CheckOpReserve(opdb, order.BuyCount, parentUser.Id))
                        {
                            //购机奖
                            decimal CurBuyPrize = GetBuyPrize(parentUser, order);
                            decimal GetPrize = CurBuyPrize - BuyPrize;
                            if(GetPrize > 0)
                            {
                                int ChangeType = 120;
                                if(parentUser.OperateLevel > 1)
                                {
                                    ChangeType = 128;
                                }
                                BuyPrize = CurBuyPrize;
                                if(GetPrize == 60) Utils.WriteLog(order.Id + " " + parentUser.Id + " " + GetPrize, "补60购机奖励");
                                BuyPrize = CurBuyPrize;
                            }

                            if(!BackAccountFlag)
                            {
                                BackAccountFlag = true;
                            }
                        }
                    }
                }
            }
            db.Dispose();
            opdb.Dispose();
        }

        /// <summary>
        /// 获取创客各种等级
        /// </summary>
        /// <param name="db"></param>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public UserRankItem GetUserLevel(int UserId, bool AuthFlag = true)
        {
            WebCMSEntities db = new WebCMSEntities();
            OpModels.WebCMSEntities opdb = new OpModels.WebCMSEntities();
            UserRankItem dic = new UserRankItem();
            DateTime now = DateTime.Now;
            Users user = db.Users.FirstOrDefault(m => m.Id == UserId && m.AuthFlag == 1 && m.Status > -1) ?? new Users();
            if(!AuthFlag) user = db.Users.FirstOrDefault(m => m.Id == UserId && m.Status > -1) ?? new Users();
            UserRankWhite userWhite = db.UserRankWhite.FirstOrDefault(m => m.Id == UserId && m.UpdateDate > now) ?? new UserRankWhite();
            Leaders leader = db.Leaders.FirstOrDefault(m => m.Id == UserId) ?? new Leaders();
            dic.UserLevel = userWhite.Rank > user.UserLevel ? userWhite.Rank : user.UserLevel;
            if(leader.ExpiredDate > now)
            {
                dic.LeaderLevel = leader.LeaderLevel;
            }
            dic.AgoLeaderLevel = leader.LeaderLevel;
            OpModels.SysAdmin sys = opdb.SysAdmin.FirstOrDefault(m => m.UserId == UserId) ?? new OpModels.SysAdmin();
            if(sys.ExpireDate > now)
            {
                dic.OperateLevel = user.UserType;
                dic.UserType = user.UserType;
            }
            dic.MerchantType = user.MerchantType;
            dic.Id = user.Id;
            dic.MakerCode = user.MakerCode;
            dic.RealName = user.RealName;
            dic.ParentUserId = user.ParentUserId;
            dic.ParentNav = user.ParentNav;
            db.Dispose();
            opdb.Dispose();
            return dic;
        }

        public UserRankItem GetUserLevel2(int UserId, DateTime OrderTime, bool AuthFlag = true)
        {
            WebCMSEntities db = new WebCMSEntities();
            OpModels.WebCMSEntities opdb = new OpModels.WebCMSEntities();
            UserRankItem dic = new UserRankItem();
            Users user = db.Users.FirstOrDefault(m => m.Id == UserId && m.AuthFlag == 1 && m.Status > -1) ?? new Users();
            if(!AuthFlag) user = db.Users.FirstOrDefault(m => m.Id == UserId && m.Status > -1) ?? new Users();
            UserRankWhite userWhite = db.UserRankWhite.FirstOrDefault(m => m.Id == UserId && m.UpdateDate > OrderTime) ?? new UserRankWhite();
            Leaders leader = db.Leaders.FirstOrDefault(m => m.Id == UserId) ?? new Leaders();
            dic.UserLevel = userWhite.Rank > user.UserLevel ? userWhite.Rank : user.UserLevel;
            if(leader.ExpiredDate > OrderTime && leader.LastBuyDate < OrderTime)
            {
                dic.LeaderLevel = leader.LeaderLevel;
            }
            dic.AgoLeaderLevel = leader.LeaderLevel;
            OpModels.SysAdmin sys = opdb.SysAdmin.FirstOrDefault(m => m.UserId == UserId) ?? new OpModels.SysAdmin();
            if(sys.ExpireDate > OrderTime && sys.CreateDate < OrderTime)
            {
                dic.OperateLevel = user.UserType;
                dic.UserType = user.UserType;
            }
            dic.MerchantType = user.MerchantType;
            dic.Id = user.Id;
            dic.MakerCode = user.MakerCode;
            dic.RealName = user.RealName;
            dic.ParentUserId = user.ParentUserId;
            dic.ParentNav = user.ParentNav;
            db.Dispose();
            opdb.Dispose();
            return dic;
        }

        /// <summary>
        /// 直推奖励
        /// </summary>
        /// <param name="db"></param>
        /// <param name="OrderId"></param>
        /// <param name="UserId"></param>
        /// <param name="Count"></param>
        public void DirectPrize(WebCMSEntities db, int OrderId, int UserId, int Count = 1)
        {
            UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == UserId);
            if (account == null)
            {
                account = db.UserAccount.Add(new UserAccount()
                {
                    Id = UserId,
                    UserId = UserId,
                }).Entity;
                db.SaveChanges();
            }
            decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
            decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
            decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
            account.BalanceAmount += 100 * Count;
            account.TotalAmount += 100 * Count;
            decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
            decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
            decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
            UserAccountRecord userAccountRecord = db.UserAccountRecord.Add(new UserAccountRecord()
            {
                CreateDate = DateTime.Now,
                UpdateDate = DateTime.Now,
                UserId = UserId, //创客
                ChangeType = 112, //变动类型
                ChangeAmount = 100 * Count, //变更金额
                BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                AfterTotalAmount = AfterTotalAmount, //变更后总金额
                BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                QueryCount = OrderId,
            }).Entity;
            db.SaveChanges();

            //发送APP推送消息
            Utils.Instance.PrizePush(UserId, 100 * Count);
        }
    
        /// <summary>
        /// 判断盟主储蓄金足够
        /// </summary>
        /// <param name="db"></param>
        /// <param name="Count"></param>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public bool CheckLeaderReserve(WebCMSEntities db, int Count, int UserId)
        {
            UserAccount acccount = db.UserAccount.FirstOrDefault(m => m.Id == UserId) ?? new UserAccount();
            if(acccount.LeaderReserve >= 400 * Count)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 判断运营中心/合伙人额度足够
        /// </summary>
        /// <param name="db"></param>
        /// <param name="Count"></param>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public bool CheckOpReserve(OpModels.WebCMSEntities db, int Count, int UserId)
        {
            OpModels.UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == UserId) ?? new OpModels.UserAccount();
            if(account.TotalAmt >= 400 * Count)
            {
                return true;
            }
            return false;
        }
        public bool CheckOpReserve(OpModels.WebCMSEntities db, decimal Amt, int UserId)
        {
            OpModels.UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == UserId) ?? new OpModels.UserAccount();
            if(account.TotalAmt >= Amt)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 扣减/增加盟主储蓄金
        /// </summary>
        /// <param name="db"></param>
        /// <param name="OrderId"></param>
        /// <param name="UserId"></param>
        /// <param name="Money"></param>
        /// <param name="ChangeType"></param>
        /// <param name="SourceUserId"></param>
        /// <param name="Remark"></param>
        public int OpReserve(WebCMSEntities db, int OrderId, int UserId, decimal Money, int ChangeType, int SourceUserId = 0, string Remark = "储备金购买")
        {
            UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == UserId);
            if (account == null)
            {
                account = db.UserAccount.Add(new UserAccount()
                {
                    Id = UserId,
                    UserId = UserId,
                }).Entity;
                db.SaveChanges();
            }
            decimal BeforeAmount = account.LeaderReserve; //变更前总金额
            if(ChangeType == 1)
            {
                account.LeaderReserve += Money;
            }
            else
            {
                account.LeaderReserve -= Money;
            }
            decimal AfterAmount = account.LeaderReserve; //变更后总金额
            LeaderReserveRecord add = db.LeaderReserveRecord.Add(new LeaderReserveRecord()
            {
                CreateDate = DateTime.Now,
                ChangeType = ChangeType,
                OrderId = OrderId,
                Remark = Remark,
                AfterAmt = AfterAmount,
                BeforeAmt = BeforeAmount,
                ChangeAmt = Money,
                TradeDate = DateTime.Now.ToString("yyyyMMdd"),
                TradeMonth = DateTime.Now.ToString("yyyyMM"),
                UserId = UserId,
                SourceUserId = SourceUserId,
                Sort = GetLeaderReserveRecordType(Remark),
            }).Entity;
            db.SaveChanges();
            return add.Id;
        }
        private int GetLeaderReserveRecordType(string Remark)
        {
            Dictionary<int, string> data = new Dictionary<int, string>();
            data.Add(11, "兑换机具券,机具券兑换,系统增加(盟主储蓄金),系统扣减(盟主储蓄金),储备金购买");
            data.Add(12, "系统增加(可提现余额),系统扣减(可提现余额)");
            data.Add(13, "推荐大盟主,推荐小盟主,商城购机,购机奖励");
            var item = data.FirstOrDefault(m => m.Value.Contains(Remark));
            if(item.Key > 0)
            {
                return item.Key;
            }
            return 0;
        }

        /// <summary>
        /// 操作盟主可提现余额
        /// </summary>
        /// <param name="db"></param>
        /// <param name="order"></param>
        /// <param name="UserId"></param>
        /// <param name="Money"></param>
        /// <param name="Count"></param>
        /// <param name="Kind"></param>
        public void OpLeaderAccount(WebCMSEntities db, Orders order, int UserId, decimal Money, int Count = 1, int ReserveRecordId = 0)
        {
            UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == UserId);
            if (account == null)
            {
                account = db.UserAccount.Add(new UserAccount()
                {
                    Id = UserId,
                    UserId = UserId,
                }).Entity;
                db.SaveChanges();
            }
            int ChangeType = 0;
            if(Money == 400)
            {
                ChangeType = 117;
            }
            decimal BeforeLeaderBalanceAmount = account.LeaderBalanceAmount; //变更前余额
            account.LeaderBalanceAmount += Money * Count;
            decimal AfterLeaderBalanceAmount = account.LeaderBalanceAmount; //变更后余额
            LeaderAccountRecord leaderAccountRecord = db.LeaderAccountRecord.Add(new LeaderAccountRecord()
            {
                CreateDate = DateTime.Now,
                UpdateDate = DateTime.Now,
                UserId = UserId, //创客
                ChangeType = ChangeType, //变动类型
                ChangeAmount = Money * Count, //变更金额
                BeforeBalanceAmount = BeforeLeaderBalanceAmount, //变更前余额
                AfterBalanceAmount = AfterLeaderBalanceAmount, //变更后余额
                QueryCount = order.Id,
                Sort = order.UserId,
            }).Entity;
            db.SaveChanges();
            if(ReserveRecordId > 0)
            {
                LeaderReserveRecord edit = db.LeaderReserveRecord.FirstOrDefault(m => m.Id == ReserveRecordId);
                if(edit != null)
                {
                    edit.AccountRecordId = leaderAccountRecord.Id;
                    db.SaveChanges();
                }
            }
        }

        /// <summary>
        /// 操作余额
        /// </summary>
        /// <param name="db"></param>
        /// <param name="order"></param>
        /// <param name="UserId"></param>
        /// <param name="Money"></param>
        /// <param name="Count"></param>
        public void OpAccount(WebCMSEntities db, int OrderId, int UserId, decimal Money, int Count = 1, int ChangeType = 0, int Kind = 0)
        {
            UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == UserId);
            if (account == null)
            {
                account = db.UserAccount.Add(new UserAccount()
                {
                    Id = UserId,
                    UserId = UserId,
                }).Entity;
                db.SaveChanges();
            }
            decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
            decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
            decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
            account.BalanceAmount += Money * Count;
            account.TotalAmount += Money * Count;
            decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
            decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
            decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
            UserAccountRecord userAccountRecord = db.UserAccountRecord.Add(new UserAccountRecord()
            {
                CreateDate = DateTime.Now,
                UpdateDate = DateTime.Now,
                UserId = UserId, //创客
                ChangeType = ChangeType, //变动类型
                ChangeAmount = Money * Count, //变更金额
                BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                AfterTotalAmount = AfterTotalAmount, //变更后总金额
                BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                QueryCount = OrderId,
                Kind = Kind,
            }).Entity;
            db.SaveChanges();

            //发送APP推送消息
            Utils.Instance.PrizePush(UserId, Money * Count);
        }

        /// <summary>
        /// 操作运营中心/合伙人额度（TotalAmt未使用额度，ValidForGetAmount可提现额度）
        /// </summary>
        /// <param name="db"></param>
        /// <param name="UserId"></param>
        /// <param name="Money"></param>
        /// <param name="OperateType">（1增加，2减少）</param>
        /// <param name="AmountType">（1未使用额度，2可提现额度）</param>
        /// <param name="Remark"></param>
        /// <param name="record"></param>
        public void OperateAmountChange(OpModels.WebCMSEntities db, int UserId, decimal Money, int OperateType, int AmountType, string Remark = "", bool record = false, int OrderId = 0)
        {
            OpModels.UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == UserId);
            if (account == null)
            {
                account = db.UserAccount.Add(new OpModels.UserAccount()
                {
                    Id = UserId,
                    UserId = UserId,
                }).Entity;
                db.SaveChanges();
            }
            decimal BeforeAmount = account.ValidAmount + account.TotalAmt + account.ValidForGetAmount; //变更前总金额
            if(OperateType == 1)
            {
                if(AmountType == 1)
                {
                    account.TotalAmt += Money;
                }
                else if(AmountType == 2)
                {
                    account.ValidForGetAmount += Money;
                }
                else
                {
                    account.ValidAmount += Money;
                }
            }
            else
            {
                if(AmountType == 1)
                {
                    account.TotalAmt -= Money;
                }
                else if(AmountType == 2)
                {
                    account.ValidForGetAmount -= Money;
                }
                else
                {
                    account.ValidAmount -= Money;
                }
            }
            decimal AfterAmount = account.ValidAmount + account.TotalAmt + account.ValidForGetAmount; //变更后总金额
            if(record)
            {
                OpModels.AmountRecord add = db.AmountRecord.Add(new OpModels.AmountRecord()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,
                    OperateType = OperateType,
                    AfterAmount = AfterAmount,
                    AfterValidForGetAmount = account.ValidForGetAmount,
                    AfterTotalAmt = account.TotalAmt,
                    AfterValidAmount = account.ValidAmount,
                    BeforeAmount = BeforeAmount,
                    UseAmount = Money,
                    UserId = UserId,
                    SeoDescription = Remark,
                    Version = AmountType,
                    QueryCount = OrderId,
                }).Entity;

                OpModels.AmountChangeRecord amountChangeRecord = db.AmountChangeRecord.Add(new OpModels.AmountChangeRecord()
                {
                    AmountType = 2,//1 未使用额度 2 可提现额度 3 关联分仓额度
                    CreateDate = DateTime.Now,
                    Title = Remark,
                    UserId = UserId, //运营中心Id
                    BeforeAmount = BeforeAmount,//使用前剩余额度
                    AfterAmount = AfterAmount,//使用后剩余额度
                    ChangeAmount = Money,//操作金额
                    OperateType = OperateType,//操作类别
                    Sort = OrderId,
                }).Entity;
            }
            db.SaveChanges();
        }

        /// <summary>
        /// 给券设置大盟主标记
        /// </summary>
        /// <param name="db"></param>
        /// <param name="LeaderUserId"></param>
        /// <param name="Count"></param>
        /// <param name="couponIds"></param>
        public int SetPosCouponLeaderFlag(WebCMSEntities db, int LeaderUserId, int Count, List<int> couponIds, decimal UseAmount = 0)
        {
            int SetCount = 0;
            UserAccount pacccount = db.UserAccount.FirstOrDefault(m => m.Id == LeaderUserId) ?? new UserAccount();
            foreach(int couponId in couponIds)
            {
                PosCoupons coupon = db.PosCoupons.FirstOrDefault(m => m.Id == couponId);
                decimal LeaderReserve = pacccount.LeaderReserve;
                decimal CheckReserve = 400 * Count;
                // if(LeaderReserve < CheckReserve)
                // {
                //     LeaderReserveRecord ReserveRecord = db.LeaderReserveRecord.FirstOrDefault(m => m.UserId == LeaderUserId && m.Remark == "推荐小盟主" && m.ChangeAmt - m.UsedReserve > 0);
                //     if(ReserveRecord != null)
                //     {
                //         if(ReserveRecord.ChangeAmt - ReserveRecord.UsedReserve >= CheckReserve)
                //         {
                //             LeaderReserve = CheckReserve;
                //             ReserveRecord.UsedReserve += CheckReserve;
                //         }
                //         else
                //         {
                //             decimal OtherLeaderReserve = ReserveRecord.ChangeAmt - ReserveRecord.UsedReserve;
                //             ReserveRecord.UsedReserve += OtherLeaderReserve;
                //             LeaderReserveRecord ReserveRecord2 = db.LeaderReserveRecord.FirstOrDefault(m => m.Id > ReserveRecord.Id && m.UserId == LeaderUserId && m.Remark == "推荐小盟主" && m.ChangeAmt - m.UsedReserve > 0);
                //             if(ReserveRecord2 != null)
                //             {
                //                 if(ReserveRecord2.ChangeAmt - ReserveRecord2.UsedReserve >= CheckReserve - OtherLeaderReserve)
                //                 {
                //                     LeaderReserve = CheckReserve - OtherLeaderReserve;
                //                     ReserveRecord2.UsedReserve += CheckReserve - OtherLeaderReserve;
                //                 }
                //                 else
                //                 {
                //                     OtherLeaderReserve = ReserveRecord2.ChangeAmt - ReserveRecord2.UsedReserve;
                //                     ReserveRecord2.UsedReserve += OtherLeaderReserve;
                //                 }
                //             }
                //         }
                //     }
                // }
                if(coupon != null && LeaderReserve + UseAmount >= CheckReserve)
                {
                    coupon.LeaderUserId = LeaderUserId;
                    SetCount += 1;
                }
            }
            db.SaveChanges();
            return SetCount;
        }

        public int CheckPosCouponLeaderFlag(WebCMSEntities db, int UserId, int Count, List<string> codes)
        {
            int LeaderUserId = 0;
            decimal CheckReserve = 400 * Count;
            // decimal LeaderReserve = 0;
            LeaderReserveRecord ReserveRecord = db.LeaderReserveRecord.FirstOrDefault(m => m.SourceUserId == UserId && m.Remark == "推荐小盟主" && m.ChangeAmt - m.UsedReserve > CheckReserve);
            if(ReserveRecord != null)
            {
                LeaderUserId = ReserveRecord.UserId;
                // if(ReserveRecord.ChangeAmt - ReserveRecord.UsedReserve >= CheckReserve)
                // {
                    // LeaderReserve = CheckReserve;
                    ReserveRecord.UsedReserve += CheckReserve;
                // }
                // else
                // {
                //     decimal OtherLeaderReserve = ReserveRecord.ChangeAmt - ReserveRecord.UsedReserve;
                //     ReserveRecord.UsedReserve += OtherLeaderReserve;
                //     LeaderReserveRecord ReserveRecord2 = db.LeaderReserveRecord.FirstOrDefault(m => m.Id > ReserveRecord.Id && m.UserId == LeaderUserId && m.Remark == "推荐小盟主" && m.ChangeAmt - m.UsedReserve > 0);
                //     if(ReserveRecord2 != null)
                //     {
                //         if(ReserveRecord2.ChangeAmt - ReserveRecord2.UsedReserve >= CheckReserve - OtherLeaderReserve)
                //         {
                //             LeaderReserve = CheckReserve - OtherLeaderReserve;
                //             ReserveRecord2.UsedReserve += CheckReserve - OtherLeaderReserve;
                //         }
                //         else
                //         {
                //             OtherLeaderReserve = ReserveRecord2.ChangeAmt - ReserveRecord2.UsedReserve;
                //             ReserveRecord2.UsedReserve += OtherLeaderReserve;
                //         }
                //     }
                // }

                List<int> couponIds = db.PosCoupons.Where(m => codes.Contains(m.ExchangeCode)).OrderBy(m => m.Id).ToList().Select(m => m.Id).ToList();
                foreach(int couponId in couponIds)
                {
                    PosCoupons coupon = db.PosCoupons.FirstOrDefault(m => m.Id == couponId);
                    if(coupon != null)
                    {
                        coupon.LeaderUserId = LeaderUserId;
                    }
                }
                db.SaveChanges();
            }
            return LeaderUserId;
        }

        /// <summary>
        /// 获取购机奖金额
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public decimal GetBuyPrize(UserRankItem user, Orders order)
        {
            if(user.OperateLevel == 1) return 100;
            if(user.OperateLevel == 2) 
            {
                Utils.WriteLog("\n\n\n创客Id:" + user.Id, "训练营60拦截日志");
                if(TradeTeamCheck2(user.Id))
                {
                    return 160;
                }
                Utils.WriteLog("下单人:" + order.UserId, "训练营60拦截日志");
                if(!TradeTeamCheck(order.UserId) && user.Id != order.UserId)
                {
                    Utils.WriteLog("拦截", "训练营60拦截日志");
                    decimal Amount = order.BuyCount * 60;
                    RedisDbconn.Instance.AddList("TradeFilterQueue", "{\"OrderId\":\"" + order.Id + "\",\"PrizeUserId\":\"" + user.Id + "\",\"Amount\":\"" + Amount + "\",\"Kind\":\"1\"}");
                    Utils.WriteLog("end", "训练营60拦截日志");
                    return 100;
                }
                if(CheckSpecialUserNav(order.UserId))
                {
                    return 100;
                }
                return 160;
            }
            if(user.OperateLevel == 3) return 180;
            if(user.OperateLevel == 4) return 200;
            if(user.LeaderLevel > 0) return 100;
            return 0;
        }

        public bool TradeTeamCheck(int UserId)
        {
            bool op = true;
            if(UserId == 0)
            {
                return op;
            }
            Utils.WriteLog("UserId:" + UserId, "训练营判断参与活动");
            WebCMSEntities maindb = new WebCMSEntities();
            Users muser = maindb.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
            string ParentNav = muser.ParentUserId + "," + UserId;
            string[] ParentNavList = ParentNav.Split(',');
            List<int> UserIds = new List<int>();
            foreach(string IdString in ParentNavList)
            {
                UserIds.Add(int.Parse(function.CheckInt(IdString)));
            } 
            JavaModels.WebCMSEntities db = new JavaModels.WebCMSEntities();
            JavaModels.KxsCamp camp = db.KxsCamp.FirstOrDefault(m => m.Status == 1);
            if(camp != null)
            {
                int CampId = camp.Id;
                var users = db.KxsCampUser.Where(m => UserIds.Contains(m.UserId) && m.CampId == CampId).ToList();
                foreach(var user in users)
                {
                    Utils.WriteLog("活动Id:" + camp.Id, "训练营判断参与活动");
                    op = false;
                    break;
                }
            }
            maindb.Dispose();
            db.Dispose();
            Utils.WriteLog("\n\n\n", "训练营判断参与活动");
            return op;
        }

        public bool TradeTeamCheck2(int UserId)
        {
            bool op = false;
            if(UserId == 0)
            {
                return op;
            }
            Utils.WriteLog("黄金合伙人-UserId:" + UserId, "训练营判断参与活动");
            JavaModels.WebCMSEntities db = new JavaModels.WebCMSEntities();
            var users = db.KxsCampUser.Where(m => m.UserId == UserId).ToList();
            foreach(var user in users)
            {
                DateTime now = DateTime.Now;
                // JavaModels.KxsCamp camp = db.KxsCamp.FirstOrDefault(m => m.Id == user.CampId && m.StartTime <= now && m.EndTime >= now);
                JavaModels.KxsCamp camp = db.KxsCamp.FirstOrDefault(m => m.Id == user.CampId && m.Status == 1);
                if(camp != null)
                {
                    Utils.WriteLog("黄金合伙人-活动Id:" + camp.Id, "训练营判断参与活动");
                    op = true;
                    break;
                }
            }
            db.Dispose();
            Utils.WriteLog("\n\n\n", "训练营判断参与活动");
            return op;
        }

        public bool CheckSpecialUserNav(int UserId)
        {
            List<int> ids = new List<int>();
            WebCMSEntities maindb = new WebCMSEntities();
            bool op = maindb.Users.Any(m => (m.ParentNav.Contains(",246751,") || m.Id == 246751) && m.Id == UserId);
            maindb.Dispose();
            return op;
        }

        /// <summary>
        /// 获取可提现金额
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public decimal GetWithdrawMoney(UserRankItem user)
        {
            if(user.OperateLevel == 1) return 400;
            // if(user.OperateLevel == 2) return 340;
            // if(user.OperateLevel == 3) return 320;
            // if(user.OperateLevel == 4) return 300;
            if(user.OperateLevel == 2) return 400;
            if(user.OperateLevel == 3) return 400;
            if(user.OperateLevel == 4) return 400;
            if(user.AgoLeaderLevel > 0) return 400;
            return 0;
        }

        /// <summary>
        /// 预设职级
        /// </summary>
        /// <param name="db"></param>
        /// <param name="UserId">创客Id</param>
        /// <param name="Rank">职级</param>
        /// <param name="ExpiredDate">过期时间</param>
        public void PreUserLevel(WebCMSEntities db, int UserId, int Rank, DateTime ExpiredDate)
        {
            UserRankWhite rank = db.UserRankWhite.FirstOrDefault(m => m.Id == UserId);
            if(rank == null)
            {
                rank = db.UserRankWhite.Add(new UserRankWhite()
                {
                    CreateDate = DateTime.Now, //设置时间
                    UserId = UserId, //用户
                    Id = UserId,
                }).Entity;
                db.SaveChanges();
            }
            rank.Rank = Rank;
            rank.UpdateDate = ExpiredDate;
            db.SaveChanges();
        }
    }
}