using IRaCIS.Core.Application.Service.Reading.Dto; using IRaCIS.Core.Application.ViewModel; using IRaCIS.Core.Domain.Share; using IRaCIS.Core.Infra.EFCore.Common; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace IRaCIS.Core.Application.Service.ReadingCalculate { [ApiExplorerSettings(GroupName = "Reading")] public class OCTCalculateService( IRepository _readingTableQuestionAnswerRepository, IRepository _visitTaskRepository, IRepository _readingQuestionCriterionTrialRepository, IRepository _readingTableQuestionTrialRepository, IRepository _readingTableAnswerRowInfoRepository, IRepository _readingQuestionTrialRepository, IRepository _organInfoRepository, IRepository _readingGlobalTaskInfoRepository, IRepository _subjectVisitRepository, IRepository _tumorAssessmentRepository, IGeneralCalculateService _generalCalculateService, IRepository _readingTaskQuestionAnswerRepository, ILogger _logger) : BaseService, ICriterionCalculateService { /// /// 获取阅片的计算数据 /// /// /// public async Task GetReadingCalculationData(GetReadingCalculationDataInDto inDto) { return new { }; } #region 临时对象 单个请求的生命周期 避免重复查询数据库 private List visitTaskAnswerList; /// /// 获取Sod的值 /// private decimal? sODData; /// /// 获取iSod的值 /// private decimal? iSODData; private string nAString = "NA"; /// /// 上一次访视Id /// public Guid? lastVisitTaskId; /// /// 首次转变的任务ID /// public Guid? firstChangeTaskId; /// /// 触发任务list /// public List? compareTaskList = null; #endregion #region 删除病灶获取起始病灶序号 /// /// 删除病灶获取起始病灶序号(RECIST1Point1 固定是1) /// /// public async Task GetDeleteLesionStatrIndex(DeleteReadingRowAnswerInDto inDto) { return 1; } #endregion #region 获取阅片报告 /// /// 获取阅片报告 /// /// /// [HttpPost] public async Task GetReadingReportEvaluation(GetReadingReportEvaluationInDto indto) { GetReadingReportEvaluationOutDto result = new GetReadingReportEvaluationOutDto(); var isConvertTask = await _visitTaskRepository.Where(x => x.Id == indto.VisitTaskId).Select(x => x.IsConvertedTask).FirstNotNullAsync(); var visitTaskInfo = await _visitTaskRepository.Where(x => x.Id == indto.VisitTaskId).FirstNotNullAsync(); result.CalculateResult = await this.GetReportVerify(new GetReportVerifyInDto() { VisitTaskId = indto.VisitTaskId, IsConvertTask = isConvertTask, BeforeConvertedTaskId = visitTaskInfo.BeforeConvertedTaskId, }); result.ReadingTaskState = visitTaskInfo.ReadingTaskState; var taskInfoList = await _generalCalculateService.GetReadingReportTaskList(indto.VisitTaskId); result.VisitTaskList = taskInfoList; var visitTaskIds = taskInfoList.Select(x => x.VisitTaskId).ToList(); var criterionId = visitTaskInfo.TrialReadingCriterionId; var questionList = await _readingQuestionTrialRepository.Where(x => x.ReadingQuestionCriterionTrialId == criterionId && x.ShowQuestion != ShowQuestion.Hide) .WhereIf(isConvertTask, x => x.ConvertShowType == ConvertShowType.All || x.ConvertShowType == ConvertShowType.AfterShow) .WhereIf(!isConvertTask, x => x.ConvertShowType == ConvertShowType.All || x.ConvertShowType == ConvertShowType.BeforeShow) .ToListAsync(); var tableQuestionList = await _readingTableQuestionTrialRepository.Where(x => x.TrialCriterionId == criterionId).OrderBy(x => x.ShowOrder).ToListAsync(); var tableAnsweRowInfos = await _readingTableAnswerRowInfoRepository.Where(x => x.VisitTaskId == indto.VisitTaskId).ProjectTo(_mapper.ConfigurationProvider).ToListAsync(); result.LesionCountList = tableAnsweRowInfos.GroupBy(x => x.LesionType).Select(x => new LesionDto { LesionType = x.Key!.Value, Count = x.ToList().Count() }).ToList(); var lesionsIndexs = await _readingTableAnswerRowInfoRepository.Where(x => visitTaskIds.Contains(x.VisitTaskId)).GroupBy(x => new { x.QuestionId }).Select(x => new lesionsIndexDto() { QuestionId = x.Key.QuestionId, Rowindexs = x.Select(x => x.RowIndex).Distinct().OrderBy(x => x).ToList() }).ToListAsync(); var answers = await _readingTaskQuestionAnswerRepository.Where(x => visitTaskIds.Contains(x.VisitTaskId)).ToListAsync(); var tableAnswers = await _readingTableQuestionAnswerRepository.Where(x => visitTaskIds.Contains(x.VisitTaskId)).ToListAsync(); var globalanswerList = await _readingGlobalTaskInfoRepository.Where(x => visitTaskIds.Contains(x.TaskId) && x.GlobalVisitTask.TaskState == TaskState.Effect && x.Answer != string.Empty).Select(x => new { x.TaskId, x.GlobalVisitTask.VisitTaskNum, x.QuestionId, x.Answer }).ToListAsync(); var alltableAnsweRowInfos = await _readingTableAnswerRowInfoRepository.Where(x => visitTaskIds.Contains(x.VisitTaskId)).ToListAsync(); var organIds = alltableAnsweRowInfos.Where(x => x.OrganInfoId != null).Select(x => x.OrganInfoId).Distinct().ToList(); var organInfos = await _organInfoRepository.Where(x => organIds.Contains(x.Id)).ToListAsync(); var needChangeType = new List() { QuestionMark.Organ, QuestionMark.Location, QuestionMark.Part, }; // 第一级 #region 构造问题 List questions = questionList.Where(x => x.Type == ReadingQestionType.Group).OrderBy(x => x.ShowOrder).Select(x => new ReadingReportDto() { QuestionId = x.Id, GroupName = x.GroupName, GroupEnName = x.GroupEnName, IsShowInDicom = x.IsShowInDicom, Type = x.Type, GroupId = x.GroupId, QuestionType = x.QuestionType, LesionType = x.LesionType, QuestionGenre = x.QuestionGenre, DataSource = x.DataSource, DictionaryCode = x.DictionaryCode, TypeValue = x.TypeValue, QuestionName = x.QuestionName.LanguageName(x.QuestionEnName, _userInfo.IsEn_Us), ShowOrder = x.ShowOrder, ValueType = x.ValueType, Unit = x.Unit, CustomUnit = x.CustomUnit, ReportLayType = ReportLayType.Group, HighlightAnswer = x.HighlightAnswer, HighlightAnswerList = x.HighlightAnswerList, }).ToList(); // 分组 foreach (var item in questions) { item.Childrens = questionList.Where(x => x.GroupId == item.QuestionId).OrderBy(x => x.ShowOrder).Select(x => new ReadingReportDto() { GroupName = x.GroupName, QuestionId = x.Id, IsShowInDicom = x.IsShowInDicom, GroupEnName = x.GroupEnName, QuestionName = x.QuestionName.LanguageName(x.QuestionEnName, _userInfo.IsEn_Us), LesionType = x.LesionType, QuestionGenre = x.QuestionGenre, DataSource = x.DataSource, DictionaryCode = x.DictionaryCode, Type = x.Type, QuestionType = x.QuestionType, TypeValue = x.TypeValue, ShowOrder = x.ShowOrder, OrderMark = x.OrderMark, ValueType = x.ValueType, Unit = x.Unit, CustomUnit = x.CustomUnit, ReportLayType = ReportLayType.Question, HighlightAnswer = x.HighlightAnswer, HighlightAnswerList = x.HighlightAnswerList, }).ToList(); // 问题 foreach (var question in item.Childrens) { foreach (var task in taskInfoList) { var globalAnswer = globalanswerList.Where(x => x.TaskId == task.VisitTaskId && x.QuestionId == question.QuestionId).OrderByDescending(x => x.VisitTaskNum).FirstOrDefault(); var answer = answers.Where(x => x.VisitTaskId == task.VisitTaskId && x.ReadingQuestionTrialId == question.QuestionId).FirstOrDefault(); question.Answer.Add(new TaskQuestionAnswer() { Answer = answer == null ? string.Empty : answer.Answer, IsGlobalChange = globalAnswer == null ? false : true, GlobalChangeAnswer = globalAnswer == null ? string.Empty : globalAnswer.Answer, TaskName = task.TaskName, VisitTaskId = task.VisitTaskId, }); } // 构造表格行数据 var rowlist = tableAnsweRowInfos.Where(x => x.QuestionId == question.QuestionId).OrderBy(x => x.RowIndex).ToList(); question.Childrens = new List(); var rowoindexs = lesionsIndexs.Where(x => x.QuestionId == question.QuestionId).Select(x => x.Rowindexs.OrderBy(y => y).ToList()).FirstOrDefault(); rowoindexs = rowoindexs == null ? new List() : rowoindexs; foreach (var rowoindex in rowoindexs) { var rowinfo = rowlist.Where(x => x.RowIndex == rowoindex).FirstOrDefault(); question.Childrens.Add(new ReadingReportDto() { QuestionName = question.OrderMark + rowoindex.GetLesionMark(), RowId = rowinfo?.Id, IsShowInDicom = question.IsShowInDicom, SplitOrMergeLesionName = rowinfo != null ? (rowinfo.MergeName.IsNullOrEmpty() ? rowinfo.SplitName : rowinfo.MergeName) : string.Empty, SplitOrMergeType = rowinfo != null ? (rowinfo.SplitOrMergeType) : null, LesionType = question.LesionType, IsCanEditPosition = rowinfo != null ? (rowinfo.IsCanEditPosition) : false, RowIndex = rowoindex, BlindName = rowinfo != null ? rowinfo.BlindName : string.Empty, ReportLayType = ReportLayType.Lesions, ReportMark = rowinfo != null ? rowinfo.ReportMark : string.Empty, }); } foreach (var row in question.Childrens) { // tableQuestion row.Childrens = tableQuestionList.Where(x => x.ReadingQuestionId == question.QuestionId).Select(x => new ReadingReportDto() { QuestionName = x.QuestionName.LanguageName(x.QuestionEnName, _userInfo.IsEn_Us), QuestionId = x.ReadingQuestionId, TableQuestionId = x.Id, Type = x.Type, LesionType = question.LesionType, TableQuestionType = x.TableQuestionType, RowId = row.RowId, IsShowInDicom = question.IsShowInDicom, DataSource = x.DataSource, DictionaryCode = x.DictionaryCode, QuestionMark = x.QuestionMark, TypeValue = x.TypeValue, RowIndex = row.RowIndex, ShowOrder = x.ShowOrder, ValueType = x.ValueType, Unit = x.Unit, ReportLayType = ReportLayType.TableQuestion, }).ToList(); foreach (var tableQuestion in row.Childrens) { foreach (var task in taskInfoList) { var rowinfo = alltableAnsweRowInfos.Where(x => x.VisitTaskId == task.VisitTaskId && x.QuestionId == tableQuestion.QuestionId && x.RowIndex == tableQuestion.RowIndex).FirstOrDefault(); var taskQuestionAnswer = new TaskQuestionAnswer() { Answer = tableAnswers.Where(x => x.VisitTaskId == task.VisitTaskId && x.QuestionId == tableQuestion.QuestionId && x.RowIndex == tableQuestion.RowIndex && x.TableQuestionId == tableQuestion.TableQuestionId).Select(x => x.Answer).FirstIsNullReturnEmpty(), TaskName = task.TaskName, VisitTaskId = task.VisitTaskId, }; if (rowinfo != null && rowinfo.OrganInfoId != null) { var organInfo = organInfos.Where(x => x.Id == rowinfo.OrganInfoId).FirstOrDefault(); if (organInfo != null && needChangeType.Contains(tableQuestion.QuestionMark)) { if (_userInfo.IsEn_Us) { switch (tableQuestion.QuestionMark) { case QuestionMark.Organ: taskQuestionAnswer.Answer = organInfo.TULOCEN; break; case QuestionMark.Location: if (organInfo.IsCanEditPosition) { } else { taskQuestionAnswer.Answer = organInfo.TULATEN; } break; case QuestionMark.Part: taskQuestionAnswer.Answer = organInfo.PartEN; break; } } else { switch (tableQuestion.QuestionMark) { case QuestionMark.Organ: taskQuestionAnswer.Answer = organInfo.TULOC; break; case QuestionMark.Location: if (organInfo.IsCanEditPosition) { } else { taskQuestionAnswer.Answer = organInfo.TULAT; } break; case QuestionMark.Part: taskQuestionAnswer.Answer = organInfo.Part; break; } } } } tableQuestion.Answer.Add(taskQuestionAnswer); } } } }; } #endregion result.TaskQuestions = questions; return result; } #endregion /// /// 测试计算 /// /// /// /// [HttpGet] public async Task TestCalculate(Guid visitTaskId, QuestionType? type) { //_logger.LogError("测试计算"); ReadingCalculateDto readingData = await _generalCalculateService.GetReadingCalculateDto(visitTaskId); // await _generalCalculateService.LogRecord(readingData, "其他既往新病灶", LesionType.OtherPreviousNewLesion); if (type == null) { await ReadingCalculate(readingData); } else { await ReadingCalculate(readingData, new List() { type.Value }); } } /// /// 计算任务 /// /// /// [HttpPost] public async Task CalculateTask(CalculateTaskInDto inDto) { ReadingCalculateDto readingData = await _generalCalculateService.GetReadingCalculateDto(inDto.VisitTaskId); readingData.IsChangeOtherTask = inDto.IsChangeOtherTask; await ReadingCalculate(readingData); } /// /// 获取报告验证的信息(这里每个标准可能不一样 返回用object) /// /// /// public async Task GetReportVerify(GetReportVerifyInDto inDto) { return new GetReportVerifyOutDto() { TumorEvaluate = string.Empty, IsExistDisease = string.Empty, }; } /// /// 自动计算 /// /// /// /// public async Task ReadingCalculate(ReadingCalculateDto inDto, List? calculateType = null) { #region 计算 这里顺序非常重要 后面计算的值要依赖前面计算的结果 var needAddList = new List(); List calculateList = new List() { //// 匹配动脉段最小FCT //new ReadingCalculateData (){QuestionType=QuestionType.MinFCT,GetDecimalNullFun=GetAllMinFCT}, // // 平均最小FCT // new ReadingCalculateData (){QuestionType=QuestionType.AverageMinFCT,GetDecimalNullFun=GetAvgMinFCT}, // // 脂质角度平均值 // new ReadingCalculateData (){QuestionType=QuestionType.AvgLipidAngle,GetDecimalNullFun=GetAvgMinLipidAngle}, // // 脂质角度最大值 // new ReadingCalculateData (){QuestionType=QuestionType.MaxLipidAngle,GetDecimalNullFun=GetAllMaxLipidAngle}, }; if (calculateType != null) { calculateList = calculateList.Where(x => calculateType.Contains(x.QuestionType)).ToList(); } foreach (var calculate in calculateList) { var item = inDto.QuestionInfo.FirstOrDefault(x => x.QuestionType == calculate.QuestionType); if (item != null) { //计算答案 #region 计算答案 if (calculate.GetDecimalFun != null) { item.Answer = (await calculate.GetDecimalFun(inDto)).ToString(); } else if (calculate.GetDecimalNullFun != null) { var value = await calculate.GetDecimalNullFun(inDto); item.Answer = value == null ? string.Empty : value.Value.ToString(); } else if (calculate.GetStringFun != null) { item.Answer = await calculate.GetStringFun(inDto); } #endregion // 修改修约小数位数 List valueOfTypes = new List() { ValueOfType.Decimals, ValueOfType.Percentage }; if (inDto.DigitPlaces != -1) { try { if (valueOfTypes.Contains(item.ValueType)) { item.Answer = decimal.Round(decimal.Parse(item.Answer ?? "0"), inDto.DigitPlaces).ToString("F" + inDto.DigitPlaces.ToString()); } } catch (Exception) { } } needAddList.Add(new ReadingTaskQuestionAnswer() { Answer = item.Answer, ReadingQuestionTrialId = item.QuestionId, }); } } var questionIds = needAddList.Select(x => x.ReadingQuestionTrialId).ToList(); await _readingTaskQuestionAnswerRepository.BatchDeleteNoTrackingAsync(x => questionIds.Contains(x.ReadingQuestionTrialId) && x.VisitTaskId == inDto.VisitTaskId); needAddList.ForEach(x => { x.SubjectId = inDto.SubjectId; x.ReadingQuestionCriterionTrialId = inDto.CriterionId; x.VisitTaskId = inDto.VisitTaskId; x.TrialId = inDto.TrialId; x.SubjectId = inDto.SubjectId; }); await _readingTaskQuestionAnswerRepository.AddRangeAsync(needAddList); await _readingTaskQuestionAnswerRepository.SaveChangesAsync(); #endregion } /// /// 验证访视提交 /// /// /// public async Task VerifyVisitTaskQuestions(VerifyVisitTaskQuestionsInDto inDto) { } /// /// 匹配动脉段最小FCT /// /// /// public async Task GetAllMinFCT(ReadingCalculateDto inDto) { var allMinFCT = inDto.QuestionInfo.Where(x => x.LesionType == LesionType.FCT).SelectMany(x => x.TableRowInfoList).SelectMany(x => x.TableQuestionList) .Where(x => x.QuestionMark == QuestionMark.MinFCT).Select(x => x.Answer.IsNullOrEmptyReturn0()).MinOrDefault(); if (allMinFCT == 0) { return null; } return allMinFCT; } /// /// 所有FCT最小值中的平均值 /// /// /// public async Task GetAvgMinFCT(ReadingCalculateDto inDto) { var allMinFCT = inDto.QuestionInfo.Where(x => x.LesionType == LesionType.FCT).SelectMany(x => x.TableRowInfoList).SelectMany(x => x.TableQuestionList) .Where(x => x.QuestionMark == QuestionMark.MinFCT).Select(x => x.Answer.IsNullOrEmptyReturn0()).ToList(); if (allMinFCT.Count() == 0) { return null; } return allMinFCT.Average(); ; } /// /// 脂质角度最大值 /// /// /// public async Task GetAllMaxLipidAngle(ReadingCalculateDto inDto) { var maxLipidAngle = inDto.QuestionInfo.Where(x => x.LesionType == LesionType.LipidAngle).SelectMany(x => x.TableRowInfoList).SelectMany(x => x.TableQuestionList) .Where(x => x.QuestionMark == QuestionMark.LipidAngle).Select(x => x.Answer.IsNullOrEmptyReturn0()).MaxOrDefault(); if (maxLipidAngle == 0) { return null; } return maxLipidAngle; } /// /// 脂质角度平均值 /// /// /// public async Task GetAvgMinLipidAngle(ReadingCalculateDto inDto) { var avgMinLipidAngle = inDto.QuestionInfo.Where(x => x.LesionType == LesionType.LipidAngle).SelectMany(x => x.TableRowInfoList).SelectMany(x => x.TableQuestionList) .Where(x => x.QuestionMark == QuestionMark.LipidAngle).Select(x => x.Answer.IsNullOrEmptyReturn0()).ToList(); if (avgMinLipidAngle.Count() == 0) { return null; } return avgMinLipidAngle.Average(); } #region 将上一次的访视病灶添加到这一次 /// /// 将上一次的访视病灶添加到这一次 /// /// /// public async Task AddTaskLesionAnswerFromLastTask(AddTaskLesionAnswerFromLastTaskInDto inDto) { var visitTaskId = inDto.VisitTaskId; var taskinfo = await _visitTaskRepository.Where(x => x.Id == visitTaskId).ProjectTo(_mapper.ConfigurationProvider).FirstNotNullAsync(); var baseLineVisitId = await _subjectVisitRepository.Where(x => x.SubjectId == taskinfo.SubjectId && x.IsBaseLine).Select(x => x.Id).FirstOrDefaultAsync(); return new AddTaskLesionAnswerFromLastTaskOutDto() { IsBaseLine = taskinfo.SourceSubjectVisitId == baseLineVisitId, }; } #endregion } }