using IRaCIS.Core.Infra.EFCore;
using Microsoft.Extensions.Logging;

namespace IRaCIS.Core.Application.BackGroundJob
{
    public interface IObtainTaskAutoCancelJob
    {
      Task  CancelQCObtaion(Guid subjectVisitId,DateTime startTime);
    }

    public class ObtainTaskAutoCancelJob : IObtainTaskAutoCancelJob
    {
        private readonly IRepository<SubjectVisit> _subjectVisitRepository;
        private readonly ILogger<ObtainTaskAutoCancelJob> _logger;

        public ObtainTaskAutoCancelJob(IRepository<SubjectVisit> subjectVisitRepository,  ILogger<ObtainTaskAutoCancelJob> logger)
        {
            _subjectVisitRepository = subjectVisitRepository;
            _logger = logger;
        }
        public async Task CancelQCObtaion(Guid subjectVisitId, DateTime startTime)
        {
            try
            {
                var dbSubjectVisit = await _subjectVisitRepository.FirstOrDefaultAsync(t => t.Id == subjectVisitId).IfNullThrowException();

                dbSubjectVisit.IsTake = false;
                dbSubjectVisit.CurrentActionUserId = null;
                dbSubjectVisit.CurrentActionUserExpireTime = null;

                var success = await _subjectVisitRepository.SaveChangesAsync();

                _logger.LogWarning($"任务建立时间:{startTime}  取消时间：{DateTime.Now} 取消 受试者访视：{ subjectVisitId }success:{success}"); 
            }
            catch (Exception e)
            {
                _logger.LogError("hangfire 定时任务执行失败" + e.Message);

            }

        }
    }
}
