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

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

        public void Start()//启动
        {
            Thread thread = new Thread(doSomething);
            thread.IsBackground = true;
            thread.Start();
        }

        public void doSomething()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("LeaderApplyCouponsQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    try
                    {
                        var Id = int.Parse(content);
                        WebCMSEntities db = new WebCMSEntities();
                        var queryList = db.LeaderReserveRecord.FirstOrDefault(m => m.Id == Id) ?? new LeaderReserveRecord();
                        var user = db.Users.FirstOrDefault(m => m.Id == queryList.UserId) ?? new Users();

                        List<int> couponIds = new List<int>();
                        List<string> codes = new List<string>();                        
                        int count = 0;
                        int BuyCount = 0;

                        JsonData ApplyList = JsonMapper.ToObject(queryList.SeoTitle);
                        for (int i = 0; i < ApplyList.Count; i++)
                        {
                            int num = Convert.ToInt32(ApplyList[i]["Num"].ToString());
                            int type = Convert.ToInt32(ApplyList[i]["Type"].ToString());
                            //电签
                            if (type == 1)
                            {
                                var dposCoupons = db.PosCoupons.Where(m => m.QueryCount == 1 && m.UserId == 0 && m.LeaderUserId == 0 && m.IsUse == 0 && m.IsLock == 0 && m.Sort == 0 && m.OpId == 0).Take(num).ToList();//电签券
                                foreach (var item in dposCoupons)
                                {
                                    var posCoupon = db.PosCoupons.FirstOrDefault(m => m.Id == item.Id) ?? new PosCoupons();
                                    posCoupon.UserId = queryList.UserId;
                                    posCoupon.Sort = 1;
                                    db.UserSnDelayChange.Add(new UserSnDelayChange()
                                    {
                                        CreateDate = DateTime.Now,
                                        QueryCount = Id,
                                        SnNo = posCoupon.ExchangeCode,
                                    });
                                    couponIds.Add(item.Id);
                                    codes.Add(item.ExchangeCode);
                                }
                                count += couponIds.Count / 3;
                                BuyCount += num / 3;
                            }
                            //大机
                            if (type == 2)
                            {
                                var bposCoupons = db.PosCoupons.Where(m => m.QueryCount == 2 && m.UserId == 0 && m.LeaderUserId == 0 && m.IsUse == 0 && m.IsLock == 0 && m.Sort == 0 && m.OpId == 0).Take(num).ToList();//大机券
                                foreach (var items in bposCoupons)
                                {
                                    var posCoupon = db.PosCoupons.FirstOrDefault(m => m.Id == items.Id) ?? new PosCoupons();
                                    posCoupon.UserId = queryList.UserId;
                                    posCoupon.Sort = 1;
                                    db.UserSnDelayChange.Add(new UserSnDelayChange()
                                    {
                                        CreateDate = DateTime.Now,
                                        QueryCount = Id,
                                        SnNo = posCoupon.ExchangeCode,
                                    });
                                    couponIds.Add(items.Id);
                                    codes.Add(items.ExchangeCode);
                                }
                                count += couponIds.Count / 2;
                                BuyCount += num / 2;
                            }
                            db.SaveChanges();
                        }
                        db.SaveChanges();
                        
                        dosomething(Id, couponIds, codes, count);

                        //推动数据到MQ
                        Utils.Instance.SendMqOrder(new Orders()
                        {
                            Id = queryList.Id,
                            Status = 2,
                            CreateDate = queryList.CreateDate,
                            Remark = queryList.Remark,
                            BuyCount = BuyCount,
                            PayStatus = 1,
                            ProductId = 10000,
                            DeliveryType = 0,
                            PayMode = 4,
                            PayDate = queryList.CreateDate,
                            TotalPrice = queryList.ChangeAmt,
                            Mobile = user.Mobile,
                            RealName = user.RealName,
                            OrderNo = queryList.SeoKeyword,
                            UserId = queryList.UserId,
                        });
                    }
                    catch (Exception ex)
                    {
                        Utils.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "盟主兑换机具券异常");
                    }
                }
                else
                {
                    Thread.Sleep(5000);
                }
            }
        }

        public void dosomething(int Id, List<int> couponIds, List<string> codes, int count = 0)
        { 
            WebCMSEntities db = new WebCMSEntities();
            OpModels.WebCMSEntities opdb = new OpModels.WebCMSEntities();
            var query = db.LeaderReserveRecord.FirstOrDefault(m => m.Id == Id && m.Remark == "兑换机具券");
            if(query != null)
            {
                JsonData ApplyList = JsonMapper.ToObject(query.SeoTitle);
                UserRankItem orderUser = PosCouponPrizeService.Instance.GetUserLevel(query.UserId);
                string ParentNav = orderUser.ParentNav + "," + orderUser.Id + ",";
                string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                Array.Reverse(ParentNavList);
                int index = 0;
                bool BigLeaderFlag = false; //大盟主标记
                bool BuyPrizeFlag = false; //购机奖励发放标识
                decimal BuyPrize = 0; //购机奖励
                foreach(string ParentId in ParentNavList)
                {
                    UserRankItem parentUser = PosCouponPrizeService.Instance.GetUserLevel(int.Parse(ParentId));
                    index += 1;

                    //给券打大盟主标记
                    if(parentUser.LeaderLevel == 1 && PosCouponPrizeService.Instance.CheckLeaderReserve(db, count, parentUser.Id) && !BigLeaderFlag)
                    {
                        if(PosCouponPrizeService.Instance.CheckPosCouponLeaderFlag(db, parentUser.Id, count, codes) > 0)
                        {
                            BigLeaderFlag = true;
                        }
                    }
                    else if(parentUser.LeaderLevel == 2 && !BigLeaderFlag)
                    {
                        for (int i = 0; i < ApplyList.Count; i++)
                        {
                            int num = Convert.ToInt32(ApplyList[i]["Num"].ToString());
                            int Kind = Convert.ToInt32(ApplyList[i]["Type"].ToString());
                            int Step = 0;
                            if(Kind == 1)
                            {
                                Step = 3;
                            }
                            else
                            {
                                Step = 2;
                            }
                            int result = PosCouponPrizeService.Instance.SetPosCouponLeaderFlag(db, parentUser.Id, num / Step, couponIds, query.ChangeAmt);
                            if(result > 0) BigLeaderFlag = true;
                        }
                    }

                    if(parentUser.OperateLevel > 0)
                    {
                        int groupCount = 0;
                        for (int i = 0; i < ApplyList.Count; i++)
                        {
                            int num = Convert.ToInt32(ApplyList[i]["Num"].ToString());
                            int Kind = Convert.ToInt32(ApplyList[i]["Type"].ToString());
                            if(Kind == 1)
                            {
                                groupCount += num / 3;
                            }
                            else
                            {
                                groupCount += num / 2;
                            }
                        }
                        if(PosCouponPrizeService.Instance.CheckOpReserve(opdb, groupCount, parentUser.Id))
                        {
                            //购机奖
                            decimal CurBuyPrize = GetBuyPrize(parentUser, query);
                            decimal GetPrize = CurBuyPrize - BuyPrize;
                            int Kind = 0;
                            if(query.Remark == "兑换机具券")
                            {
                                Kind = 101;
                            }
                            if(GetPrize > 0 && !BuyPrizeFlag)
                            {
                                PosCouponPrizeService.Instance.OpAccount(db, Id, parentUser.Id, GetPrize, groupCount, 128, Kind);
                                BuyPrizeFlag = true;
                            }
                            if(CurBuyPrize == -1) BuyPrizeFlag = true;
                            if(parentUser.OperateLevel == 2 && CurBuyPrize == 100) BuyPrizeFlag = true;
                            BuyPrize = CurBuyPrize;
                        }
                    }
                }
            }
            db.Dispose();
            opdb.Dispose();
        }

        public void addprize(int Id)
        { 
            WebCMSEntities db = new WebCMSEntities();
            OpModels.WebCMSEntities opdb = new OpModels.WebCMSEntities();
            var query = db.LeaderReserveRecord.FirstOrDefault(m => m.Id == Id && m.Remark == "兑换机具券");
            if(query != null)
            {
                JsonData ApplyList = JsonMapper.ToObject(query.SeoTitle);
                UserRankItem orderUser = PosCouponPrizeService.Instance.GetUserLevel(query.UserId);
                string ParentNav = orderUser.ParentNav + "," + orderUser.Id + ",";
                string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                Array.Reverse(ParentNavList);
                int index = 0;
                bool BigLeaderFlag = false; //大盟主标记
                decimal BuyPrize = 0; //购机奖励
                foreach(string ParentId in ParentNavList)
                {
                    UserRankItem parentUser = PosCouponPrizeService.Instance.GetUserLevel(int.Parse(ParentId));
                    index += 1;

                    if(parentUser.OperateLevel > 0)
                    {
                        int groupCount = 0;
                        for (int i = 0; i < ApplyList.Count; i++)
                        {
                            int num = Convert.ToInt32(ApplyList[i]["Num"].ToString());
                            int Kind = Convert.ToInt32(ApplyList[i]["Type"].ToString());
                            if(Kind == 1)
                            {
                                groupCount += num / 3;
                            }
                            else
                            {
                                groupCount += num / 2;
                            }
                        }
                        if(PosCouponPrizeService.Instance.CheckOpReserve(opdb, groupCount, parentUser.Id))
                        {
                            //购机奖
                            decimal CurBuyPrize = GetBuyPrize(parentUser, query, groupCount);
                            decimal GetPrize = CurBuyPrize - BuyPrize;
                            int Kind = 0;
                            if(query.Remark == "兑换机具券")
                            {
                                Kind = 101;
                            }
                            if(GetPrize > 0 && !db.UserAccountRecord.Any(m => m.QueryCount == Id && m.ChangeType == 128)) 
                            {
                                PosCouponPrizeService.Instance.OpAccount(db, Id, parentUser.Id, GetPrize, groupCount, 128, Kind);
                            }
                            BuyPrize = CurBuyPrize;
                        }
                    }
                }
            }
            db.Dispose();
            opdb.Dispose();
        }

        /// <summary>
        /// 获取购机奖金额
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public decimal GetBuyPrize(UserRankItem user, LeaderReserveRecord record, int count = 0)
        {
            if(user.OperateLevel == 2) 
            {
                if(PosCouponPrizeService.Instance.TradeTeamCheck2(user.Id))
                {
                    return 60;
                }
                if(!PosCouponPrizeService.Instance.TradeTeamCheck(record.UserId))
                {
                    decimal Amount = count * 60;
                    RedisDbconn.Instance.AddList("TradeFilterQueue", "{\"OrderId\":\"" + record.Id + "\",\"PrizeUserId\":\"" + user.Id + "\",\"Amount\":\"" + Amount + "\",\"Kind\":\"2\"}");
                    return -1;
                }
                if(PosCouponPrizeService.Instance.CheckSpecialUserNav(record.UserId))
                {
                    return -1;
                }
                return 60;
            }
            if(user.OperateLevel == 3) return 80;
            if(user.OperateLevel == 4) return 100;
            return 0;
        }
    }
}