using AutoMapper;
using EntityFrameworkCore.Triggered;
using IRaCIS.Core.Domain.Share;
using MassTransit;

namespace IRaCIS.Core.Application.Triggers
{
    /// <summary>
    /// 添加访视计划  要给改项目下的所有Subject 添加该访视
    /// </summary>
    public class AddSubjectTrigger : IBeforeSaveTrigger<Subject>
    {
        private readonly IRepository<SubjectVisit> _subjectVisitRepository;
        private readonly IRepository<ClinicalDataTrialSet> _clinicalDataTrialSetRepository;
        private readonly IRepository<ReadingClinicalData> _readingClinicalDataRepository;
        private readonly IRepository<VisitStage> _visitStageRepository;
        private readonly IRepository<Trial> _trialRepository;
        private readonly IMapper _mapper;

        public AddSubjectTrigger(IRepository<SubjectVisit> subjectVisitRepository,
            IRepository<ClinicalDataTrialSet> clinicalDataTrialSetRepository,
            IRepository<ReadingClinicalData> readingClinicalDataRepository,
            IMapper mapper, IRepository<VisitStage> visitStageRepository, IRepository<Trial> trialRepository)
        {
            _subjectVisitRepository = subjectVisitRepository;
            this._clinicalDataTrialSetRepository = clinicalDataTrialSetRepository;
            this._readingClinicalDataRepository = readingClinicalDataRepository;
            _trialRepository = trialRepository;

            _visitStageRepository = visitStageRepository;
            _mapper = mapper;
        }

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

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



                //添加受试者的时候，获取访视计划列表，添加到受试者访视表。
                var visitPlanList = await _visitStageRepository.Where(t => t.TrialId == subject.TrialId && t.IsConfirmed).ToListAsync();

                var svList = _mapper.Map<List<SubjectVisit>>(visitPlanList);

                var IsEnrollementQualificationConfirm = await _trialRepository.Where(t => t.Id == subject.TrialId).Select(u => u.IsEnrollementQualificationConfirm).FirstOrDefaultAsync();

              


           
                svList.ForEach(t =>
                {
                    t.Subject = subject;
                    t.SubjectId = subject.Id;
                    t.TrialId = subject.TrialId;
                    t.TrialSiteId = subject.TrialSiteId;
                    t.IsEnrollmentConfirm = t.IsBaseLine ? IsEnrollementQualificationConfirm : false;
                    t.Id = NewId.NextGuid();
                 
                });


                await _subjectVisitRepository.AddRangeAsync(svList);

                await _subjectVisitRepository.SaveChangesAsync();



            }
        }
    }
}