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

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

        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(60));
            Console.WriteLine("执行缺货数据同步！");
            return Task.CompletedTask;
        }

        private void DoWork(object state)
        {
            var now = DateTime.Now;
            if (now.Hour == 9 && now.Minute == 1)
            {
                try
                {
                    Console.WriteLine($"开始 执行缺货数据同步，线程Id：{Thread.CurrentThread.ManagedThreadId}，{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
                    new WeeklyStatisticsServices().TimingWeekShortageTask();
                    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();
        }
    }
}
