using AutoMapper;
using EasyCaching.Core;
using EntityFrameworkCore.Triggered;
using IRaCIS.Core.Application.Service;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using System.Linq.Expressions;

namespace IRaCIS.Core.Application.Triggers
{
    /// <summary>
    ///  维护 IsFrontTaskNeedSignButNotSign 字段   另外附加评估结果
    /// </summary>
    public class VisitTaskIsFrontTaskNeedSignButNotSignTrigger : IAfterSaveTrigger<VisitTask>
    {

        private readonly IRepository<VisitTask> _visitTaskRepository;
        private readonly IRepository<ReadingQuestionCriterionTrial> _trialReadingCriterionRepository;

        private readonly IRepository<ReadingQuestionTrial> _trialReadingQuestionRepository;

        private readonly IRepository<ReadingTaskQuestionAnswer> _readingTaskQuestionAnswerRepository;

        private readonly IRepository<SubjectAdditionalEvaluationResult> _subjectAdditionalEvaluationResultRepository;



        public VisitTaskIsFrontTaskNeedSignButNotSignTrigger(

            IRepository<VisitTask> visitTaskRepository, IRepository<ReadingQuestionCriterionTrial> trialReadingCriterionRepository, IRepository<ReadingQuestionTrial> trialReadingQuestionRepository
            , IRepository<ReadingTaskQuestionAnswer> readingTaskQuestionAnswerRepository, IRepository<SubjectAdditionalEvaluationResult> subjectAdditionalEvaluationResultRepository)
        {
            _trialReadingCriterionRepository = trialReadingCriterionRepository;

            _visitTaskRepository = visitTaskRepository;
            _trialReadingQuestionRepository = trialReadingQuestionRepository;

            _readingTaskQuestionAnswerRepository = readingTaskQuestionAnswerRepository;
            _subjectAdditionalEvaluationResultRepository = subjectAdditionalEvaluationResultRepository;
        }


        //添加任务的时候  如果需要签名 并且已经签名了  那么要维护该标准 该Subject   IsFrontTaskNeedSignButNotSign字段
        public async Task AfterSave(ITriggerContext<VisitTask> context, CancellationToken cancellationToken)
        {
            var visitTask = context.Entity;


            Expression<Func<VisitTask, bool>> visitTaskLambda = x => x.TrialId == visitTask.TrialId && x.SubjectId == visitTask.SubjectId && x.TrialReadingCriterionId == visitTask.TrialReadingCriterionId;
            if (context.ChangeType == ChangeType.Added)
            {
               
                //判断是否需要临床数据签名  不需要 就不用维护
                if (visitTask.IsNeedClinicalDataSign)
                {

                    //有序阅片  IsFrontTaskNeedSignButNotSign  维护才有意义
                    if (_trialReadingCriterionRepository.Any(t => t.Id == visitTask.TrialReadingCriterionId && t.IsReadingTaskViewInOrder == true))
                    {
                        var visitTaskIdQueryable = _visitTaskRepository.Where(visitTaskLambda) //该Subject  该标准的任务
                                                                                               //小于自己任务号的任务  存在需要签名  但是没签名
                        .Where(t => t.IsFrontTaskNeedSignButNotSign == false &&

                       (t.Subject.SubjectVisitTaskList.AsQueryable().Where(visitTaskLambda).Any(c => c.IsNeedClinicalDataSign == true && c.IsClinicalDataSign == false && c.VisitTaskNum < t.VisitTaskNum)

                       // 前序存在 未一致性核查未通过的
                       || t.Subject.SubjectVisitList.Any(sv => sv.CheckState != CheckStateEnum.CVPassed && t.VisitTaskNum > sv.VisitNum)

                         ))
                        .Select(t => t.Id);

                        await _visitTaskRepository.BatchUpdateNoTrackingAsync(t => visitTaskIdQueryable.Contains(t.Id), u => new VisitTask()
                        {
                            IsFrontTaskNeedSignButNotSign = true
                        });



                        var visitTaskIdQueryable2 = _visitTaskRepository.Where(visitTaskLambda) //该Subject  该标准的任务

                                  .Where(t => t.IsFrontTaskNeedSignButNotSign == true &&

                                  //前序任务  不存在需要签名  但是没签名
                                  !t.Subject.SubjectVisitTaskList.AsQueryable().Where(visitTaskLambda).Any(c => c.IsNeedClinicalDataSign == true && c.IsClinicalDataSign == false && c.VisitTaskNum < t.VisitTaskNum)

                                  // 前序  不存在 未一致性核查未通过的
                                  && !t.Subject.SubjectVisitList.Any(sv => sv.CheckState != CheckStateEnum.CVPassed && t.VisitTaskNum > sv.VisitNum)
                                  )
                                  .Select(t => t.Id);

                        await _visitTaskRepository.BatchUpdateNoTrackingAsync(t => visitTaskIdQueryable2.Contains(t.Id), u => new VisitTask()
                        {
                            IsFrontTaskNeedSignButNotSign = false
                        });
                    }

                   

                }

            }


        }


    }
}