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 : 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(
                                "该患者已经有检查批次被设置为末次检查批次，不允许将当前检查批次设置为末次检查批次。");
                        }

                        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(
                                "该患者当前检查批次后有检查批次的影像已上传，当前检查批次不允许设置为末次检查批次。");

                        }

                        sv.IsFinalVisit = true;

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



            }


        }
    }
}