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

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



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


            if (context.ChangeType == ChangeType.Added)
            {
                Expression<Func<VisitTask, bool>> visitTaskLambda = x => x.TrialId == visitTask.TrialId && x.SubjectId == visitTask.SubjectId && x.TrialReadingCriterionId == visitTask.TrialReadingCriterionId;

                if (visitTask.ArmEnum == Arm.TumorArm)
                {

                    visitTaskLambda = visitTaskLambda.And(x => x.ArmEnum == Arm.TumorArm);
                }
                else
                {
                    //访视类型、全局的任务 不影响肿瘤学任务的临床数据状态
                    visitTaskLambda = visitTaskLambda.And(x => x.ArmEnum != Arm.TumorArm);
                }

                //判断是否需要临床数据签名  不需要 就不用维护
                if (visitTask.IsNeedClinicalDataSign)
                {

                    //有序阅片  IsFrontTaskNeedSignButNotSign  维护才有意义
                    if (_trialReadingCriterionRepository.Any(t => t.Id == visitTask.TrialReadingCriterionId && t.IsReadingTaskViewInOrder == ReadingOrder.InOrder))
                    {
                        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
                        });
                    }



                }


            }

            #region 附加评估 暂时废弃
            //            //从未签名状态 改为签名状态时   判断是否进行了附加评估，将附加评估的结果冗余
            //            if (context.ChangeType == ChangeType.Modified && visitTask.ReadingTaskState == ReadingTaskState.HaveSigned && context.UnmodifiedEntity.ReadingTaskState != ReadingTaskState.HaveSigned)
            //            {

            //                var criterion = _trialReadingCriterionRepository.Where(t => t.Id == visitTask.TrialReadingCriterionId).FirstOrDefault();

            //                //如果是附加评估
            //                if (criterion.IsAdditionalAssessment)
            //                {


            //                    if (visitTask.ReadingCategory == ReadingCategory.Visit)
            //                    {


            //                        switch (criterion.CriterionType)
            //                        {
            //                            case CriterionType.RECIST1Point1:
            //                                var isbaseLine = _visitTaskRepository.Where(t => t.Id == visitTask.Id).Select(t => t.SourceSubjectVisit.IsBaseLine).FirstOrDefault();



            //                                if (isbaseLine)
            //                                {
            //                                    var currentTaskAdditionarlAnswer = await _readingTaskQuestionAnswerRepository.Where(t => t.VisitTaskId == visitTask.Id &&
            //                                    t.ReadingQuestionTrial.IsAdditional == true && t.ReadingQuestionTrial.Type != "group"
            //                                    ).Include(t => t.ReadingQuestionTrial).FirstOrDefaultAsync();


            //                                    //双重阅片完成了
            //                                    if (criterion.ReadingType == ReadingMethod.Double &&
            //(_visitTaskRepository.Where(t => t.SubjectId == visitTask.SubjectId && t.TaskName == visitTask.TaskName && t.TaskState == TaskState.Effect && t.ReadingTaskState == ReadingTaskState.HaveSigned).Count() == 2)
            //                                       )
            //                                    {

            //                                        var otherTaskId = await _visitTaskRepository.Where(t => t.SubjectId == visitTask.SubjectId && t.TaskName == visitTask.TaskName && t.TaskState == TaskState.Effect && t.ReadingTaskState == ReadingTaskState.HaveSigned && t.Id != visitTask.Id)
            //                                            .Select(t => t.Id).FirstOrDefaultAsync();


            //                                        var otherTaskAdditionarlAnswer = await _readingTaskQuestionAnswerRepository.Where(t => t.VisitTaskId == otherTaskId &&
            //                                  t.ReadingQuestionTrial.IsAdditional == true && t.ReadingQuestionTrial.Type != "group"
            //                                  ).Include(t => t.ReadingQuestionTrial).FirstOrDefaultAsync();



            //                                        await _subjectAdditionalEvaluationResultRepository.AddAsync(new SubjectAdditionalEvaluationResult()
            //                                        {
            //                                            TrialReadingCriterionId = visitTask.TrialReadingCriterionId,
            //                                            IsFinalResult = true,
            //                                            SubjectId = visitTask.SubjectId,
            //                                            TrialReadingQuestionId = currentTaskAdditionarlAnswer.ReadingQuestionTrialId,
            //                                            FinalAnswer = currentTaskAdditionarlAnswer.Answer,
            //                                            FinalTranslateDictionaryCode = currentTaskAdditionarlAnswer.ReadingQuestionTrial.DictionaryCode,

            //                                        });

            //                                    }
            //                                    if (criterion.ReadingType == ReadingMethod.Single)
            //                                    {

            //                                        await _subjectAdditionalEvaluationResultRepository.AddAsync(new SubjectAdditionalEvaluationResult()
            //                                        {
            //                                            TrialReadingCriterionId = visitTask.TrialReadingCriterionId,
            //                                            IsFinalResult = true,
            //                                            SubjectId = visitTask.SubjectId,
            //                                            TrialReadingQuestionId = currentTaskAdditionarlAnswer.ReadingQuestionTrialId,
            //                                            FinalAnswer = currentTaskAdditionarlAnswer.Answer,
            //                                            FinalTranslateDictionaryCode = currentTaskAdditionarlAnswer.ReadingQuestionTrial.DictionaryCode,

            //                                        });

            //                                    }



            //                                }

            //                                break;
            //                            default:
            //                                break;
            //                        }





            //                    }








            //                }
            //            }


            #endregion

        }


    }
}