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 triconfig = await _trialRepository.Where(t => t.Id == subject.TrialId).Select(u => new { u.IsEnrollementQualificationConfirm,u.IsPDProgressView }).FirstOrDefaultAsync();
                      
                svList.ForEach(t =>
                {
                    t.Subject = subject;
                    t.SubjectId = subject.Id;
                    t.TrialId = subject.TrialId;
                    t.SiteId = subject.SiteId;
                    t.IsEnrollmentConfirm = t.IsBaseLine ? triconfig.IsEnrollementQualificationConfirm : false;
                    t.PDState = t.IsBaseLine==false && triconfig.IsPDProgressView ? PDStateEnum.PDProgress : PDStateEnum.None;
                    t.Id = NewId.NextGuid();
                 
                });


                await _subjectVisitRepository.AddRangeAsync(svList);

                await _subjectVisitRepository.SaveChangesAsync();

                #region 在f访视计划确认的时候处理 给subject添加访视计划
                ////已添加受试者  都不存在该新增的计划名称 那么该项目所有受试者都增加一个访视记录
                //if (!await _subjectVisitRepository.AnyAsync(t => t.VisitName == visitPlan.VisitName && t.TrialId == visitPlan.TrialId))
                //{
                //    var subjectSVS = await _subjectVisitRepository.Where(t => t.TrialId == visitPlan.TrialId).Select(t => new { t.SubjectId, t.SiteId, t.IsFinalVisit }).Distinct().ToListAsync();

                //    var subjects = subjectSVS.Select(t => new { t.SubjectId, t.SiteId }).Distinct().ToList();

                //    foreach (var subject in subjects)
                //    {

                //        var svItem = _mapper.Map<SubjectVisit>(visitPlan);
                //        svItem.SiteId = subject.SiteId;
                //        svItem.SubjectId = subject.SubjectId;
                //        svItem.Id = NewId.NextGuid();

                //        //设置了末次访视，那么加访视计划的时候，设置为不可用
                //        if (subjectSVS.Any(t => t.SubjectId == svItem.SubjectId && t.IsFinalVisit))
                //        {
                //            svItem.VisitExecuted = VisitExecutedEnum.Unavailable;
                //        }

                //        await _subjectVisitRepository.AddAsync(svItem);
                //    }

                //    await _subjectVisitRepository.SaveChangesAsync();
                //}
                #endregion


            }
        }
    }
}