using Microsoft.Extensions.Hosting;
using System.Threading;
using System;
using System.Threading.Tasks;
using MassTransit;
using IRaCIS.Core.Domain.Models;
using IRaCIS.Core.Infra.EFCore;
using Microsoft.Extensions.Logging;
using Hangfire;
using IRaCIS.Core.Application.Helper;
using IRaCIS.Core.Application.MassTransit.Consumer;
using IRaCIS.Core.Domain.Share;
using MassTransit.Scheduling;
using Hangfire.Storage;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using MassTransit.Mediator;
using Microsoft.Extensions.Configuration;

namespace IRaCIS.Core.API.HostService;

public class HangfireHostService(IRecurringMessageScheduler _recurringMessageScheduler, 
    IRepository<TrialEmailNoticeConfig> _trialEmailNoticeConfigRepository,
    IConfiguration _config,
     IRepository<EmailNoticeConfig> _emailNoticeConfigrepository,
    IMediator _mediator,
    ILogger<HangfireHostService> _logger) : IHostedService
{
  

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


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

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

        // 清除所有可能存在的定时任务，防止类型加载错误
        var allJobIdList = JobStorage.Current.GetConnection().GetRecurringJobs().Select(t => t.Id).ToList();
        foreach (var jobId in allJobIdList)
        {
            try
            {
                HangfireJobHelper.RemoveCronJob(jobId);
                _logger.LogInformation($"已清除定时任务: {jobId}");
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"清除定时任务 {jobId} 时出错: {ex.Message}");
            }
        }

        string defaultCulture = _config.GetValue<string>("SystemEmailSendConfig:CronEmailDefaultCulture");

        // 项目手动选择，周期性邮件 
        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, TrialCode = t.Trial.TrialCode, t.EmailCron, t.BusinessScenarioEnum, t.TrialId })
              .ToListAsync();

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

            var trialId = task.TrialId;

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


        // 系统邮件定时任务  要设置默认语言
        var systemTaskInfoList = await _emailNoticeConfigrepository.Where(t => t.EmailCron != string.Empty && t.IsAutoSend)
          .Select(t => new { t.Id, t.Code,  t.EmailCron, t.BusinessScenarioEnum, })
          .ToListAsync();

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

            HangfireJobHelper.AddOrUpdateTimingCronJob(jobId, task.BusinessScenarioEnum, task.EmailCron, defaultCulture);
        }


        //await _recurringMessageScheduler.ScheduleRecurringPublish(new QCImageQuestionSchedule() { CronExpression = "0/3 * * * * ? " }, new MasstransiTestCommand { value = "message at " + DateTime.Now.ToString() });



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

    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;


}
