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

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

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

    private void DoWorks()
    {
        while (true)
        {
            if (DateTime.Now.Hour >= 3)
            {
                string ActivityDate = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
                string check = function.ReadInstance("/Activity/RedPackage/" + ActivityDate + ".txt");
                if (string.IsNullOrEmpty(check))
                {
                    function.WritePage("/Activity/RedPackage/", ActivityDate + ".txt", DateTime.Now.ToString());
                    function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "生成指定未领取红包日志");
                    WebCMSEntities db = new WebCMSEntities();
                    try
                    {
                        // decimal TotalPrize = 888.88M;
                        // DateTime start = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 07:50:00");
                        // DateTime today = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00");
                        // string PreDate = DateTime.Now.AddDays(-2).ToString("yyyyMMdd");
                        List<decimal> list = new List<decimal>();
                        list.Add(88.88M);
                        list.Add(40.76M);
                        list.Add(38.88M);
                        list.Add(18.88M);
                        list.Add(15.88M);
                        list.Add(11.88M);
                        list.Add(8.88M);
                        list.Add(8.88M);
                        list.Add(8.88M);
                        list.Add(8.88M);
                        list.Add(8.88M);
                        list.Add(8.88M);
                        list.Add(8.88M);
                        list.Add(8.88M);
                        list.Add(8.88M);
                        list.Add(8.88M);
                        list.Add(8.88M);
                        list.Add(8.88M);
                        list.Add(8.88M);
                        list.Add(8.88M);
                        list.Add(8.88M);
                        list.Add(8.88M);
                        list.Add(8.88M);
                        list.Add(8.88M);
                        list.Add(8.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(5.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(3.88M);
                        list.Add(1.88M);
                        list.Add(1.88M);
                        list.Add(1.88M);
                        list.Add(1.88M);
                        list.Add(1.88M);
                        list.Add(1.88M);
                        list.Add(1.88M);
                        list.Add(1.88M);
                        list.Add(1.88M);
                        list.Add(1.88M);
                        list.Add(1.88M);
                        list.Add(1.88M);
                        list.Add(1.88M);
                        list.Add(1.88M);
                        list.Add(1.88M);
                        list.Add(1.88M);
                        list.Add(1.88M);
                        list.Add(1.88M);
                        list.Add(1.88M);
                        list.Add(1.88M);
                        // TotalPrize -= 88.88M;
                        // for (int i = 1; i < 150; i++)
                        // {
                        //     list.Add(0.88M);
                        //     TotalPrize -= 0.88M;
                        // }
                        // for (int i = 0; i < 150; i++)
                        // {
                        //     if (TotalPrize > 0)
                        //     {
                        //         int BigPrize = function.get_Random(1, 150);
                        //         decimal PrizeAmt = (decimal)function.get_Random(88, 1000) / 100M;
                        //         if (TotalPrize > PrizeAmt)
                        //         {
                        //             list[BigPrize] += PrizeAmt;
                        //             TotalPrize -= PrizeAmt;
                        //         }
                        //         else
                        //         {
                        //             list[BigPrize] += TotalPrize;
                        //             TotalPrize = 0;
                        //         }
                        //     }
                        //     else
                        //     {
                        //         break;
                        //     }
                        // }
                        foreach (decimal PrizeAmt in list)
                        {
                            db.ActivityRedPackageStock.Add(new ActivityRedPackageStock()
                            {
                                CreateDate = DateTime.Now,
                                PrizeAmt = PrizeAmt,
                                ActivityDate = ActivityDate,
                                SeoTitle = function.get_Random(20),
                            });
                        }
                        db.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "生成指定未领取红包异常");
                    }
                    db.Dispose();
                    function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "生成指定未领取红包日志");
                }
                redisStock();
            }
            Thread.Sleep(60000);
        }
    }

    // 将红包加入缓存
    public void redisStock()
    {
        string ActivityDate = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
        string check = function.ReadInstance("/Activity/RedPackageRedis/" + ActivityDate + ".txt");
        if (!string.IsNullOrEmpty(check))
        {
            return;
        }
        function.WritePage("/Activity/RedPackageRedis/", ActivityDate + ".txt", DateTime.Now.ToString());
        WebCMSEntities db = new WebCMSEntities();
        List<ActivityRedPackageStock> list = db.ActivityRedPackageStock.Where(m => m.ActivityDate == ActivityDate && m.PrizeAmt != 88.88M).OrderBy(m => m.SeoTitle).ToList();
        int i = 0;
        foreach(ActivityRedPackageStock sub in list)
        {
            i += 1;
            if(i == 18)
            {
                ActivityRedPackageStock best = db.ActivityRedPackageStock.FirstOrDefault(m => m.ActivityDate == ActivityDate && m.PrizeAmt == 88.88M);
                if(best != null)
                {
                    RedisDbconn.Instance.AddList("RedPackageList:" + ActivityDate, best);
                }
            }
            RedisDbconn.Instance.AddList("RedPackageList:" + ActivityDate, sub);
        }

        string PreDate = DateTime.Now.AddDays(-2).ToString("yyyyMMdd");
        string PreMakerCode = "";
        string PreRealName = "";
        decimal PrePrizeAmt = 0;
        bool checkPre = db.ActivityRedPackageStock.Any(m => m.ActivityDate == PreDate);
        if (checkPre)
        {
            ActivityRedPackageStock preInfo = db.ActivityRedPackageStock.Where(m => m.ActivityDate == PreDate).OrderByDescending(m => m.PrizeAmt).FirstOrDefault();
            if (preInfo != null)
            {
                Users user = db.Users.FirstOrDefault(m => m.Id == preInfo.UserId) ?? new Users();
                PreMakerCode = user.MakerCode;
                PreRealName = user.RealName;
                PrePrizeAmt = preInfo.PrizeAmt;
                RedisDbconn.Instance.Set("PreInfoString:" + PreDate, PreMakerCode + "|" + PreRealName + "|" + PrePrizeAmt);
                RedisDbconn.Instance.SetExpire("PreInfoString:" + PreDate, 7200);
            }
        }
        db.Dispose();
    }





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

    private void StartStatTop10Do()
    {
        while (true)
        {
            if(DateTime.Now.Hour >= 7 && DateTime.Now.Hour <= 10)
            {
                OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
                OtherMySqlConn.op("delete from ActivityRedPackageTop10");
                using (WebCMSEntities db = new WebCMSEntities())
                {
                    DataTable dt = OtherMySqlConn.dtable("select UserId,sum(PrizeAmt) from ActivityRedPackageJoins group by UserId order by sum(PrizeAmt) desc");
                    int index = 0;
                    foreach (DataRow dr in dt.Rows)
                    {
                        index += 1;
                        int UserId = int.Parse(dr["UserId"].ToString());
                        decimal PrizeAmt = decimal.Parse(dr[1].ToString());
                        db.ActivityRedPackageTop10.Add(new ActivityRedPackageTop10()
                        {
                            Sort = index,
                            UserId = UserId,
                            PrizeAmt = PrizeAmt,
                            Kind = 1,
                        });
                    }
                    dt = OtherMySqlConn.dtable("select UserId,count(Id) from ActivityRedPackageJoins group by UserId order by count(Id) desc");
                    index = 0;
                    foreach (DataRow dr in dt.Rows)
                    {
                        index += 1;
                        int UserId = int.Parse(dr["UserId"].ToString());
                        int PrizeCount = int.Parse(dr[1].ToString());
                        db.ActivityRedPackageTop10.Add(new ActivityRedPackageTop10()
                        {
                            Sort = index,
                            UserId = UserId,
                            TimeNum = PrizeCount,
                            Kind = 2,
                        });
                    }
                    db.SaveChanges();
                }
            }
            Thread.Sleep(300000);
        }
    }


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

    private void StartSendPrizeNewDo()
    {
        while (true)
        {
            string content = RedisDbconn.Instance.RPop<string>("RedPrizeQueue");
            if (!string.IsNullOrEmpty(content))
            {
                try
                {
                    string[] data = content.Split(':');
                    int Id = int.Parse(function.CheckInt(data[0]));
                    int UserId = int.Parse(function.CheckInt(data[1]));
                    string ActivityDate = data[2];
                    using (WebCMSEntities db = new WebCMSEntities())
                    {
                        ActivityRedPackageStock edit = db.ActivityRedPackageStock.FirstOrDefault(m => m.Id == Id);
                        if(edit != null)
                        {
                            edit.UserId = UserId;
                            edit.UpdateDate = DateTime.Now;
                            ActivityRedPackageJoins query = db.ActivityRedPackageJoins.Add(new ActivityRedPackageJoins()
                            {
                                CreateDate = DateTime.Now, //创建时间
                                Status = 1,
                                UserId = UserId, //创客
                                ActivityDate = ActivityDate, //期数
                                PrizeAmt = edit.PrizeAmt,
                            }).Entity;
                            db.SaveChanges();
                            StartGetAccount(db, UserId, query.Id, edit.PrizeAmt);
                        }
                    }
                }
                catch (Exception ex)
                {
                    function.WriteLog(ex.ToString(), "发放红包奖励异常");
                }
                Thread.Sleep(200);
            }
            else
            {
                Thread.Sleep(500);
            }
        }
    }
    
    private void StartGetAccount(WebCMSEntities db, int UserId, int Id, decimal PrizeAmt)
    {
        try
        {
            UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == UserId);
            if (account == null)
            {
                account = db.UserAccount.Add(new UserAccount()
                {
                    Id = UserId,
                    UserId = UserId,
                }).Entity;
                db.SaveChanges();
            }
            decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
            decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
            decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
            account.BalanceAmount += PrizeAmt;
            account.TotalAmount += PrizeAmt;
            decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
            decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
            decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
            UserAccountRecord userAccountRecord = db.UserAccountRecord.Add(new UserAccountRecord()
            {
                CreateDate = DateTime.Now,
                UpdateDate = DateTime.Now,
                UserId = UserId, //创客
                ChangeType = 31, //变动类型
                ChangeAmount = PrizeAmt, //变更金额
                BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                AfterTotalAmount = AfterTotalAmount, //变更后总金额
                BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                QueryCount = Id,
                Remark = "开机抢红包活动",
            }).Entity;
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            function.WriteLog(ex.ToString(), "领取红包奖励异常");
        }
    }    
}