using IRaCIS.Core.Domain.Share;
using Microsoft.AspNetCore.Mvc;
using IRaCIS.Core.Application.Service.Reading.Dto;
using MassTransit;
using IRaCIS.Core.Infra.EFCore.Common;
using Panda.DynamicWebApi.Attributes;
using AutoMapper;
using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Infrastructure;
using Newtonsoft.Json;
using IRaCIS.Core.Application.Service;
using IRaCIS.Core.Application.ViewModel;

namespace IRaCIS.Application.Services
{
  
    /// <summary>
    /// 全局阅片
    /// </summary>
    public partial class ReadingImageTaskService : BaseService, IReadingImageTaskService
    {
        /// <summary>
        /// 提交全局阅片结果
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        //[NonDynamicMethod]
        public async Task<IResponseOutput> SubmitGlobalReadingInfo(SubmitGlobalReadingInfoInDto inDto)
        {
            //var result = await this.SaveGlobalReadingInfo(inDto);
            await VerifyTaskIsSign(inDto.GlobalTaskId);
            await this.SubmitTaskChangeState(inDto.GlobalTaskId);

            return ResponseOutput.Ok(true);
        }

        #region 全局阅片相关
        /// <summary>
        /// 保存全局阅片结果
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> SaveGlobalReadingInfo(SaveGlobalReadingInfoInDto inDto)
        {
            await VerifyTaskIsSign(inDto.GlobalTaskId);
            var visitTaskId = inDto.QuestionList.Select(x => x.VisitTaskId).FirstOrDefault();

            foreach (var item in inDto.QuestionList)
            {

                await _readingGlobalTaskInfoRepository.BatchDeleteNoTrackingAsync(x => x.GlobalTaskId == inDto.GlobalTaskId && x.TaskId == visitTaskId && x.GlobalAnswerType == item.GlobalAnswerType && x.QuestionId == item.QuestionId);

                await _readingTaskQuestionAnswerRepository.BatchUpdateNoTrackingAsync(x => x.VisitTaskId == item.VisitTaskId && x.ReadingQuestionTrialId == item.QuestionId, x => new ReadingTaskQuestionAnswer()
                {
                    GlobalChangeAnswer = item.Answer
                });
            }

            await _readingGlobalTaskInfoRepository.AddRangeAsync(inDto.QuestionList.Select(x => new ReadingGlobalTaskInfo()
            {
                Answer = x.Answer,
                QuestionId = x.QuestionId,
                SubjectId = inDto.SubjectId,
                GlobalTaskId = inDto.GlobalTaskId,
                GlobalAnswerType = x.GlobalAnswerType,
                TaskId = x.VisitTaskId,
                TrialId = inDto.TrialId,
            }).ToList());

            await _visitTaskRepository.UpdatePartialFromQueryAsync(t => t.Id == inDto.GlobalTaskId, u => new VisitTask() { ReadingTaskState = ReadingTaskState.Reading });

            var result = await _readingGlobalTaskInfoRepository.SaveChangesAsync();
            return ResponseOutput.Ok(result);

        }


