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

namespace IRaCIS.Core.Application.Triggers
{
    /// <summary>
    /// 
    /// </summary>
    public class SubjectStateTrigger :BaseService, IAfterSaveTrigger<Subject>
    {
        private readonly IRepository<SubjectVisit> _subjectVisitRepository;
        private readonly IRepository _repository;
        private readonly IMapper _mapper;

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

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

            var dbSubject = context.Entity;

            if (context.ChangeType == ChangeType.Modified )
            {
                //Site变更

                if ( context.Entity.SiteId != context.UnmodifiedEntity?.SiteId)
                {
                    var subjectId = context.Entity.Id;
                    var siteId = context.Entity.SiteId;


                    await _repository.BatchUpdateAsync<SubjectVisit>(t => t.SubjectId == subjectId, u => new SubjectVisit() { SiteId = siteId });

                    await _repository.BatchUpdateAsync<DicomStudy>(t => t.SubjectId == subjectId, u => new DicomStudy() { SiteId = siteId });


                    #region 废弃
                    ////如果访视结束了   需要删除计划外未执行的访视
                    //if (mapedSubject.Status == SubjectStatus.EndOfVisit)
                    //{
                    //    await _repository.DeleteFromQueryAsync<SubjectVisit>(t => t.VisitExecuted == VisitExecutedEnum.UnExecuted && t.SubjectId == mapedSubject.Id && t.InPlan == false);
                    //}

                    ////如果是出组了  将受试者未执行的 设置为不可用
                    //if (mapedSubject.Status == SubjectStatus.OutOfEnrollment)
                    //{
                    //    await _repository.UpdateFromQueryAsync<SubjectVisit>(t => t.SubjectId == mapedSubject.Id && t.VisitExecuted == VisitExecutedEnum.UnExecuted, u => new SubjectVisit() { VisitExecuted = VisitExecutedEnum.Unavailable });
                    //}
                    #endregion
                }


                // 出组  状态发生了变更
                if (context.Entity.Status == SubjectStatus.OutOfVisit && context.Entity.Status != context.UnmodifiedEntity?.Status)
                {
                    if (context.Entity.FinalSubjectVisitId != null)
                    {
                        if (await _subjectVisitRepository.AnyAsync(t => t.SubjectId == dbSubject.Id && t.IsFinalVisit && t.Id != dbSubject.FinalSubjectVisitId))
                        {

                            throw new BusinessValidationFailedException(
                //---该受试者已经有访视被设置为末次访视，不允许将当前访视设置为末次访视。
                                _localizer["SubjectState_CannotSetCurrentAsLastVisit"]);
                        }

                        var sv = await _subjectVisitRepository.FirstOrDefaultAsync(t => t.Id == dbSubject.FinalSubjectVisitId).IfNullThrowException();

                        if (await _subjectVisitRepository.AnyAsync(t => t.SubjectId == dbSubject.Id && t.VisitNum > sv.VisitNum && t.SubmitState == SubmitStateEnum.ToSubmit))
                        {

                            throw new BusinessValidationFailedException(
                //---该受试者当前访视后有访视的影像已上传，当前访视不允许设置为末次访视。
                                _localizer["SubjectState_CannotSetAsLastVisitWithImage"]);

                        }

                        sv.IsFinalVisit = true;

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



            }


        }
    }
}
