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;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Application.Contracts;

namespace IRaCIS.Application.Services.BackGroundJob
{

    public class CancelTaskQuartZJob : IJob
    {

        private readonly IRepository<Subject> _subjectRepository;
        private readonly ILogger<CancelTaskQuartZJob> _logger;
        private readonly IRepository<VisitTask> _visitTaskRepository;

        public CancelTaskQuartZJob(IRepository<Subject> subjectRepository, IEasyCachingProvider provider, ILogger<CancelTaskQuartZJob> logger, IRepository<VisitTask> visitTaskRepository)
        {
            _subjectRepository = subjectRepository;
            _logger = logger;
            _visitTaskRepository = visitTaskRepository;
        }

        public async Task Execute(IJobExecutionContext context)

        {
            _logger.LogInformation($"开始执行QuartZ定时取消任务作业");

            try
            {
                JobDataMap dataMap = context.JobDetail.JobDataMap;

                bool isInOrder = (bool)dataMap.Get("IsInOrder");

                if (isInOrder)
                {
                    Guid subjectId = (Guid)dataMap.Get("SubjectId");

                    Guid trialReadingCriterionId = (Guid)dataMap.Get("TrialReadingCriterionId");
                   
                    await _visitTaskRepository.BatchUpdateNoTrackingAsync(t => t.SubjectId == subjectId && t.TrialReadingCriterionId==trialReadingCriterionId, u => new VisitTask() { SubjectCriterionClaimUserId = null });

                }
                else
                {
                    Guid id = (Guid)dataMap.Get("VisitTaskId");

                    await _visitTaskRepository.UpdatePartialFromQueryAsync(t => t.Id == id && t.ReadingTaskState!=ReadingTaskState.HaveSigned, u => new VisitTask() { DoctorUserId = null }, true);
                }

            }
            catch (Exception e)
            {
                _logger.LogError($"QuartZ定时取消任务异常" + e.Message);
            }
            _logger.LogInformation("QuartZ定时取消任务作业结束");
        }







    }
}