        /// <summary>
        /// 获取全局阅片信息
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<GetGlobalReadingInfoOutDto> GetGlobalReadingInfo(GetGlobalReadingInfoInDto inDto)
        {
            var taskInfo = await _visitTaskRepository.Where(x => x.Id == inDto.VisitTaskId).FirstNotNullAsync();
            if (taskInfo.ReadingCategory != ReadingCategory.Global)
            {
                throw new BusinessValidationFailedException("当前任务不是全局阅片任务");
            }
            GetGlobalReadingInfoOutDto result = new GetGlobalReadingInfoOutDto()
            {
                GlobalTaskId = inDto.VisitTaskId,
                ReadingTaskState = taskInfo.ReadingTaskState,

            };

            // 一致性分析按照doctorId 其他按照分组
          
            result.TaskList = await _visitTaskRepository.Where(x => x.ReadingCategory == ReadingCategory.Visit &&
            x.TrialReadingCriterionId == taskInfo.TrialReadingCriterionId &&
                 x.SubjectId == taskInfo.SubjectId && x.IsAnalysisCreate == taskInfo.IsAnalysisCreate && x.TaskState == TaskState.Effect && x.VisitTaskNum < taskInfo.VisitTaskNum)
               .Where(x => x.DoctorUserId == taskInfo.DoctorUserId)
                .OrderBy(x => x.VisitTaskNum).Select(x => new GlobalVisitInfo()
                {
                    VisitName = x.SourceSubjectVisit.VisitName,
                    BlindName = x.SourceSubjectVisit.BlindName,
                    VisitTaskId = x.Id,
                    ArmEnum = taskInfo.ArmEnum,
                    VisitNum = x.SourceSubjectVisit.VisitNum,
                    IsBaseLine=x.SourceSubjectVisit.IsBaseLine,
                    VisitId = x.SourceSubjectVisitId.Value,
                   
                    BeforeQuestionList = x.ReadingTaskQuestionAnswerList.Where(y => y.ReadingQuestionTrial.GlobalReadingShowType!=GlobalReadingShowType.NotShow).OrderBy(y => y.ReadingQuestionTrial.ShowOrder)
                  .Select(y => new GlobalQuestionInfo()
                  {
                      QuestionId = y.ReadingQuestionTrialId,
                      QuestionName = y.ReadingQuestionTrial.QuestionName,
                      AnswerGroup = y.ReadingQuestionTrial.AnswerGroup,
                      QuestionType = y.ReadingQuestionTrial.QuestionType,
                      QuestionGenre = y.ReadingQuestionTrial.QuestionGenre,
                      DictionaryCode = y.ReadingQuestionTrial.DictionaryCode,
                      GlobalReadingShowType=y.ReadingQuestionTrial.GlobalReadingShowType,
                      AnswerCombination = y.ReadingQuestionTrial.AnswerCombination,
                      JudgeType = y.ReadingQuestionTrial.JudgeType,
                      Type = y.ReadingQuestionTrial.Type,
                      TypeValue = y.ReadingQuestionTrial.TypeValue,
                      ValueType = y.ReadingQuestionTrial.ValueType,
                      IsJudgeQuestion =y.ReadingQuestionTrial.IsJudgeQuestion,
                      Answer = y.Answer
                  }).ToList()
                }).ToListAsync();



            var globalReadingQuestion = await _readingGlobalTaskInfoRepository.Where(x => x.GlobalTaskId == inDto.VisitTaskId).ToListAsync();
            var criterionType = await _readingQuestionCriterionTrialRepository.Where(x => x.Id == taskInfo.TrialReadingCriterionId).Select(x => x.CriterionType).FirstOrDefaultAsync();
            if (criterionType == CriterionType.PCWG3)
            {
                result.TaskList.ForEach(x =>
                {

                    x.BeforeQuestionList.ForEach(y =>
                    {
                        var globalAnswer = globalReadingQuestion.Where(z => z.QuestionId == y.QuestionId).Select(z => z.Answer).FirstOrDefault();
                        y.Answer = globalAnswer.IsNullOrEmpty() ? y.Answer : globalAnswer;
                    });
                });
            }
            
            result.TaskList.ForEach(x =>
            {
                x.AfterQuestionList = x.BeforeQuestionList.Where(x=>x.IsJudgeQuestion).GroupJoin(
                    globalReadingQuestion
                      , l => new { a = l.QuestionId, b = x.VisitTaskId }
                      , r => new { a = r.QuestionId, b = r.TaskId }
                      , (l, r) => new { question = l, global = r })
                  .SelectMany(lr => lr.global.DefaultIfEmpty(), (lr, r) => new GlobalQuestionInfo
                  {
                      Answer = lr.global == null || lr.global.Count() == 0 ?
                      (inDto.UsingOriginalData ? lr.question.Answer : string.Empty) :
                      (lr.global.Select(x => x.Answer).FirstOrDefault().IsNullOrEmpty() && inDto.UsingOriginalData ?
                      lr.question.Answer : lr.global.Select(x => x.Answer).FirstOrDefault()
                      ),
                      IsHaveChange = lr.global.Any(x=>x.QuestionId!=null&&!x.Answer.IsNullOrEmpty()) ? true : false,
                      QuestionId = lr.question.QuestionId,
                      QuestionName = lr.question.QuestionName,
                      QuestionType = lr.question.QuestionType,
                      QuestionGenre = lr.question.QuestionGenre,
                      DictionaryCode = lr.question.DictionaryCode,
                      GlobalReadingShowType = lr.question.GlobalReadingShowType,
                      Type = lr.question.Type,
                      GlobalAnswerType = GlobalAnswerType.Question,
                      AnswerGroup = lr.question.AnswerGroup,
                      AnswerCombination = lr.question.AnswerCombination,
                      IsJudgeQuestion=lr.question.IsJudgeQuestion,
                      JudgeType = lr.question.JudgeType,
                      TypeValue = lr.question.TypeValue,
                      ValueType= lr.question.ValueType,

                  }).ToList();

                x.AgreeOrNot = new List<GlobalQuestionInfo>()
                {
                    new GlobalQuestionInfo()
                    {
                        Answer = globalReadingQuestion.Where(y => y.TaskId == x.VisitTaskId && y.GlobalAnswerType == GlobalAnswerType.AgreeOrNot).Select(x => x.Answer).FirstOrDefault() ?? string.Empty,
                        QuestionName = "是否同意访视整体评估",
                        Type = "input",
                        GlobalAnswerType=GlobalAnswerType.AgreeOrNot,
                        GlobalReadingShowType= GlobalReadingShowType.AllShow,
                    }

                };

             

                List<GetGlobalQuestionType> questionTypes = new List<GetGlobalQuestionType>()
                {
                };
                if(criterionType!= CriterionType.PCWG3)
                {
                    questionTypes.Add(new GetGlobalQuestionType() { GlobalAnswerType = GlobalAnswerType.UpdateType, QuestionName = "评估更新类型" });

                }
                questionTypes.Add(new GetGlobalQuestionType() { GlobalAnswerType = GlobalAnswerType.Reason, QuestionName = "全局阅片备注" });
                foreach (var item in questionTypes)
                {
                    x.AfterQuestionList.Add(new GlobalQuestionInfo()
                    {
                        Answer = globalReadingQuestion.Where(y => y.TaskId == x.VisitTaskId && y.GlobalAnswerType == item.GlobalAnswerType).Select(x => x.Answer).FirstOrDefault() ?? string.Empty,
                        QuestionName = item.QuestionName,
                        Type = "input",
                        GlobalAnswerType = item.GlobalAnswerType,
                        GlobalReadingShowType= GlobalReadingShowType.AllShow,

                    });
                }



            });

            if (criterionType == CriterionType.PCWG3)
            {

                result.TaskList.ForEach(x =>
                {
                    foreach (var item in x.AfterQuestionList.Where(x => x.QuestionType == QuestionType.SiteVisitForTumorEvaluation))
                    {
                        item.Answer = item.Answer.IsNullOrEmpty() ? (x.BeforeQuestionList.Where(x => x.QuestionType == QuestionType.SiteVisitForTumorEvaluation).Select(x => x.Answer).FirstOrDefault()??string.Empty) : item.Answer;
                    }

                    x.BeforeQuestionList = x.BeforeQuestionList.Where(x => x.QuestionType != QuestionType.SiteVisitForTumorEvaluation).ToList();

                });
            }



            var subjectVisitId = await _readModuleRepository.Where(x => x.Id == taskInfo.SouceReadModuleId).Select(x => x.SubjectVisitId).FirstOrDefaultAsync();
            var isBaseLine = await _subjectVisitRepository.Where(x => x.Id == subjectVisitId).Select(x => x.IsBaseLine).FirstOrDefaultAsync();
            List<CriterionDictionaryInfo> assessTypeList = await _readingCriterionDictionaryRepository.Where(x => x.CriterionId == taskInfo.TrialReadingCriterionId
          && x.ParentCode == ReadingCommon.CriterionDictionary.GlobalAssess
          )
               //.WhereIf(isBaseLine,x=>x.IsBaseLineUse)
               //.WhereIf(!isBaseLine,x=>x.IsFollowVisitUse)
          .Select(x => new CriterionDictionaryInfo()
          {
              Id = x.Id,
              DictionaryId = x.DictionaryId,
              ChildGroup = x.Dictionary.ChildGroup,
              IsBaseLineUse=x.IsBaseLineUse,
              IsFollowVisitUse=x.IsFollowVisitUse,
              Code = x.Dictionary.Code,
              Description = x.Dictionary.Description,
              ShowOrder = x.Dictionary.ShowOrder,
              ParentCode = x.Dictionary.Parent.Code,
              Value = x.Dictionary.Value,
              ValueCN = x.Dictionary.ValueCN
          }).OrderBy(x => x.ParentCode).ThenBy(x => x.ShowOrder).ToListAsync();
            result.AssessTypeList = assessTypeList;
            return result;
        }
        #endregion
    }
}
