using EntityFrameworkCore.Triggered;
using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.Service.Reading.Interface;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Domain.Models;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using MassTransit;
using Microsoft.Extensions.Localization;

namespace IRaCIS.Core.Application.Triggers
{
    /// <summary>
    ///  访视保存后： 末次访视设置和取消触发 Subject状态，以后后续访视状态的修改，以及自动生成阅片期和任务
    ///  访视保存前：一致性核查通过，生成任务
    /// </summary>
    public class SubjectVisitTrigger(
         IRepository<SubjectVisit> _subjectVisitRepository,
         IRepository<ReadModule> _readModuleRepository,
         IRepository<Subject> _subjectRepository,
         IRepository<VisitTask> _visitTaskRepository,
         IStringLocalizer _localizer,
         IRepository<Trial> _trialRepository,
         IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository,
         IClinicalAnswerService _iClinicalAnswerService,
         IRepository<ReadingQuestionCriterionTrial> _trialReadingCriterionRepository,
         ISubjectCriteriaEvaluationService _subjectCriteriaEvaluationService,
         IRepository<SubjectCriteriaEvaluation> _subjectCriteriaEvaluationRepository,
         IVisitTaskHelpeService _visitTaskHelpeService
         ) : IAfterSaveTrigger<SubjectVisit>, IBeforeSaveTrigger<SubjectVisit>
    {


        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);

