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;
using IRaCIS.Core.Domain.Share;

namespace IRaCIS.Application.Services.BackGroundJob
{

    public class CacheTrialStatusQuartZJob: IJob
    {

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

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

        public async Task Execute(IJobExecutionContext context)
        
        {
            _logger.LogInformation($"开始执行QuartZ定时任务作业");
            try
            {
                await MemoryCacheTrialStatus();

                await MemoryCacheAnonymizeData();

            }
            catch (Exception e)
            {
                _logger.LogError($" 查询和缓存过程出现异常"+e.Message);
            }
            _logger.LogInformation("QuartZ定时任务作业结束");
        }


        public async Task MemoryCacheTrialStatus()
        {
            var list = await _trialRepository.Select(t => new { TrialId = t.Id, TrialStatusStr = t.TrialStatusStr })
                  .ToListAsync();

            list.ForEach(t => _provider.Set(t.TrialId.ToString(), t.TrialStatusStr, TimeSpan.FromDays(7)));

        }

        public async Task MemoryCacheAnonymizeData()
        {
            var systemAnonymizationList = await _systemAnonymizationRepository.Where(t => t.IsEnable).ToListAsync();

            _provider.Set(StaticData.Anonymize.Anonymize_AddFixedFiled, systemAnonymizationList.Where(t => t.IsAdd && t.IsFixed).ToList(), TimeSpan.FromDays(7));
            _provider.Set(StaticData.Anonymize.Anonymize_AddIRCInfoFiled, systemAnonymizationList.Where(t => t.IsAdd && t.IsFixed == false).ToList(), TimeSpan.FromDays(7));
            _provider.Set(StaticData.Anonymize.Anonymize_FixedField, systemAnonymizationList.Where(t => t.IsAdd == false && t.IsFixed).ToList(), TimeSpan.FromDays(7));
            _provider.Set(StaticData.Anonymize.Anonymize_IRCInfoField, systemAnonymizationList.Where(t => t.IsAdd == false && t.IsFixed == false).ToList(), TimeSpan.FromDays(7));
        }



    }
}