using Hangfire;
using Hangfire.Storage;
using IRaCIS.Core.Application.Helper;
using IRaCIS.Core.Domain.Share;
using Microsoft.Extensions.Logging;

namespace IRaCIS.Core.Application.Service.BackGroundJob
{

    public interface IIRaCISHangfireJob
    {

        //Task MemoryCacheTrialStatusAsync();

        Task InitHangfireJobTaskAsync();

    }
    public class IRaCISCHangfireJob(ILogger<IRaCISCHangfireJob> _logger,
         IRepository<Internationalization> _internationalizationRepository,
         IRepository<TrialEmailNoticeConfig> _trialEmailNoticeConfigRepository
        ) : IIRaCISHangfireJob
    {
        public static string JsonFileFolder = Path.Combine(AppContext.BaseDirectory, StaticData.Folder.Resources);


        public async Task InitHangfireJobTaskAsync()
        {
            _logger.LogInformation("项目启动 hangfire 任务初始化 执行开始~");

            //初始化国际化

            await InternationalizationHelper.InitInternationlizationDataAndWatchJsonFileAsync(_internationalizationRepository);

            //创建邮件定时任务
            await InitSysAndTrialCronJobAsync();

            #region 废弃
            ////项目状态 立即加载到缓存中
            //await MemoryCacheTrialStatusAsync();

            ////await MemoryCacheAnonymizeData();


            ////创建项目缓存 定时任务
            //HangfireJobHelper.AddOrUpdateInitCronJob<IIRaCISHangfireJob>("RecurringJob_Cache_TrialState", t => t.MemoryCacheTrialStatusAsync(), Cron.Daily());
            #endregion


            _logger.LogInformation("项目启动 hangfire 任务初始化 执行结束");
        }







        public async Task InitSysAndTrialCronJobAsync()
        {
            //var deleteJobIdList = await _trialEmailNoticeConfigRepository.Where(t => t.Trial.TrialStatusStr != StaticData.TrialState.TrialOngoing && t.EmailCron != string.Empty && t.IsAutoSend)
            //   .Select(t => t.TrialId + "_" + t.Id)
            //    .ToListAsync();

            //foreach (var jobId in deleteJobIdList)
            //{
            //    HangfireJobHelper.RemoveCronJob(jobId);
            //}


            var taskInfoList = await _trialEmailNoticeConfigRepository.Where(t => t.Trial.TrialStatusStr == StaticData.TrialState.TrialOngoing && t.EmailCron != string.Empty && t.IsAutoSend)
                  .Select(t => new { t.Id, t.Code, t.EmailCron, t.BusinessScenarioEnum, t.TrialId })
                  .ToListAsync();

            foreach (var task in taskInfoList)
            {
                //利用主键作为任务Id
                var jobId = $"{task.TrialId}_{task.Id}";

                HangfireJobHelper.AddOrUpdateTrialCronJob(jobId, task.TrialId, task.BusinessScenarioEnum, task.EmailCron);
            }

            var addOrUpdateJobIdList = taskInfoList.Select(t => $"{t.TrialId}_{t.Id}").ToList();

            var list = JobStorage.Current.GetConnection().GetRecurringJobs().ToList();

            //项目定时任务都在default 队列
            //var dbJobIdList = JobStorage.Current.GetConnection().GetRecurringJobs().Where(t => t.Queue == "default").Select(t => t.Id).ToList();

            //var deleteList=  dbJobIdList.Except(addOrUpdateJobIdList).ToList();

            //  foreach (var jobId in deleteList)
            //  {
            //      HangfireJobHelper.RemoveCronJob(jobId);
            //  }


        }



    }


}
