using System;
using System.Linq;
using System.Threading.Tasks;
using EasyCaching.Core;
using IRaCIS.Core.Domain;
using IRaCIS.Core.Infra.EFCore;
using IRaCIS.Core.Domain.Models;
using Microsoft.Extensions.Logging;
using Quartz;

namespace IRaCIS.Application.Services.BackGroundJob
{

    public class CacheTrialStatusQuartZJob: IJob
    {

        private readonly IRepository<Trial> _trialRepository;
        private readonly IEasyCachingProvider _provider;
        private readonly ILogger<CacheTrialStatusQuartZJob> _logger;

        public CacheTrialStatusQuartZJob(IRepository<Trial> trialRepository, IEasyCachingProvider provider,ILogger<CacheTrialStatusQuartZJob> logger)
        {
            _trialRepository = trialRepository;
            _provider = provider;
            _logger = logger;
        }

        public Task Execute(IJobExecutionContext context)
        
        {
            _logger.LogInformation($"开始执行QuartZ定时任务作业");
            try
            {
                var list = _trialRepository.Select(t => new { TrialId = t.Id, TrialStatusStr = t.TrialStatusStr })
                    .ToList();

                list.ForEach(t => _provider.Set(t.TrialId.ToString(), t.TrialStatusStr, TimeSpan.FromDays(1)));
               
            }
            catch (Exception e)
            {
                _logger.LogError($" 查询和缓存过程出现异常"+e.Message);
            }
            _logger.LogInformation("QuartZ定时任务作业结束");
            return Task.CompletedTask;
        }

      

       
    }
}