using AutoTurnOver.Services;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace AutoTurnOver.WeeklyStatistics
{
    public class RedundancyBackgrounService : BackgroundService
    {
        private Timer _timer;

        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(60));
            return Task.CompletedTask;
        }

        private void DoWork(object state)
        {
            var now = DateTime.Now;
            var dayOfWeek = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(now.DayOfWeek);
            if (now.Hour == 0 && now.Minute == 1 && dayOfWeek.Equals("星期一"))
            {
                try
                {
                    Console.WriteLine($"开始 执行汇总统计，线程Id：{Thread.CurrentThread.ManagedThreadId}，{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
                    new WeeklyStatisticsServices().TimingWeekRedundancyTask();
                    Console.WriteLine($"结束 执行汇总统计，线程Id：{Thread.CurrentThread.ManagedThreadId}，{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("推送pps回货异常" + ex.Message);
                    Console.WriteLine("推送pps回货异常" + ex.StackTrace);
                }

            }
        }

        public override void Dispose()
        {
            base.Dispose();
            _timer?.Dispose();
        }
    }
}
