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

public class AddPosCouponPrizeHelper
{
    public readonly static AddPosCouponPrizeHelper Instance = new AddPosCouponPrizeHelper();
    private AddPosCouponPrizeHelper()
    {
    }

    public void Start()
    {
        Thread th = new Thread(DoWorks);
        th.IsBackground = true;
        th.Start();
    }

    private void DoWorks()
    {
        while (true)
        {
            try
            {
                string content = RedisDbconn.Instance.RPop<string>("AddPosCouponPrizeQueue");
                if(!string.IsNullOrEmpty(content))
                {
                    int oid = int.Parse(content);
                    WebCMSEntities db = new WebCMSEntities();
                    DoSomething(db, oid);
                    db.Dispose();
                }
                else
                {
                    Thread.Sleep(60000);
                }
            }
            catch (Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "补下单机具券奖励异常");
            }
            Utils.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "补下单机具券奖励日志");
        }
    }

    public void DoSomething(WebCMSEntities db, int OrderId)
    {
        List<int> ids = new List<int>();
        ids.Add(10);
        ids.Add(11);
        ids.Add(77);
        ids.Add(78);
        ids.Add(79);
        Orders order = db.Orders.FirstOrDefault(m => m.Status > 0 && m.Id == OrderId && ids.Contains(m.ProductId));
        if(order != null)
        {
            OrderProduct pro = db.OrderProduct.FirstOrDefault(m => m.OrderId == order.Id) ?? new OrderProduct();
            // Users user = db.Users.FirstOrDefault(m => m.Id == order.UserId) ?? new Users();
            UserRankItem user = PosCouponPrizeService.Instance.GetUserLevel(db, order.UserId);
            List<int> prizeChk = new List<int>();
            if(!db.UserAccountRecord.Any(m => m.ChangeType == 112 && m.QueryCount == order.Id))
            {
                prizeChk.Add(1);
            }
            if(!db.UserAccountRecord.Any(m => m.ChangeType == 118 && m.QueryCount == order.Id))
            {
                prizeChk.Add(2);
            }
            if(!db.LeaderAccountRecord.Any(m => m.QueryCount == order.Id))
            {
                prizeChk.Add(3);
            }
            int ParentUserId = user.ParentUserId;
            bool buyPrize = false;
            bool OncePrizeFlag4 = true;
            int leaderFlag = 0;
            bool DirectPrizeFlag = true;
            bool PosCouponFlag = true;
            bool OperateFlag = true;
            if(user.LeaderLevel > 0 || user.UserType == 1) //盟主或运营中心
            {
                //推荐奖励
                if(prizeChk.Contains(1))
                {
                    AlipayPayBack2Service.Instance.DirectPrize(db, order.Id, order.UserId, pro.ProductCount);
                }
                DirectPrizeFlag = false;
                UserAccount acccount = db.UserAccount.FirstOrDefault(m => m.Id == order.UserId) ?? new UserAccount();
                if (acccount.LeaderReserve >= 400 * pro.ProductCount && !buyPrize)
                {
                    //购机奖励
                    if(prizeChk.Contains(2))
                    {
                        AlipayPayBack2Service.Instance.OpAccount(db, order, order.UserId, 100, 1);
                    }
                    buyPrize = true;
                }
                if(user.LeaderLevel == 2 && PosCouponFlag)
                {
                    if(PosCouponLeader(db, user.Id, pro.ProductCount, order.SnNos.Split(',')))
                    {
                        PosCouponFlag = false;
                    }
                }
                if(user.UserType == 1 && OperateFlag)
                {
                    PosCouponOp(db, user.Id, order.SnNos.Split(','));
                    OperateFlag = false;
                }
            }
            while (ParentUserId > 0)
            {
                // Users puser = db.Users.FirstOrDefault(m => m.Id == ParentUserId) ?? new Users();
                UserRankItem puser = PosCouponPrizeService.Instance.GetUserLevel(db, ParentUserId);
                if(DirectPrizeFlag)
                {
                    if(prizeChk.Contains(1))
                    {
                        AlipayPayBack2Service.Instance.DirectPrize(db, order.Id, ParentUserId, pro.ProductCount);
                    }
                    DirectPrizeFlag = false;
                }
                if (puser.LeaderLevel > 0)
                {
                    UserAccount acccount = db.UserAccount.FirstOrDefault(m => m.Id == puser.Id) ?? new UserAccount();
                    if (acccount.LeaderReserve >= 400 * pro.ProductCount && !buyPrize)
                    {
                        //购机奖励
                        if(prizeChk.Contains(2))
                        {
                            AlipayPayBack2Service.Instance.OpAccount(db, order, puser.Id, 100, 1);
                        }
                        buyPrize = true;
                    }

                    if (acccount.LeaderReserve >= 400 * pro.ProductCount && puser.LeaderLevel > leaderFlag && leaderFlag < 2 && OncePrizeFlag4)
                    {
                        if(prizeChk.Contains(3))
                        {
                            //扣减备用金
                            AlipayPayBack2Service.Instance.OpReserve(db, order, puser.Id, 400 * pro.ProductCount, 2, order.UserId, "购机奖励");
                            //返回到余额
                            AlipayPayBack2Service.Instance.OpLeaderAccount(db, order, puser.Id, 400, pro.ProductCount);
                        }
                        leaderFlag = puser.LeaderLevel;
                        OncePrizeFlag4 = false;
                    }
                }
                if(puser.LeaderLevel == 2 && PosCouponFlag)
                {
                    if(PosCouponLeader(db, puser.Id, pro.ProductCount, order.SnNos.Split(',')))
                    {
                        PosCouponFlag = false;
                    }
                }
                if(puser.UserType == 1 && OperateFlag)
                {
                    PosCouponOp(db, puser.Id, order.SnNos.Split(','));
                    OperateFlag = false;
                }
                ParentUserId = puser.ParentUserId;
            }            
        }
        db.Dispose();
    }

    public bool PosCouponLeader(WebCMSEntities db, int Id, int ProductCount, string[] Codes)
    {
        UserAccount pacccount = db.UserAccount.FirstOrDefault(m => m.Id == Id) ?? new UserAccount();
        foreach(string Code in Codes)
        {
            PosCoupons coupon = db.PosCoupons.FirstOrDefault(m => m.ExchangeCode == Code);
            if(coupon != null && pacccount.LeaderReserve >= 400 * ProductCount)
            {
                coupon.LeaderUserId = Id;
            }
            else
            {
                return false;
            }
        }
        db.SaveChanges();
        return true;
    }

    public void PosCouponOp(WebCMSEntities db, int Id, string[] Codes)
    {
        foreach(string Code in Codes)
        {
            PosCoupons coupon = db.PosCoupons.FirstOrDefault(m => m.ExchangeCode == Code);
            if(coupon != null)
            {
                coupon.OpId = Id;
            }
        }
        db.SaveChanges();
    }
}