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


        public void Start()
        {
            Thread th = new Thread(dosomething);
            th.IsBackground = true;
            th.Start();
        }
        
        private void dosomething()
        { 
            bool op = true;
            while (op)
            {
                string content = RedisDbconn.Instance.RPop<string>("PayCallBack2");
                if (!string.IsNullOrEmpty(content))
                {
                    try
                    {
                        sloveAlipayCallBack(content);
                    }
                    catch(Exception ex)
                    {
                        function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "支付宝支付回调异常");
                    }
                }
                else
                {
                    Thread.Sleep(2000);
                }
            }
        }

        public void sloveAlipayCallBack(string content)
        { 
            JsonData jsonObj = JsonMapper.ToObject(content);
            string OrderNo = jsonObj["out_trade_no"].ToString();
            string TradeNo = jsonObj["transaction_id"].ToString();
            decimal TotalFee = decimal.Parse(function.CheckNum(jsonObj["total_fee"].ToString()));
            WebCMSEntities db = new WebCMSEntities();
            OrderForNo forNo = db.OrderForNo.FirstOrDefault(m => m.OrderNo == OrderNo);
            if (forNo != null)
            {
                string[] ids = forNo.OrderIds.Split(',');
                foreach (string idString in ids)
                {
                    int OrderId = int.Parse(idString);
                    DoOrderV2(db, OrderId);
                    Orders order = db.Orders.FirstOrDefault(m => m.Id == OrderId && m.Status > 0);
                    if(order != null)
                    {
                        Products product = db.Products.FirstOrDefault(m => m.Id == order.ProductId) ?? new Products();
                        if(product.ProductKind == 2)
                        {
                            order.Status = 2;
                            order.SendStatus = 1;
                            order.SendDate = DateTime.Now;
                            db.SaveChanges();
                        }
                    }
                }
            }
            db.Dispose();
        }

        #region 新订单流程
        public void DoOrderV2(WebCMSEntities db, int OrderId)
        {
            Orders order = db.Orders.FirstOrDefault(m => m.Id == OrderId && m.Status <= 0);
            if (order != null)
            {
                order.Status = 1;
                order.PayDate = DateTime.Now;
                order.PayStatus = 1;
                db.SaveChanges();
                if(order.ParentOrderId > 0)
                {
                    int total = db.Orders.Count(m => m.ParentOrderId == order.ParentOrderId);
                    int paycount = db.Orders.Count(m => m.ParentOrderId == order.ParentOrderId && m.Status > 0);
                    if(paycount >= total)
                    {
                        // order = db.Orders.FirstOrDefault(m => m.Id == order.ParentOrderId && m.Status == 0);
                        // if (order != null)
                        // {
                        //     order.Status = 2;
                        //     order.PayDate = DateTime.Now;
                        //     order.PayStatus = 1;
                        //     OrderId = order.Id;
                        // }
                        DoOrderV2(db, order.ParentOrderId);
                    }
                    return;
                }

                OrderProduct pro = db.OrderProduct.FirstOrDefault(m => m.OrderId == OrderId);
                if (pro != null)
                {
                    order.ProductId = pro.ProductId;
                    //扣减对应商品的库存
                    Products product = db.Products.FirstOrDefault(m => m.Id == pro.ProductId);
                    if(product != null)
                    {
                        product.Stock -= pro.ProductCount;
                        product.BuyCount += pro.ProductCount;
                    }
                    db.SaveChanges();
                    if(order.ErpMode > 0)
                    {
                        pro.ProductId = order.ProductId;
                    }
                    List<int> couponIds = new List<int>();
                    if (pro.ProductId == 10 || pro.ProductId == 11 || pro.ProductId == 27 || pro.ProductId == 28 || pro.ProductId == 34 || pro.ProductId == -2)
                    {
                        order.Status = 2;
                        int BuyCount = pro.ProductCount;
                        int Kind = 0;
                        int BeforeLeaderLevel = 0;
                        if (pro.ProductId == 10 || pro.ProductId == 34)
                        {
                            Kind = 1;
                        }
                        else if (pro.ProductId == 11 || pro.ProductId == -2)
                        {
                            Kind = 2;
                        }
                        else if (pro.ProductId == 28)
                        {
                            Users user = db.Users.FirstOrDefault(m => m.Id == order.UserId && m.LeaderLevel == 0);
                            if(user != null)
                            {
                                BeforeLeaderLevel = user.LeaderLevel;
                                user.LeaderLevel = 1;
                            }
                        }
                        else if (pro.ProductId == 27)
                        {
                            Users user = db.Users.FirstOrDefault(m => m.Id == order.UserId && m.LeaderLevel < 2);
                            if(user != null)
                            {
                                BeforeLeaderLevel = user.LeaderLevel;
                                user.LeaderLevel = 2;
                            }
                        }
                        if(Kind <= 2 && (pro.ProductId == 10 || pro.ProductId == 11 || pro.ProductId == 34 || pro.ProductId == -2))
                        {
                            // 购买600一组机具券，返券
                            int CouponCount = 0;
                            if(Kind == 1 || Kind == 3)
                            {
                                CouponCount = 3 * pro.ProductCount;
                            }
                            else if(Kind == 2)
                            {
                                CouponCount = 2 * pro.ProductCount;
                            }
                            if(pro.ProductId == 34) //助利宝商机券购买，50张起购
                            {
                                CouponCount = 50 * pro.ProductCount;
                            }
                            string Codes = "";
                            var coupons = db.PosCoupons.Where(m => m.IsLock == 0 && m.IsUse == 0 && m.UserId == 0 && m.QueryCount == Kind).OrderBy(m => m.Id).Take(CouponCount).ToList();
                            int RecordId = 0;
                            if(coupons.Count > 0 && (pro.ProductId == 34 || pro.ProductId == -2))
                            {
                                var adds = db.HelpProfitExchange.Add(new HelpProfitExchange()
                                {
                                    CreateDate = DateTime.Now, //创建时间
                                    UserId = order.UserId,
                                    ExchangeCount = coupons.Count,
                                }).Entity;
                                db.SaveChanges();
                                RecordId = adds.Id;
                            }
                            foreach (var coupon in coupons) // TODO: 数量多的话，会慢
                            {
                                PosCoupons item = db.PosCoupons.FirstOrDefault(m => m.Id == coupon.Id);
                                if (item != null)
                                {
                                    item.CreateDate = DateTime.Now;
                                    item.UserId = order.UserId;
                                    item.UpdateDate = DateTime.Now.AddDays(180);
                                    if(pro.ProductId == 34 || pro.ProductId == -2)
                                    {
                                        item.HelpProfitFlag = 1;
                                        db.HelpProfitExchangeDetail.Add(new HelpProfitExchangeDetail()
                                        {
                                            CreateDate = DateTime.Now, //创建时间
                                            UserId = order.UserId,
                                            PosCouponId = item.Id,
                                            ExchangeCode = item.ExchangeCode,
                                            RecordId = RecordId,
                                        });
                                    }
                                    Codes += item.ExchangeCode + ",";
                                    couponIds.Add(coupon.Id);
                                }
                            }
                            order.SnNos = Codes.TrimEnd(',');
                        }
                        db.SaveChanges();
                        if (pro.ProductId == 27 || pro.ProductId == 28)
                        {
                            //充值盟主储备金
                            decimal TotalPrice = 10000;
                            if(pro.ProductId == 27)
                            {
                                TotalPrice = 40000;
                            }
                            OpReserve(db, order, order.UserId, TotalPrice, 1);
                            Users user = db.Users.FirstOrDefault(m => m.Id == order.UserId) ?? new Users();
                            if(pro.ProductId == 27)
                            {
                                OperateReserveBackFor(db, user.Id, 40000);
                                //自留券数量清除
                                CancelStayCoupon(db, order.UserId, 7);
                                //预设大盟主职级
                                LeaderPreUserLevel(db, order.UserId, 2);
                                AddLeader(db, order.UserId, 2);
                                decimal Prize = decimal.Parse(function.CheckNum(PublicFunction.GetPublicParam(db, "BigLeaderPrize")));
                                if(Prize > 0 && BeforeLeaderLevel < 2 && user.UserType == 0)
                                {
                                    LeaderRecommendPrize(db, order, user.Id, Prize, 122);
                                }
                            }
                        }
                        if (pro.ProductId == 28) //购买小盟主，给上级大盟主返储备金
                        {
                            bool check = LeaderBack(db, order);
                            Users user = db.Users.FirstOrDefault(m => m.Id == order.UserId) ?? new Users();
                            //自留券数量清除
                            CancelStayCoupon(db, order.UserId, 5);
                            if (check) OperateReserveBackFor(db, user.Id, 10000);
                            //预设小盟主职级
                            LeaderPreUserLevel(db, order.UserId, 1);
                            AddLeader(db, order.UserId, 1);
                            decimal Prize = decimal.Parse(function.CheckNum(PublicFunction.GetPublicParam(db, "SmallLeaderPrize")));
                            if(Prize > 0 && BeforeLeaderLevel < 1 && user.UserType == 0)
                            {
                                LeaderRecommendPrize(db, order, user.Id, Prize, 123);
                            }
                        }
                    }
                    // 购买盟主储蓄金
                    if (pro.ProductId == 39 || pro.ProductId == 40)
                    {
                        order.Status = 2;
                        //充值盟主储备金
                        decimal TotalPrice = 10000;
                        if(pro.ProductId == 39)
                        {
                            TotalPrice = 40000;
                        }
                        OpReserve(db, order, order.UserId, TotalPrice, 1);
                        if(pro.ProductId == 39) //购买大盟主储蓄金，给上级运营中心返可提现金额
                        {
                            OperateReserveBackFor(db, order.UserId, 40000);
                            AddLeader(db, order.UserId, 2);
                            LeaderPreUserLevel(db, order.UserId, 2);
                        }
                        else if(pro.ProductId == 40) //购买小盟主储蓄金，给上级大盟主返储备金
                        {
                            LeaderBack(db, order);
                            AddLeader(db, order.UserId, 1);
                            LeaderPreUserLevel(db, order.UserId, 1);
                        }
                    }

                    //推荐下单奖励
                    RedisDbconn.Instance.AddList("PosCouponPrizeQueue", order.Id.ToString());

                    //推荐王
                    if(pro.ProductId == 29)
                    {
                        RecommendMethod(order.UserId, order.CreateDate.Value.ToString("yyyyMM"));
                    }
                    //购买分仓临时额度
                    if(pro.ProductId == 30 || pro.ProductId == 31 || pro.ProductId == 32)
                    {
                        string SendData = "{\"Kind\":\"1\",\"Data\":{\"OrderId\":\"" + order.Id + "\"}}";
                        RedisDbconn.Instance.AddList("StoreApplyQueue", SendData);
                    }
                    //购买小分仓临时额度
                    if(pro.ProductId == 56 || pro.ProductId == 57 || pro.ProductId == 58)
                    {
                        string SendData = "{\"Kind\":\"1\",\"Data\":{\"OrderId\":\"" + order.Id + "\"}}";
                        RedisDbconn.Instance.AddList("PreStoreApplyQueue", SendData);
                    }

                }
                else
                {
                    if(order.ProductId > 0 && order.ErpMode > 0)
                    {
                        //盟主储备金-升级/购买 ErpMode:1-升级，2-购买
                        if(order.ErpMode > 0)
                        {
                            Users user = db.Users.FirstOrDefault(m => m.Id == order.UserId);
                            if(user != null)
                            {
                                if(order.ErpMode == 1)
                                {
                                    user.LeaderLevel = 2;
                                    db.SaveChanges();
                                }
                                OpReserve(db, order, order.UserId, order.TotalPrice, 1);
                            }
                        }
                    }
                }
            }
        }

        //小盟主购买逻辑
        public bool LeaderBack(WebCMSEntities db, Orders order)
        {
            int LeaderUserId = order.UserId;
            int level = 0;
            bool result = true;
            while(LeaderUserId > 0)
            {
                level += 1;
                Users user = db.Users.FirstOrDefault(m => m.Id == LeaderUserId);
                if(user != null)
                {
                    decimal TotalPrice = 10000;
                    if((user.LeaderLevel == 2 || user.UserType > 1) && level > 1)
                    {
                        if(user.UserType > 1 && result)
                        {
                            OpModels.WebCMSEntities opdb = new OpModels.WebCMSEntities();
                            OpModels.UserAccount account = opdb.UserAccount.FirstOrDefault(m => m.Id == LeaderUserId) ?? new OpModels.UserAccount();
                            if(account.TotalAmt > 0)
                            {
                                if(account.TotalAmt < TotalPrice)
                                {
                                    TotalPrice = account.TotalAmt;
                                }
                                if(TotalPrice > 0)
                                {
                                    OperateAmountChange(opdb, LeaderUserId, TotalPrice, 2, 1, "商城购机", true);
                                    OperateAmountChange(opdb, LeaderUserId, TotalPrice, 1, 2, "商城购机", true);
                                    LeaderUserId = 0;
                                    result = false;
                                }
                            }
                            else
                            {
                                LeaderUserId = user.ParentUserId;
                            }
                        }
                        else if(user.LeaderLevel == 2 && result)
                        {
                            UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == LeaderUserId);
                            if(account != null)
                            {
                                if(account.LeaderReserve >= TotalPrice)
                                {
                                    OpReserve(db, order, LeaderUserId, TotalPrice, 2, 0, "推荐小盟主");
                                    OpLeaderAccount(db, order, LeaderUserId, TotalPrice, 1, 1);
                                    LeaderUserId = 0;
                                    result = false;
                                }
                                else
                                {
                                    LeaderUserId = user.ParentUserId;
                                    // decimal LeaderReserve = account.LeaderReserve;
                                    // OpReserve(db, order, LeaderUserId, LeaderReserve, 2, 0, "推荐小盟主");
                                    // OpLeaderAccount(db, order, LeaderUserId, LeaderReserve);
                                }
                            }
                        }
                        else
                        {
                            LeaderUserId = user.ParentUserId;
                        }
                    }
                    else
                    {
                        LeaderUserId = user.ParentUserId;
                    }
                }
                else
                {
                    LeaderUserId = 0;
                }
            }
            return result;
        }

        //操作储备金
        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;
        }
        public void OpReserve(WebCMSEntities db, Orders order, 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 = order.Id,
                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();
        }
        //操作余额
        public void OpAccount(WebCMSEntities db, Orders order, int UserId, decimal Money, 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();
            }
            int ChangeType = 0;
            if(Money == 600)
            {
                ChangeType = 117;
            }
            else if(Money == 100)
            {
                ChangeType = 118;
            }
            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 = order.Id,
            }).Entity;
            db.SaveChanges();
        }
        public void ChangeAccount(WebCMSEntities db, Orders order, int UserId, decimal Money, int ChangeType = 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 BeforeTotalAmount = account.TotalAmount; //变更前总金额
            decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
            decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
            account.BalanceAmount += Money;
            if(Money > 0)
            {
                account.TotalAmount += Money;
            }
            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 = Math.Abs(Money), //变更金额
                BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                AfterTotalAmount = AfterTotalAmount, //变更后总金额
                BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                QueryCount = order.Id,
                Remark = Remark,
            }).Entity;
            db.SaveChanges();
        }
        //操作盟主可提现余额
        public void OpLeaderAccount(WebCMSEntities db, Orders order, int UserId, decimal Money, int Count = 1, 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();
            }
            int ChangeType = 0;
            if(Money == 400)
            {
                ChangeType = 117;
            }
            int LeaderId = 0;
            decimal LeaderReserve = 0;
            if(Kind == 1)
            {
                LeaderId = UserId;
                LeaderReserve = Money * Count;
            }
            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,
                LeaderId = LeaderId,
                LeaderReserve = LeaderReserve,
            }).Entity;
            db.SaveChanges();
        }
        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();
        }

        // 推荐王逻辑（下单）
        public void RecommendMethod(int UserId, string TradeMonth)
        {
            string SendData = "{\"Kind\":\"1\",\"Data\":{\"UserId\":\"" + UserId + "\",\"TradeMonth\":\"" + TradeMonth + "\"}}";
            RedisDbconn.Instance.AddList("RecommendActStatQueue", SendData);
        }


        //操作运营中心额度
        public void OperateReserveBackFor(WebCMSEntities maindb, int UserId, decimal Money)
        {
            OpModels.WebCMSEntities db = new OpModels.WebCMSEntities();
            while(UserId > 0)
            {
                Users user = maindb.Users.FirstOrDefault(m => m.Id == UserId);
                if(user != null)
                {
                    bool sys = db.SysAdmin.Any(m => m.UserId == UserId);
                    if(sys)
                    {
                        OpModels.UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == UserId) ?? new OpModels.UserAccount();
                        if(account.TotalAmt >= Money)
                        {
                            OperateAmountChange(db, UserId, Money, 2, 1, "商城购机", true);
                            OperateAmountChange(db, UserId, Money, 1, 2, "商城购机", true);
                            UserId = 0;
                        }
                        else
                        {
                            UserId = user.ParentUserId;
                        }
                    }
                    else
                    {
                        UserId = user.ParentUserId;
                    }
                }
                else
                {
                    UserId = 0;
                }
            }
            db.Dispose();
        }
        public void OperateReserveBack(int UserId, decimal Money)
        {
            OpModels.WebCMSEntities db = new OpModels.WebCMSEntities();
            OpModels.UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == UserId) ?? new OpModels.UserAccount();
            if(account.TotalAmt <= 0)
            {
                return;
            }
            if(account.TotalAmt < Money)
            {
                Money = account.TotalAmt;
            }
            if(Money > 0)
            {
                OperateAmountChange(db, UserId, Money, 2, 1, "商城购机");
                OperateAmountChange(db, UserId, Money, 1, 2, "商城购机");
            }
            db.Dispose();
        }
        public void ActReserveBack(int UserId, decimal OpReserve1, decimal OpReserve2, decimal OpReserve3)
        {
            OpModels.WebCMSEntities db = new OpModels.WebCMSEntities();
            if(OpReserve1 > 0) OperateAmountChange(db, UserId, OpReserve1, 1, 1, "机具激活", true);
            if(OpReserve2 > 0) OperateAmountChange(db, UserId, OpReserve2, 1, 2, "机具激活", true);
            if(OpReserve3 > 0) OperateAmountChange(db, UserId, OpReserve3, 1, 3, "机具激活", true);
            db.Dispose();
        }
        public void OperateAmountChange(OpModels.WebCMSEntities db, int UserId, decimal Money, int OperateType, int AmountType, string Remark = "", bool record = false)
        {
            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)
                {
                    // BeforeAmount = account.TotalAmt;
                    account.TotalAmt += Money;
                    // AfterAmount = account.TotalAmt;
                }
                else if(AmountType == 2)
                {
                    // BeforeAmount = account.ValidForGetAmount;
                    account.ValidForGetAmount += Money;
                    // AfterAmount = account.ValidForGetAmount;
                }
                else
                {
                    // BeforeAmount = account.ValidAmount;
                    account.ValidAmount += Money;
                    // AfterAmount = account.ValidAmount;
                }
            }
            else
            {
                if(AmountType == 1)
                {
                    // BeforeAmount = account.TotalAmt;
                    account.TotalAmt -= Money;
                    // AfterAmount = account.TotalAmt;
                }
                else if(AmountType == 2)
                {
                    // BeforeAmount = account.ValidForGetAmount;
                    account.ValidForGetAmount -= Money;
                    // AfterAmount = account.ValidForGetAmount;
                }
                else
                {
                    // BeforeAmount = account.ValidAmount;
                    account.ValidAmount -= Money;
                    // AfterAmount = account.ValidAmount;
                }
            }
            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,
                    BeforeAmount = BeforeAmount,
                    UseAmount = Money,
                    UserId = UserId,
                    SeoDescription = Remark,
                    Version = AmountType,
                }).Entity;
            }
            db.SaveChanges();
        }

        #endregion


        #region 盟主推荐奖励

        public void LeaderRecommendPrize(WebCMSEntities db, Orders order, int UserId, decimal Money, int ChangeType)
        {
            int level = 0;
            while(UserId > 0)
            {
                level += 1;
                Users user = db.Users.FirstOrDefault(m => m.Id == UserId);
                if(user != null)
                {
                    if((user.UserType == 1 || user.LeaderLevel > 0) && level > 1)
                    {
                        ChangeAccount(db, order, UserId, Money, ChangeType);
                        UserId = 0;
                    }
                    else
                    {
                        UserId = user.ParentUserId;
                    }
                }
                else
                {
                    UserId = 0;
                }
            }
            db.Dispose();
        }

        #endregion


        #region 购买盟主预设职级

        public void LeaderPreUserLevel(WebCMSEntities db, int UserId, int LeaderKind)
        {
            int Month = LeaderKind == 1 ? 6 : 9;
            int Rank = LeaderKind == 1 ? 5 : 7;
            LeaderRankWhite check = db.LeaderRankWhite.FirstOrDefault(m => m.Id == UserId);
            if(check == null)
            {
                db.LeaderRankWhite.Add(new LeaderRankWhite()
                {
                    CreateDate = DateTime.Now, //设置时间
                    UpdateDate = DateTime.Now.AddMonths(Month), //过期时间
                    Rank = Rank,
                    UserId = UserId, //用户
                    Id = UserId,
                });
            }
            else
            {
                if(check.Rank < Rank)
                {
                    check.Rank = Rank;
                    check.UpdateDate = DateTime.Now.AddMonths(Month);
                }
                else if(check.Rank == Rank && check.UpdateDate < DateTime.Now.AddMonths(Month))
                {
                    check.UpdateDate = DateTime.Now.AddMonths(Month);
                }
            }
            db.SaveChanges();
        }

        public void PreUserLevel(WebCMSEntities db, int UserId, int Rank, DateTime ExpiredDate)
        {
            LeaderRankWhite rank = db.LeaderRankWhite.FirstOrDefault(m => m.Id == UserId);
            if(rank == null)
            {
                rank = db.LeaderRankWhite.Add(new LeaderRankWhite()
                {
                    CreateDate = DateTime.Now, //设置时间
                    UserId = UserId, //用户
                    Id = UserId,
                }).Entity;
                db.SaveChanges();
            }
            rank.Rank = Rank;
            rank.UpdateDate = ExpiredDate;
            db.SaveChanges();
        }

        //取消自留券数量
        public void CancelStayCoupon(WebCMSEntities db, int UserId, int CheckLevel = 5)
        {
            int myLevel = Utils.Instance.GetUserLevel(UserId);
            if(myLevel <= CheckLevel)
            {
                Users user = db.Users.FirstOrDefault(m => m.Id == UserId);
                if(user != null)
                {
                    user.Version = 0;
                    db.SaveChanges();
                }
            }
        }

        #endregion

        #region 记录盟主

        public void AddLeader(WebCMSEntities db, int UserId, int LeaderLevel)
        {
            int Month = LeaderLevel == 1 ? 6 : 9;
            Leaders leader = db.Leaders.FirstOrDefault(m => m.Id == UserId);
            if(leader == null)
            {
                db.Leaders.Add(new Leaders()
                {
                    Id = UserId,
                    CreateDate = DateTime.Now, //设置时间
                    UserId = UserId, //用户
                    LeaderLevel = LeaderLevel,
                    LastBuyDate = DateTime.Now,
                    ExpiredDate = DateTime.Now.AddMonths(Month),
                });
            }
            else
            {
                leader.LeaderLevel = LeaderLevel;
                leader.LastBuyDate = DateTime.Now;
                leader.ExpiredDate = DateTime.Now.AddMonths(Month);
            }
            db.SaveChanges();
            SendLeaderMsg(db, UserId);
        }

        #endregion

        #region 盟主续费通知

        public void SendLeaderMsg(WebCMSEntities db, int UserId)
        {
            string msg = "";
            Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
            DateTime now = DateTime.Now;
            Leaders leader = db.Leaders.FirstOrDefault(m => m.Id == UserId);
            if(leader != null)
            {
                if(leader.ExpiredDate >= now)
                {
                    msg = "尊敬的" + user.RealName + "盟主，恭喜您的盟主已成功开通";
                }
                else
                {
                    msg = "尊敬的" + user.RealName + "盟主，恭喜您重新成为盟主";
                }
            }
            else
            {
                msg = "尊敬的" + user.RealName + "盟主，恭喜您的盟主已成功开通";
            }
            RedisDbconn.Instance.AddList("MsgPersonalQueue", Newtonsoft.Json.JsonConvert.SerializeObject(new MsgPersonal()
            {
                UserId = Convert.ToInt32(UserId), //创客
                Title = "开通盟主提醒", //标题
                Content = msg, //内容
                Summary = msg,
                CreateDate = DateTime.Now,
            }));
        }

        #endregion

    }
}