using System;
using System.Threading;
using System.Linq;
using System.Data;
using Library;
using MySystem.Models;
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 LeaderUserId = 0;
                        var queryList = db.LeaderReserveRecord.FirstOrDefault(m => m.Id == Id) ?? new LeaderReserveRecord();
                        var userInfo = db.Users.FirstOrDefault(m => m.Id == queryList.UserId) ?? new Users();
                        if (userInfo.LeaderLevel == 2)
                        {
                            LeaderUserId = queryList.UserId;
                        }
                        else
                        {
                            string[] ParentNavList = userInfo.ParentNav.Trim(',').Replace(",,", ",").Split(',');
                            for (int j = ParentNavList.Length; j > 0; j--)
                            {
                                int userId = int.Parse(ParentNavList[j - 1]);
                                var user = db.Users.FirstOrDefault(m => m.Id == userId) ?? new Users();
                                //如果是小盟主，则查找该小盟主关联的大盟主储蓄金是否充足，是则给券打上关联大盟主标记
                                if(user.LeaderLevel == 1)
                                {
                                    // LeaderAccountRecord leaderItem = db.LeaderAccountRecord.FirstOrDefault(m => m.Sort == user.Id && m.LeaderId > 0 && m.LeaderReserve >= 400 * pro.ProductCount);
                                    // if(leaderItem != null)
                                    // {
                                    //     leaderItem.LeaderReserve -= 400 * pro.ProductCount;
                                    //     foreach(int couponId in couponIds)
                                    //     {
                                    //         PosCoupons coupon = db.PosCoupons.FirstOrDefault(m => m.Id == couponId);
                                    //         if(coupon != null)
                                    //         {
                                    //             coupon.LeaderUserId = leaderItem.LeaderId;
                                    //         }
                                    //     }
                                    //     db.SaveChanges();
                                    //     bigLeaderPrize = true;
                                    // }
                                }
                                if (user.LeaderLevel == 2)
                                {
                                    LeaderUserId = userId;
                                    break;
                                }
                                else
                                {
                                    continue;
                                }
                            }

                        }

                        JsonData ApplyList = JsonMapper.ToObject(queryList.SeoTitle);
                        var SnList = "";
                        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;
                                    posCoupon.LeaderUserId = LeaderUserId;
                                    // SnList += posCoupon.ExchangeCode + ",";
                                    db.UserSnDelayChange.Add(new UserSnDelayChange()
                                    {
                                        CreateDate = DateTime.Now,
                                        QueryCount = Id,
                                        SnNo = posCoupon.ExchangeCode,
                                    });
                                }
                            }
                            //大机
                            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;
                                    posCoupon.LeaderUserId = LeaderUserId;
                                    // SnList += posCoupon.ExchangeCode + ",";
                                    db.UserSnDelayChange.Add(new UserSnDelayChange()
                                    {
                                        CreateDate = DateTime.Now,
                                        QueryCount = Id,
                                        SnNo = posCoupon.ExchangeCode,
                                    });
                                }
                            }
                            db.SaveChanges();
                        }
                        // queryList.SeoDescription = SnList.TrimEnd(',');
                        db.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "盟主兑换机具券异常");
                    }
                }
                else
                {
                    Thread.Sleep(5000);
                }
            }
        }
    }
}