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();

                        List<int> couponIds = new List<int>();

                        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.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;
                                    db.UserSnDelayChange.Add(new UserSnDelayChange()
                                    {
                                        CreateDate = DateTime.Now,
                                        QueryCount = Id,
                                        SnNo = posCoupon.ExchangeCode,
                                    });
                                    couponIds.Add(item.Id);
                                }
                            }
                            //大机
                            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.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;
                                    db.UserSnDelayChange.Add(new UserSnDelayChange()
                                    {
                                        CreateDate = DateTime.Now,
                                        QueryCount = Id,
                                        SnNo = posCoupon.ExchangeCode,
                                    });
                                    couponIds.Add(items.Id);
                                }
                            }
                            db.SaveChanges();
                        }
                        db.SaveChanges();
                        
                        dosomething(Id, couponIds);
                    }
                    catch (Exception ex)
                    {
                        function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "盟主兑换机具券异常");
                    }
                }
                else
                {
                    Thread.Sleep(5000);
                }
            }
        }

        public void dosomething(int Id, List<int> couponIds)
        { 
            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(db, 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(db, int.Parse(ParentId));
                    index += 1;

                    //给券打大盟主标记
                    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);
                            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);
                            decimal GetPrize = CurBuyPrize - BuyPrize;
                            int Kind = 0;
                            if(query.Remark == "兑换机具券")
                            {
                                Kind = 101;
                            }
                            if(GetPrize > 0) 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)
        {
            if(user.OperateLevel == 2) return 60;
            if(user.OperateLevel == 3) return 80;
            if(user.OperateLevel == 4) return 100;
            return 0;
        }
    }
}