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)
        {
            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,
                GlobalUpdateType = await _readingQuestionCriterionTrialRepository.Where(x => x.Id == taskInfo.TrialReadingCriterionId).Select(x => x.GlobalUpdateType).FirstOrDefaultAsync(),

            };

            // 一致性分析按照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,
                    VisitId = x.SourceSubjectVisitId.Value,
                    BeforeQuestionList = x.ReadingTaskQuestionAnswerList.Where(y => y.ReadingQuestionTrial.IsJudgeQuestion).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,


                      AnswerCombination = y.ReadingQuestionTrial.AnswerCombination,
                      JudgeType = y.ReadingQuestionTrial.JudgeType,
                      Type = y.ReadingQuestionTrial.Type,
                      TypeValue = y.ReadingQuestionTrial.TypeValue,
                      Answer = y.Answer
                  }).ToList()
                }).ToListAsync();


            var globalReadingQuestion = await _readingGlobalTaskInfoRepository.Where(x => x.GlobalTaskId == inDto.VisitTaskId).ToListAsync();

            result.TaskList.ForEach(x =>
            {
                x.AfterQuestionList = x.BeforeQuestionList.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 == null ? false : lr.global.Any(),
                      QuestionId = lr.question.QuestionId,
                      QuestionName = lr.question.QuestionName,
                      QuestionType = lr.question.QuestionType,
                      QuestionGenre = lr.question.QuestionGenre,
                      DictionaryCode = lr.question.DictionaryCode,
                      Type = lr.question.Type,
                      GlobalAnswerType = GlobalAnswerType.Question,
                      AnswerGroup = lr.question.AnswerGroup,
                      AnswerCombination = lr.question.AnswerCombination,
                      JudgeType = lr.question.JudgeType,
                      TypeValue = lr.question.TypeValue,

                  }).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() ?? "1",
                        QuestionName = "是否同意访视整体评估",
                        Type = "input",
                        GlobalAnswerType=GlobalAnswerType.AgreeOrNot,

                    }

                };

                List<GetGlobalQuestionType> questionTypes = new List<GetGlobalQuestionType>()
                {
                    new GetGlobalQuestionType (){GlobalAnswerType=GlobalAnswerType.UpdateType,QuestionName="评估更新类型" },
                    new GetGlobalQuestionType (){GlobalAnswerType=GlobalAnswerType.Reason,QuestionName="全局阅片备注" },
                    //new GetGlobalQuestionType (){GlobalAnswerType=GlobalAnswerType.AgreeOrNot,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,

                    });
                }



            });



            List<GetAssessTypeOutDto> assessTypeList = await _readingCriterionDictionaryRepository.Where(x => x.CriterionId == taskInfo.TrialReadingCriterionId
          && x.ParentCode == "GlobalAssessType"
          )
          .Select(x => new GetAssessTypeOutDto()
          {
              Id = x.Id,
              DictionaryId = x.DictionaryId,
              ChildGroup = x.Dictionary.ChildGroup,
              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
    }
}