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

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


        //激活奖
        public void StartAct()
        {
            Thread th = new Thread(StartActListen);
            th.IsBackground = true;
            th.Start();
        }
        
        private void StartActListen()
        {
            while(true)
            {
                if(RedisDbconn.Instance.Get<string>("ActiveRewardThreadStatus") == "1")
                {
                    StartActDo();
                    Thread.Sleep(5000);
                }
            }
        }

        public void StartActDo()
        {
            WebCMSEntities db = new WebCMSEntities();
            Models.KxsMain.WebCMSEntities kxsdb = new Models.KxsMain.WebCMSEntities();
            DateTime yesterday = DateTime.Now.AddDays(-1);
            IQueryable<MerchantDepositOrder> orderList = db.MerchantDepositOrder.Where(m => m.Status == 1 && m.UpdateDate >= yesterday);
            foreach (MerchantDepositOrder order in orderList.ToList())
            {
                doActiveReward(db, kxsdb, order, 300);
                RedisDbconn.Instance.AddList("OpenRewardQueue2", order.MerchantId);
                RedisDbconn.Instance.AddList("LeaderPrizeQueue2", order.MerchantId);
                RedisDbconn.Instance.AddList("OperatePrizeQueue2", order.MerchantId);
                MerchantDepositOrder edit = db.MerchantDepositOrder.FirstOrDefault(m => m.Id == order.Id);
                if(edit != null)
                {
                    edit.Status = 2;
                    db.SaveChanges();
                }
            }
            db.Dispose();
            kxsdb.Dispose();
        }

        public void doActiveReward(WebCMSEntities db, Models.KxsMain.WebCMSEntities kxsdb, MerchantDepositOrder order, decimal ActPrize)
        {
            MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantInfo();
            Models.KxsMain.Users user = kxsdb.Users.FirstOrDefault(m => m.Id == merchant.UserId) ?? new Models.KxsMain.Users();
            int GetUserId = user.Id;
            string ParentNav = user.ParentNav;
            int TopUserId = 0;
            if (!string.IsNullOrEmpty(ParentNav))
            {
                TopUserId = int.Parse(ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
            }
            string IdBrand = GetUserId + "_0";
            UserMachineData userData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
            if (userData == null)
            {
                userData = db.UserMachineData.Add(new UserMachineData()
                {
                    IdBrand = IdBrand,
                }).Entity;
                db.SaveChanges();
            }
            userData.ActProfit += ActPrize;
            db.SaveChanges();
            Models.KxsMain.UserAccount account = kxsdb.UserAccount.FirstOrDefault(m => m.Id == GetUserId);
            if (account == null)
            {
                account = kxsdb.UserAccount.Add(new Models.KxsMain.UserAccount()
                {
                    Id = GetUserId,
                    UserId = GetUserId,
                }).Entity;
                kxsdb.SaveChanges();
            }
            decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
            decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
            decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
            account.BalanceAmount += ActPrize;
            account.TotalAmount += ActPrize;
            decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
            decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
            decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
            Models.KxsMain.UserAccountRecord userAccountRecord = kxsdb.UserAccountRecord.Add(new Models.KxsMain.UserAccountRecord()
            {
                CreateDate = DateTime.Now,
                UpdateDate = DateTime.Now,
                UserId = GetUserId, //创客
                ChangeType = 311, //变动类型
                ChangeAmount = ActPrize, //变更金额
                BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                AfterTotalAmount = AfterTotalAmount, //变更后总金额
                BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                QueryCount = merchant.Id,
            }).Entity;
            kxsdb.SaveChanges();
        }








        //开户奖
        public void StartOpenReward()
        {
            Thread th = new Thread(StartOpenRewardDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StartOpenRewardDo()
        {
            while(true)
            {
                string content = RedisDbconn.Instance.RPop<string>("OpenRewardQueue2");
                if(!string.IsNullOrEmpty(content))
                {
                    try
                    {
                        WebCMSEntities db = new WebCMSEntities();
                        Models.KxsMain.WebCMSEntities kxsdb = new Models.KxsMain.WebCMSEntities();
                        function.WriteLog("\n\n" + DateTime.Now.ToString() + "\nposid:" + content, "开机奖励发放日志");
                        int MerchantId = int.Parse(content);
                        MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId);
                        if (merchant != null)
                        {
                            function.WriteLog("商户:" + merchant.Name, "开机奖励发放日志");
                            Models.KxsMain.Users user = kxsdb.Users.FirstOrDefault(m => m.Id == merchant.UserId);
                            if (user != null)
                            {
                                function.WriteLog("所属人:" + user.MakerCode, "开机奖励发放日志");
                                string ParentNav = function.CheckNull(user.ParentNav) + "," + user.Id + ",";
                                if (!string.IsNullOrEmpty(ParentNav))
                                {
                                    decimal Prize = 20;
                                    string[] ParentNavs = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                                    for (int i = ParentNavs.Length - 1; i >= 0; i--)
                                    {
                                        int UserId = int.Parse(ParentNavs[i]);
                                        Models.KxsMain.Users puser = kxsdb.Users.FirstOrDefault(m => m.Id == UserId && m.AuthFlag == 1 && m.Status > -1);
                                        if (puser != null && Prize > 0)
                                        {
                                            function.WriteLog("上级:" + puser.MakerCode, "开机奖励发放日志");
                                            function.WriteLog("条件:LeaderLevel:" + puser.LeaderLevel + ",UserType:" + puser.UserType, "开机奖励发放日志");
                                            if(puser.LeaderLevel > 0 || puser.UserType == 1)
                                            {
                                                bool leaderOp = true;
                                                if(puser.LeaderLevel > 0 && puser.UserType == 0)
                                                {
                                                    DateTime now = DateTime.Now;
                                                    leaderOp = kxsdb.Leaders.Any(m => m.Id == puser.Id && m.ExpiredDate >= now);
                                                    function.WriteLog("条件:leaderOp:" + leaderOp, "开机奖励发放日志");
                                                }
                                                if(leaderOp)
                                                {
                                                    function.WriteLog("满足条件", "开机奖励发放日志");
                                                    int pTopUserId = 0;
                                                    if (!string.IsNullOrEmpty(puser.ParentNav))
                                                    {
                                                        pTopUserId = int.Parse(puser.ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                                                    }
                                                    string IdBrand = puser.Id + "_0";
                                                    UserMachineData userData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
                                                    if (userData == null)
                                                    {
                                                        userData = db.UserMachineData.Add(new UserMachineData()
                                                        {
                                                            IdBrand = IdBrand,
                                                        }).Entity;
                                                        db.SaveChanges();
                                                    }
                                                    userData.OpenProfit += Prize;
                                                    db.SaveChanges();
                                                    //账户入库
                                                    Models.KxsMain.UserAccount account = kxsdb.UserAccount.FirstOrDefault(m => m.Id == puser.Id);
                                                    if (account == null)
                                                    {
                                                        account = kxsdb.UserAccount.Add(new Models.KxsMain.UserAccount()
                                                        {
                                                            Id = puser.Id,
                                                            UserId = puser.Id,
                                                        }).Entity;
                                                        kxsdb.SaveChanges();
                                                    }
                                                    //收支明细入库
                                                    decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                                                    decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                                                    decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                                                    account.BalanceAmount += Prize;
                                                    account.TotalAmount += Prize;
                                                    decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                                                    decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                                                    decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                                                    Models.KxsMain.UserAccountRecord userAccountRecord = kxsdb.UserAccountRecord.Add(new Models.KxsMain.UserAccountRecord()
                                                    {
                                                        CreateDate = DateTime.Now,
                                                        UpdateDate = DateTime.Now,
                                                        UserId = puser.Id, //创客
                                                        ChangeType = 312, //变动类型
                                                        ChangeAmount = Prize, //变更金额
                                                        BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                                                        AfterTotalAmount = AfterTotalAmount, //变更后总金额
                                                        BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                                                        AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                                                        BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                                                        AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                                                        QueryCount = MerchantId,
                                                    }).Entity;
                                                    kxsdb.SaveChanges();
                                                    Prize = 0;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        db.Dispose();
                        kxsdb.Dispose();
                    }
                    catch(Exception ex)
                    {
                        function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "实时获取开机奖励异常");
                    }
                }
                else
                {
                    Thread.Sleep(5000);
                }
            }
        }



        //盟主奖
        public void StartLeaderReward()
        {
            Thread th = new Thread(StartLeaderRewardDo);
            th.IsBackground = true;
            th.Start();
        }

        public void StartLeaderRewardDo()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("LeaderPrizeQueue2");
                if (!string.IsNullOrEmpty(content))
                {
                    try
                    {
                        WebCMSEntities db = new WebCMSEntities();
                        Models.KxsMain.WebCMSEntities kxsdb = new Models.KxsMain.WebCMSEntities();
                        function.WriteLog("\n\n" + DateTime.Now.ToString() + "\nposid:" + content, "盟主奖励发放日志");
                        int MerchantId = int.Parse(content);
                        MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId);
                        if (merchant != null)
                        {
                            function.WriteLog("商户:" + merchant.Name, "盟主奖励发放日志");
                            Models.KxsMain.Users user = kxsdb.Users.FirstOrDefault(m => m.Id == merchant.UserId);
                            if (user != null)
                            {
                                function.WriteLog("所属人:" + user.MakerCode, "盟主奖励发放日志");
                                string ParentNav = function.CheckNull(user.ParentNav) + "," + user.Id + ",";
                                if (!string.IsNullOrEmpty(ParentNav))
                                {
                                    decimal Prize = 10;
                                    string[] ParentNavs = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                                    for (int i = ParentNavs.Length - 1; i >= 0; i--)
                                    {
                                        int UserId = int.Parse(ParentNavs[i]);
                                        Models.KxsMain.Users puser = kxsdb.Users.FirstOrDefault(m => m.Id == UserId && m.AuthFlag == 1 && m.Status > -1);
                                        if (puser != null && Prize > 0)
                                        {
                                            function.WriteLog("上级:" + puser.MakerCode, "盟主奖励发放日志");
                                            function.WriteLog("条件:LeaderLevel:" + puser.LeaderLevel + ",UserType:" + puser.UserType, "盟主奖励发放日志");
                                            if(puser.LeaderLevel == 2)
                                            {
                                                DateTime now = DateTime.Now;
                                                bool leaderOp = kxsdb.Leaders.Any(m => m.Id == puser.Id && m.ExpiredDate >= now);
                                                function.WriteLog("条件:leaderOp:" + leaderOp, "盟主奖励发放日志");
                                                if(leaderOp)
                                                {
                                                    function.WriteLog("满足条件", "盟主奖励发放日志");
                                                    int pTopUserId = 0;
                                                    if (!string.IsNullOrEmpty(puser.ParentNav))
                                                    {
                                                        pTopUserId = int.Parse(puser.ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                                                    }
                                                    string IdBrand = puser.Id + "_0";
                                                    UserMachineData userData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
                                                    if (userData == null)
                                                    {
                                                        userData = db.UserMachineData.Add(new UserMachineData()
                                                        {
                                                            IdBrand = IdBrand,
                                                        }).Entity;
                                                        db.SaveChanges();
                                                    }
                                                    userData.OpenProfit += Prize;
                                                    db.SaveChanges();
                                                    //账户入库
                                                    Models.KxsMain.UserAccount account = kxsdb.UserAccount.FirstOrDefault(m => m.Id == puser.Id);
                                                    if (account == null)
                                                    {
                                                        account = kxsdb.UserAccount.Add(new Models.KxsMain.UserAccount()
                                                        {
                                                            Id = puser.Id,
                                                            UserId = puser.Id,
                                                        }).Entity;
                                                        kxsdb.SaveChanges();
                                                    }
                                                    //收支明细入库
                                                    decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                                                    decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                                                    decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                                                    account.BalanceAmount += Prize;
                                                    account.TotalAmount += Prize;
                                                    decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                                                    decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                                                    decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                                                    Models.KxsMain.UserAccountRecord userAccountRecord = kxsdb.UserAccountRecord.Add(new Models.KxsMain.UserAccountRecord()
                                                    {
                                                        CreateDate = DateTime.Now,
                                                        UpdateDate = DateTime.Now,
                                                        UserId = puser.Id, //创客
                                                        ChangeType = 313, //变动类型
                                                        ChangeAmount = Prize, //变更金额
                                                        BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                                                        AfterTotalAmount = AfterTotalAmount, //变更后总金额
                                                        BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                                                        AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                                                        BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                                                        AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                                                        QueryCount = MerchantId,
                                                    }).Entity;
                                                    kxsdb.SaveChanges();
                                                    Prize = 0;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        db.Dispose();
                        kxsdb.Dispose();
                    }
                    catch (Exception ex)
                    {
                        function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "盟主奖发放日志异常");
                    }
                    Thread.Sleep(100);
                }
                else
                {
                    Thread.Sleep(60000);
                }
            }
        }



        //运营中心奖
        public void StartOperateReward()
        {
            Thread th = new Thread(StartOperateRewardDo);
            th.IsBackground = true;
            th.Start();
        }

        public void StartOperateRewardDo()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("OperatePrizeQueue2");
                if (!string.IsNullOrEmpty(content))
                {
                    try
                    {
                        WebCMSEntities db = new WebCMSEntities();
                        Models.KxsMain.WebCMSEntities kxsdb = new Models.KxsMain.WebCMSEntities();
                        function.WriteLog("\n\n" + DateTime.Now.ToString() + "\nposid:" + content, "运营中心奖励发放日志");
                        int MerchantId = int.Parse(content);
                        MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId);
                        if (merchant != null)
                        {
                            function.WriteLog("商户:" + merchant.Name, "运营中心奖励发放日志");
                            Models.KxsMain.Users user = kxsdb.Users.FirstOrDefault(m => m.Id == merchant.UserId);
                            if (user != null)
                            {
                                function.WriteLog("所属人:" + user.MakerCode, "运营中心奖励发放日志");
                                string ParentNav = function.CheckNull(user.ParentNav) + "," + user.Id + ",";
                                if (!string.IsNullOrEmpty(ParentNav))
                                {
                                    decimal Prize = 5;
                                    string[] ParentNavs = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                                    for (int i = ParentNavs.Length - 1; i >= 0; i--)
                                    {
                                        int UserId = int.Parse(ParentNavs[i]);
                                        Models.KxsMain.Users puser = kxsdb.Users.FirstOrDefault(m => m.Id == UserId && m.AuthFlag == 1 && m.Status > -1);
                                        if (puser != null && Prize > 0)
                                        {
                                            function.WriteLog("上级:" + puser.MakerCode, "运营中心奖励发放日志");
                                            function.WriteLog("条件:LeaderLevel:" + puser.LeaderLevel + ",UserType:" + puser.UserType, "运营中心奖励发放日志");
                                            if(puser.UserType == 1)
                                            {
                                                function.WriteLog("满足条件", "运营中心奖励发放日志");
                                                int pTopUserId = 0;
                                                if (!string.IsNullOrEmpty(puser.ParentNav))
                                                {
                                                    pTopUserId = int.Parse(puser.ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                                                }
                                                string IdBrand = puser.Id + "_0";
                                                UserMachineData userData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
                                                if (userData == null)
                                                {
                                                    userData = db.UserMachineData.Add(new UserMachineData()
                                                    {
                                                        IdBrand = IdBrand,
                                                    }).Entity;
                                                    db.SaveChanges();
                                                }
                                                userData.OpenProfit += Prize;
                                                db.SaveChanges();
                                                //账户入库
                                                Models.KxsMain.UserAccount account = kxsdb.UserAccount.FirstOrDefault(m => m.Id == puser.Id);
                                                if (account == null)
                                                {
                                                    account = kxsdb.UserAccount.Add(new Models.KxsMain.UserAccount()
                                                    {
                                                        Id = puser.Id,
                                                        UserId = puser.Id,
                                                    }).Entity;
                                                    kxsdb.SaveChanges();
                                                }
                                                //收支明细入库
                                                decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                                                decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                                                decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                                                account.BalanceAmount += Prize;
                                                account.TotalAmount += Prize;
                                                decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                                                decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                                                decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                                                Models.KxsMain.UserAccountRecord userAccountRecord = kxsdb.UserAccountRecord.Add(new Models.KxsMain.UserAccountRecord()
                                                {
                                                    CreateDate = DateTime.Now,
                                                    UpdateDate = DateTime.Now,
                                                    UserId = puser.Id, //创客
                                                    ChangeType = 314, //变动类型
                                                    ChangeAmount = Prize, //变更金额
                                                    BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                                                    AfterTotalAmount = AfterTotalAmount, //变更后总金额
                                                    BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                                                    AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                                                    BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                                                    AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                                                    QueryCount = MerchantId,
                                                }).Entity;
                                                kxsdb.SaveChanges();
                                                Prize = 0;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        db.Dispose();
                        kxsdb.Dispose();
                    }
                    catch (Exception ex)
                    {
                        function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "运营中心奖发放日志异常");
                    }
                    Thread.Sleep(100);
                }
                else
                {
                    Thread.Sleep(60000);
                }
            }
        }

        
    }
}