                        await DealGenerateReadModuleAndSubjectVisit(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)
            {

                if (subjectVisit.IsFinalVisit)
                {
                    await VerifyDealFinalVisitAsync(subjectVisit);

                    await DealGenerateReadModuleAndSubjectVisit(subjectVisit);
                }

                //访视添加后 自动处理临床数据 移动
                await _iClinicalAnswerService.AutoAddCRCClinical(new Service.Reading.Dto.AutoAddClinicalInDto()
                {
                    TrialId = subjectVisit.TrialId,
                    SubjectId = subjectVisit.SubjectId,

                });
            }
        }

        public async Task BeforeSave(ITriggerContext<SubjectVisit> context, CancellationToken cancellationToken)
        {
            var subjectVisit = context.Entity;

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

                // 一致性核查通过  生成读片任务
                if (context.UnmodifiedEntity?.CheckState != subjectVisit.CheckState && subjectVisit.CheckState == CheckStateEnum.CVPassed)
                {
                    //退回或者重阅的任务一致性核查通过了  此时设置Subject 重阅影响状态
                    if (context.Entity.IsPMBackOrReReading == true)
                    {
                        await _subjectRepository.UpdatePartialFromQueryAsync(context.Entity.SubjectId, u => new Subject() { IsReReadingOrBackInfluenceAnalysis = false });
                    }

                    context.Entity.IsPMBackOrReReading = false;

                    //找到手动生成任务的标准
                    var criterionList = await _trialReadingCriterionRepository.Where(t => t.IsAutoCreate == false && t.IsSigned == true).Select(t => new { t.Id, t.TrialId, t.IsReadingTaskViewInOrder }).ToListAsync();

                    foreach (var criterion in criterionList)
                    {
                        //if(!await _SubjectCriteriaEvaluationVisitFilterRepository.AnyAsync(t=>t.SubjectId==subjectVisit.SubjectId&& t.SubjectVisitId==subjectVisit.Id && t.TrialReadingCriterionId == criterion.Id))
                        //{
                        //    await _SubjectCriteriaEvaluationVisitFilterRepository.AddAsync(new SubjectCriteriaEvaluationVisitFilter() { SubjectId = subjectVisit.SubjectId, SubjectVisitId = subjectVisit.Id, TrialReadingCriterionId = criterion.Id });
                        //}

                        //如果参与评估，那么久对当前访视进行自动筛选
                        if (await _subjectCriteriaEvaluationRepository.AnyAsync(t => t.SubjectId == subjectVisit.SubjectId && t.TrialReadingCriterionId == criterion.Id && t.IsJoinEvaluation))
                        {
                            await _subjectCriteriaEvaluationService.AutoSubjectCriteriaEvaluationVisitFilter(subjectVisit.SubjectId, subjectVisit.Id, criterion.Id);

                        }
                    }

                    await _visitTaskHelpeService.GenerateVisitTaskAsync(subjectVisit.TrialId, new List<Guid>() { subjectVisit.Id }, true);

                }

            }
        }

        /// <summary>
        /// 处理生成阅片期 以及后续访视状态
        /// </summary>
        /// <param name="subjectVisit"></param>
        /// <returns></returns>
        private async Task DealGenerateReadModuleAndSubjectVisit(SubjectVisit subjectVisit)
        {

            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 });


            #region 末次访视生成阅片器和任务  


            var trialId = subjectVisit.TrialId;
            var subjectVisitId = subjectVisit.Id;
            // 是否全局阅片


            var trial = await _trialRepository.Where(x => x.Id == trialId).FirstNotNullAsync();


            if (!subjectVisit.IsBaseLine && subjectVisit.SubmitState == SubmitStateEnum.Submitted)
            {
                var criterionList = await _readingQuestionCriterionTrialRepository.Where(x => x.TrialId == trialId && x.ReadingInfoSignTime != null && x.IsConfirm && x.IsReadingPeriod && x.IsReadingTaskViewInOrder == ReadingOrder.InOrder).ToListAsync();
                foreach (var item in criterionList)
                {

                    var readModule = await _readModuleRepository.Where(x => x.ReadingSetType == ReadingSetType.ImageReading && x.TrialReadingCriterionId == item.Id && x.SubjectVisitId == subjectVisitId).FirstOrDefaultAsync();

                    if (readModule == null)
                    {

                        ReadModule newReadModule = new ReadModule()
                        {
                            //ReadingPeriodSetId = readingPeriodSet.Id,
                            Id = NewId.NextGuid(),
                            IsUrgent = subjectVisit.IsUrgent,
                            ReadModuleAddTypeEnum=ReadModuleAddType.FinalVisit,
                            SubjectVisitId = subjectVisitId,
                            ReadingStatus = ReadingStatusEnum.TaskAllocate,
                            SubjectId = subjectVisit.SubjectId,
                            ModuleName = $"G-{subjectVisit.VisitName}",// 全局阅片
                            ReadingSetType = ReadingSetType.ImageReading,
                            ModuleType = ModuleTypeEnum.Global,
                            TrialId = subjectVisit.TrialId,
                            //VisitNum = subjectVisit.VisitNum,
                            TrialReadingCriterionId = item.Id,
                        };

                        readModule = await _readModuleRepository.AddAsync(newReadModule);

                     
                    }

                    var readTumorModule = await _readModuleRepository.Where(x => x.ReadingSetType == ReadingSetType.TumorReading && x.TrialReadingCriterionId == item.Id && x.SubjectVisitId == subjectVisitId).FirstOrDefaultAsync();

                    if ((await _readingQuestionCriterionTrialRepository.AnyAsync(x => x.Id == item.Id && x.IsOncologyReading))&& readTumorModule==null)
                    {
                        await _readModuleRepository.AddAsync(new ReadModule()
                        {
                            TrialReadingCriterionId = item.Id,
                            ReadingSetType = ReadingSetType.TumorReading,
                            SubjectVisitId = subjectVisit.Id,
                            ModuleName = $"O-{subjectVisit.VisitName}",
                            ModuleType = ModuleTypeEnum.Oncology,
                            ReadModuleAddTypeEnum = subjectVisit.PDState == PDStateEnum.PDProgress ? ReadModuleAddType.PDConfirmation : ReadModuleAddType.FinalVisit,
                            IsUrgent = subjectVisit.IsUrgent,
                            TrialId = subjectVisit.TrialId,
                            SubjectId = subjectVisit.SubjectId
                        });
                    }

                    var visitTaskList = await _visitTaskRepository.Where(x => x.TrialReadingCriterionId == item.Id && x.SourceSubjectVisitId == subjectVisitId && x.TaskState == TaskState.Effect && x.ReadingTaskState == ReadingTaskState.HaveSigned).ToListAsync();

                    foreach (var visitTask in visitTaskList)
                    {
                        await _visitTaskHelpeService.AddTaskAsync(new GenerateTaskCommand()
                        {
                            OriginalVisitId = visitTask.Id,
                            ReadingCategory = GenerateTaskCategory.Global,
                            TrialId = subjectVisit.TrialId,

                            ReadingGenerataTaskList = new List<ReadingGenerataTaskDTO>() {

                                    new ReadingGenerataTaskDTO (){
                                    IsUrgent=subjectVisit.IsUrgent,
                                    ReadingCategory=ReadingCategory.Global,
                                    ReadingName=readModule.ModuleName,
                                    ReadModuleId=readModule.Id,
                                    SubjectId=subjectVisit.SubjectId,
                                    VisitNum=visitTask.VisitTaskNum,
                                    },

                                },
                        });

                    }

                }
                await _readModuleRepository.SaveChangesAsync();
            }


            #endregion
        }

        /// <summary>
        /// 验证末次访视
        /// </summary>
        /// <param name="subjectVisit"></param>
        /// <returns></returns>
        /// <exception cref="BusinessValidationFailedException"></exception>
        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(_localizer["SubjectVisit_CannotSetAsLastVisit"]);
            }

        }
    }


}
