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

namespace IRaCIS.Core.Application.Triggers
{
    /// <summary>
    /// 添加访视计划  要给改项目下的所有Subject 添加该访视
    /// </summary>
    public class AddVisitPlanTrigger : IAfterSaveTrigger<VisitStage>
    {
        private readonly IRepository<SubjectVisit> _subjectVisitRepository;
        private readonly IMapper _mapper;

        public AddVisitPlanTrigger(IRepository<SubjectVisit> subjectVisitRepository,IMapper mapper)
        {
            _subjectVisitRepository = subjectVisitRepository;
            _mapper = mapper;
        }

        public async Task AfterSave(ITriggerContext<VisitStage> context, CancellationToken cancellationToken)
        {
            var visitPlan = context.Entity;

            if (context.ChangeType == ChangeType.Added)
            {
                //已添加受试者  都不存在该新增的计划名称 那么该项目所有受试者都增加一个访视记录
                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();
                }

            }
        }
    }
}