using AutoMapper;
using EasyCaching.Core;
using EntityFrameworkCore.Triggered;
using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.Service;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;

namespace IRaCIS.Core.Application.Triggers
{
    /// <summary>
    ///  处理  访视   末次评估  会影响Subject 状态
    /// </summary>
    public class SubjectVisitCheckPassedTrigger : IBeforeSaveTrigger<SubjectVisit>
    {

        private readonly IVisitTaskHelpeService _visitTaskHelpeService;

        private readonly IRepository<Subject> _subjectRepository;
        private readonly IRepository<ClinicalDataTrialSet> _clinicalDataTrialSetRepository;
        private readonly IRepository<ReadingClinicalData> _readingClinicalDataRepository;

        private readonly IRepository<ReadingQuestionCriterionTrial> _trialReadingCriterionRepository;




        public SubjectVisitCheckPassedTrigger(IRepository<Subject> subjectRepository,
             IRepository<ClinicalDataTrialSet> clinicalDataTrialSetRepository,
            IRepository<ReadingClinicalData> readingClinicalDataRepository,
            IVisitTaskHelpeService visitTaskHelpeService, IRepository<ReadingQuestionCriterionTrial> trialReadingCriterionRepository
       
            )
        {
        
            _subjectRepository = subjectRepository;
            _clinicalDataTrialSetRepository = clinicalDataTrialSetRepository;
            _readingClinicalDataRepository = readingClinicalDataRepository;
            this._clinicalDataTrialSetRepository = clinicalDataTrialSetRepository;
            _visitTaskHelpeService = visitTaskHelpeService;
            _trialReadingCriterionRepository = trialReadingCriterionRepository;
         
       
        }



        public async Task BeforeSave(ITriggerContext<SubjectVisit> context, CancellationToken cancellationToken)
        {
            var subjectVisit = context.Entity;


            if (context.ChangeType == ChangeType.Modified)
            {

                // 一致性核查通过  生成读片任务
                if (context.UnmodifiedEntity?.CheckState != subjectVisit.CheckState && subjectVisit.CheckState == CheckStateEnum.CVPassed)
                {
                    //退回或者重阅的任务一致性核查通过了  此时设置Subject 重阅影响状态
                    if (context.Entity.IsPMBackOrReReading == true)
                    {
                        await _subjectRepository.UpdatePartialFromQueryAsync(context.Entity.SubjectId, u => new Subject() { IsReReadingOrBackInfluenceAnalysis = false });
                    }

                    context.Entity.IsPMBackOrReReading = false;

                    await _visitTaskHelpeService.GenerateVisitTaskAsync(subjectVisit.TrialId, new List<Guid>() { subjectVisit.Id }, true);

                }

            }



        }
    }
}