using EntityFrameworkCore.Triggered;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;

namespace IRaCIS.Core.Application.Triggers
{
    /// <summary>
    ///  处理  访视   末次评估  会影响Subject 状态
    /// </summary>
    public class SubjectVisitFinalVisitTrigger : IAfterSaveTrigger<SubjectVisit>
    {
        private readonly IRepository<SubjectVisit> _subjectVisitRepository;
        private readonly IRepository<Subject> _subjectRepository;

        public SubjectVisitFinalVisitTrigger(IRepository<SubjectVisit> subjectVisitRepository, IRepository<Subject> subjectRepository)
        {
            _subjectVisitRepository = subjectVisitRepository;
            _subjectRepository = subjectRepository;
        }

        public async Task AfterSave(ITriggerContext<SubjectVisit> context, CancellationToken cancellationToken)
        {

            var subjectVisit = context.Entity;


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

                // 修改了IsFinalVisit
                if (context.UnmodifiedEntity?.IsFinalVisit != subjectVisit.IsFinalVisit)
                {
                    if (subjectVisit.IsFinalVisit)
                    {
                        await VerifyDealFinalVisitAsync(subjectVisit);
                    }
                    else
                    {
                        //回退

                        await _subjectRepository.BatchUpdateNoTrackingAsync(t => t.Id == subjectVisit.SubjectId,
                            u => new Subject() { Status = SubjectStatus.OnVisit, FinalSubjectVisitId =null });

                        await _subjectVisitRepository.BatchUpdateNoTrackingAsync(t => t.SubjectId == subjectVisit.SubjectId && t.VisitExecuted == VisitExecutedEnum.Unavailable, u => new SubjectVisit() { VisitExecuted = VisitExecutedEnum.UnExecuted });
                    }


                }

            }
            else if(context.ChangeType == ChangeType.Added && subjectVisit.IsFinalVisit)
            {
                await VerifyDealFinalVisitAsync(subjectVisit);
            }



        }


        private async Task  VerifyDealFinalVisitAsync(SubjectVisit subjectVisit)
        {
            if (await _subjectVisitRepository.AnyAsync(t => t.SubjectId == subjectVisit.SubjectId && t.VisitNum > subjectVisit.VisitNum &&
                       (t.SubmitState == SubmitStateEnum.ToSubmit || t.SubmitState == SubmitStateEnum.Submitted)))
            {
                throw new BusinessValidationFailedException("该受试者已有后续访视已上传影像或已提交，当前访视不允许设置为末次访视。");
            }

            await _subjectRepository.BatchUpdateNoTrackingAsync(t => t.Id == subjectVisit.SubjectId,
                  u => new Subject() { Status = SubjectStatus.OutOfVisit, FinalSubjectVisitId = subjectVisit.Id });


            //末次访视后的  访视设置为不可用
            await _subjectVisitRepository.BatchUpdateNoTrackingAsync(t => t.SubjectId == subjectVisit.SubjectId && t.VisitNum > subjectVisit.VisitNum &&
            t.VisitExecuted == VisitExecutedEnum.UnExecuted, u => new SubjectVisit() { VisitExecuted = VisitExecutedEnum.Unavailable });
        }


    }
}