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

/// <summary>
/// 每月一号记录上月盟主储蓄金和可提现余额
/// </summary>
public class LeaderAmountMonthChangeQueue
{
    public readonly static LeaderAmountMonthChangeQueue Instance = new LeaderAmountMonthChangeQueue();
    private LeaderAmountMonthChangeQueue()
    {
    }

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

    private void StartDo()
    {
        while (true)
        {
            if (DateTime.Now.Day == 1 && DateTime.Now.Hour > 1 && DateTime.Now.Hour < 10)
            {
                try
                {
                    string check = function.ReadInstance("/LeaderAmountMonthChange/check" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
                    if (string.IsNullOrEmpty(check))
                    {
                        function.WritePage("/LeaderAmountMonthChange/", "check" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt", DateTime.Now.ToString("HH:mm:ss"));
                        WebCMSEntities db = new WebCMSEntities();
                        var leaders = db.Leaders.Select(m => new { m.UserId, m.ExpiredDate }).ToList();
                        foreach (var item in leaders)
                        {
                            var userAccount = db.UserAccount.FirstOrDefault(m => m.Id == item.UserId) ?? new UserAccount();
                            var leaderInfo = db.Leaders.FirstOrDefault(m => m.Id == item.UserId) ?? new Leaders();
                            db.LeaderReconRecord.Add(new LeaderReconRecord()
                            {
                                CreateDate = DateTime.Now,
                                UserId = item.UserId,
                                StatMonth = DateTime.Now.ToString("yyyy-MM"),
                                ReserveAmount = userAccount.LeaderReserve,
                                BalanceAmount = userAccount.LeaderBalanceAmount
                            });
                            db.SaveChanges();
                        }
                    }
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "每月一号记录上月盟主储蓄金和可提现余额线程异常");
                }
            }
            Thread.Sleep(60000);
        }
    }
}