using DocumentFormat.OpenXml.Drawing.Diagrams;
using DocumentFormat.OpenXml.Drawing.Spreadsheet;
using DocumentFormat.OpenXml.Office.SpreadSheetML.Y2023.MsForms;
using DocumentFormat.OpenXml.Office2010.Excel;
using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.Service.Reading.Dto;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Domain.Models;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infra.EFCore.Common;
using IRaCIS.Core.Infrastructure;
using MassTransit;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace IRaCIS.Core.Application.Service.ReadingCalculate
{

    [ApiExplorerSettings(GroupName = "Reading")]
    public class OCTCalculateService(IRepository<ReadingTableQuestionAnswer> _readingTableQuestionAnswerRepository,
        IRepository<VisitTask> _visitTaskRepository,
        IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository,
        IRepository<ReadingTableQuestionTrial> _readingTableQuestionTrialRepository,
        IRepository<ReadingTableAnswerRowInfo> _readingTableAnswerRowInfoRepository,
        IRepository<ReadingQuestionTrial> _readingQuestionTrialRepository,
        IRepository<OrganInfo> _organInfoRepository,
           ISubjectVisitService iSubjectVisitService,
        IRepository<Dictionary> _dictionaryRepository,
          IHttpContextAccessor httpContext,
        IRepository<ReadingGlobalTaskInfo> _readingGlobalTaskInfoRepository,
        IRepository<SubjectVisit> _subjectVisitRepository,
        IRepository<TumorAssessment_IRECIST1Point1> _tumorAssessmentRepository,
        IGeneralCalculateService _generalCalculateService,
          IVisitTaskHelpeService _visitTaskHelpeService,
        IRepository<ReadingTaskQuestionAnswer> _readingTaskQuestionAnswerRepository,
        IRepository<TaskStudy> _taskStudyRepository,
        IRepository<NoneDicomStudyFile> _noneDicomStudyFileRepository,
        ILogger<IRECIST1Point1CalculateService> _logger, IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService, ICriterionCalculateService
    {
        /// <summary>
        /// 阅片导入
        /// </summary>
        /// <returns></returns>
        public async Task ReadingImport()
        {
            var request = httpContext.HttpContext!.Request;
            ReadingImportType readingImportType = (ReadingImportType)int.Parse(request.Form["ReadingImportType"].ToString());

            switch (readingImportType)
            {
                case ReadingImportType.ROI:
                    await UploadOCTFCTTemplate();
                    break;

                case ReadingImportType.OCT_LipidAngle:
                    await UploadOCTLipidAngleTemplate();
                    break;
            }
        }

        /// <summary>
        /// 获取阅片的计算数据
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<object> GetReadingCalculationData(GetReadingCalculationDataInDto inDto)
        {
            return new
            {
            };
        }

        #region 临时对象 单个请求的生命周期 避免重复查询数据库

        private List<VisitTaskAnswerInfo> visitTaskAnswerList;

        /// <summary>
        /// 获取Sod的值
        /// </summary>
        private decimal? sODData;

        /// <summary>
        /// 获取iSod的值
        /// </summary>
        private decimal? iSODData;

        private string nAString = "NA";

        /// <summary>
        /// 上一次访视Id
        /// </summary>
        public Guid? lastVisitTaskId;

        /// <summary>
        /// 首次转变的任务ID
        /// </summary>
        public Guid? firstChangeTaskId;

        /// <summary>
        /// 触发任务list
        /// </summary>
        public List<TirggerTaskInfo>? compareTaskList = null;
        #endregion

        #region 删除病灶获取起始病灶序号
        /// <summary>
        /// 删除病灶获取起始病灶序号（RECIST1Point1 固定是1）
        /// </summary>
        /// <returns></returns>
        public async Task<int> GetDeleteLesionStatrIndex(DeleteReadingRowAnswerInDto inDto)
        {
            return 1;
        }
        #endregion

        #region 获取阅片报告
        /// <summary>
        /// 获取阅片报告
        /// </summary>
        /// <param name="indto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<GetReadingReportEvaluationOutDto> 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<TableAnsweRowInfo>(_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 Globalanswer()
            {
                TaskId = x.TaskId,
                VisitTaskNum = x.GlobalVisitTask.VisitTaskNum,
                QuestionId = x.QuestionId,
                Answer = 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?>() {
                QuestionMark.Organ,
                QuestionMark.Location,
                QuestionMark.Part,
            };

            List<ReadingReportDto> questions = await _generalCalculateService.GetReadingReportQuestion
       (
        questionList,
        taskInfoList,
       globalanswerList,
        answers,
        tableAnsweRowInfos,
         tableQuestionList,
         alltableAnsweRowInfos,
         tableAnswers,
        organInfos,
         needChangeType
       );



            result.TaskQuestions = questions;



            return result;

        }
        #endregion

        /// <summary>
        /// 测试计算
        /// </summary>
        /// <param name="visitTaskId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [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<QuestionType>() { type.Value });
            }

        }



        /// <summary>
        /// 计算任务
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task CalculateTask(CalculateTaskInDto inDto)
        {
            ReadingCalculateDto readingData = await _generalCalculateService.GetReadingCalculateDto(inDto.VisitTaskId);
            readingData.IsChangeOtherTask = inDto.IsChangeOtherTask;
            readingData.ComputationTrigger = inDto.ComputationTrigger;
            await ReadingCalculate(readingData);
        }

        /// <summary>
        /// 获取报告验证的信息(这里每个标准可能不一样 返回用object)
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<GetReportVerifyOutDto> GetReportVerify(GetReportVerifyInDto inDto)
        {
            return new GetReportVerifyOutDto()
            {
                TumorEvaluate = string.Empty,
                IsExistDisease = string.Empty,

            };
        }

        /// <summary>
        /// 获取OCT-FCT模板
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<FileResult> GetOCTFCTTemplate(GetExportTemplateInDto inDto)
        {
            var taskinfo = await _visitTaskRepository.Where(x => x.Id == inDto.VisitTaskId).Include(x => x.Subject).FirstNotNullAsync();

            //靶段
            var targetSegmentdic = await _dictionaryRepository.Where(x => x.Parent.Code == "TargetSegment").ToListAsync();

            //斑块类型
            var plaqueTypedic = await _dictionaryRepository.Where(x => x.Parent.Code == "PlaqueType").ToListAsync();




            var awswerList = await _readingTaskQuestionAnswerRepository.Where(x => x.VisitTaskId == inDto.VisitTaskId).Include(x => x.ReadingQuestionTrial).ToListAsync();



            var targetSegmentAnswer = awswerList.Where(x => x.ReadingQuestionTrial.QuestionType == QuestionType.TargetSegment).Select(x => x.Answer).FirstOrDefault() ?? string.Empty;
            if (targetSegmentAnswer.IsNotNullOrEmpty())
            {
                var data = JsonConvert.DeserializeObject<List<string>>(targetSegmentAnswer);
                targetSegmentAnswer = string.Join(",", targetSegmentdic
                 .Where(x => data.Contains(x.Code))
                 .Select(x => x.ValueCN));
            }
            else
            {
                var targetSegmentData = await iSubjectVisitService.GetReadingVisitStudyList(new Contracts.GetReadingVisitStudyListIndto()
                {
                    SujectVisitId = taskinfo.SourceSubjectVisitId ?? default(Guid),
                    TrialId = taskinfo.TrialId,
                    VisitTaskId = inDto.VisitTaskId
                });
                targetSegmentAnswer = string.Join(",", targetSegmentData
                .Where(x => x.BodyPartForEdit.IsNotNullOrEmpty())
                .SelectMany(x => x.BodyPartForEdit.Split('|'))
                .Where(s => !string.IsNullOrWhiteSpace(s))
                .Distinct());
            }


            var plaqueTypeAnswer = awswerList.Where(x => x.ReadingQuestionTrial.QuestionType == QuestionType.PlaqueType).Select(x => x.Answer).FirstOrDefault() ?? string.Empty;
            if (plaqueTypeAnswer.IsNotNullOrEmpty())
            {
                var data = JsonConvert.DeserializeObject<List<string>>(plaqueTypeAnswer);
                plaqueTypeAnswer = string.Join(",", plaqueTypedic
                 .Where(x => data.Contains(x.Code))
                 .Select(x => x.ValueCN));
            }


            var values = new TemplateData()
            {
                SubjectID = (taskinfo.BlindSubjectCode.IsNullOrEmpty() ? taskinfo.Subject.Code : taskinfo.BlindSubjectCode),
                TaskBlindName = taskinfo.TaskBlindName,
                TargetSegment = targetSegmentAnswer,
                TargetSegmentRemarks = awswerList.Where(x => x.ReadingQuestionTrial.QuestionType == QuestionType.TargetSegmentRemarks).Select(x => x.Answer).FirstOrDefault() ?? string.Empty,
                //ROIAllLength = awswerList.Where(x => x.ReadingQuestionTrial.QuestionType == QuestionType.ROIAllLength).Select(x => x.Answer).FirstOrDefault() ?? string.Empty,
                ////PullbackFrameCount = awswerList.Where(x => x.ReadingQuestionTrial.QuestionType == QuestionType.PullbackFrameCount).Select(x => x.Answer).FirstOrDefault() ?? string.Empty,
                //PlaqueType = plaqueTypeAnswer,
                //AdjustReason = awswerList.Where(x => x.ReadingQuestionTrial.QuestionType == QuestionType.AdjustReason).Select(x => x.Answer).FirstOrDefault() ?? string.Empty,
           



            };
            return await _visitTaskHelpeService.ExportTemplateAsync(new IRaCIS.Application.Contracts.ExportTemplateAsyncDto()
            {
                ExportFileName = "OCT_FCT_Template",
                TemplateCode = StaticData.Export.OCT_FCT_Template,
                Data = values
            });
        }

        /// <summary>
        /// 导入OCT-FCT数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task UploadOCTFCTTemplate()
        {
            var request = httpContext.HttpContext!.Request;
            var file = request.Form.Files[0];
            Guid visitTaskId = Guid.Parse(request.Form["VisitTaskId"]);
            var taskinfo = await _visitTaskRepository.Where(x => x.Id == visitTaskId).Include(x => x.Subject).Include(x => x.TrialReadingCriterion).FirstNotNullAsync();
            var uploadInfo = await _generalCalculateService.GetDataTableFromUpload(file, "OCTFCT", taskinfo.TrialId);

            List<string> sheetNames = new List<string>()
            {
                "ROI测量值","ROI 测量值"
            };

            if (sheetNames.Intersect(uploadInfo.SheetNames).Count() == 0)
            {
                throw new BusinessValidationFailedException(_localizer["IVUS_UplpadDataError"]);
            }
            var dataTable = uploadInfo.DataTable;

            var values = new TemplateData()
            {
                SubjectID = taskinfo.BlindSubjectCode.IsNullOrEmpty() ? taskinfo.Subject.Code : taskinfo.BlindSubjectCode,
                TaskBlindName = taskinfo.TaskBlindName,
            };

            if (values.SubjectID != dataTable.Rows[0]["B"].ToString() || values.TaskBlindName != dataTable.Rows[1]["B"].ToString())
            {
                throw new BusinessValidationFailedException(_localizer["IVUS_UploadVisitTaskError"]);
            }
            var digitPlaces = taskinfo.TrialReadingCriterion.DigitPlaces ?? 0;
            decimal getdecimalData(string value)
            {
                return decimal.Parse(decimal.Round(decimal.Parse(value ?? "0"), digitPlaces, MidpointRounding.AwayFromZero).ToString("F" + digitPlaces.ToString()));
            }


            decimal? getdecimalEmptyData(string value)
            {
                if (value == string.Empty)
                {
                    return null;
                }
                return decimal.Parse(decimal.Round(decimal.Parse(value ?? "0"), digitPlaces, MidpointRounding.AwayFromZero).ToString("F" + digitPlaces.ToString()));
            }
            List<OCTFCTUploadData> measuredValueList = new List<OCTFCTUploadData>();
            var errorRow = new List<int> { };

            Dictionary<string, string> yesOrNo = new Dictionary<string, string>()
            {
                { "1","1"},
                { "0","0"},
                { "是","1"},
                { "否","0"},
                { "Yes","1"},
                { "No","0"},
            };


            string getNone(string value)
            {
                if (value == string.Empty || value == null)
                {
                    return "无";
                }
                else
                {
                    return value;
                }
            }
            for (int i = 8; i < dataTable.Rows.Count; i++)
            {
                try
                {


                    // 手动抛出异常进入catch
                    if (!yesOrNo.ContainsKey(dataTable.Rows[i]["K"].ToString())|| !yesOrNo.ContainsKey(dataTable.Rows[i]["L"].ToString()))
                    {
                        throw new InvalidOperationException("NullError");
                    }

                    measuredValueList.Add(new OCTFCTUploadData()
                    {
                        //PlaqueNum = int.Parse(dataTable.Rows[i]["A"].ToString()),
                        FrameNumber = dataTable.Rows[i]["A"].ToString() ?? string.Empty,
                        LumenAreaMeasurement = getdecimalEmptyData(dataTable.Rows[i]["B"].ToString()),
                        LipidAngle = getdecimalEmptyData(dataTable.Rows[i]["C"].ToString() ?? string.Empty),
                        FirstData = getdecimalEmptyData(dataTable.Rows[i]["D"].ToString()),
                        SecondData = getdecimalEmptyData(dataTable.Rows[i]["E"].ToString()),
                        ThirdData = getdecimalEmptyData(dataTable.Rows[i]["F"].ToString()),
                        MicrochannelMeasurement = getNone(dataTable.Rows[i]["G"].ToString()),
                        CholesterolCrystalMeasurement = getNone(dataTable.Rows[i]["H"].ToString()),
                        MacrophageInfiltrationMeasurement = getNone(dataTable.Rows[i]["I"].ToString()),
                        MacrophageInfiltrationAngle = getdecimalEmptyData(dataTable.Rows[i]["J"].ToString() ?? string.Empty),
                        PlaqueRupture = getNone(dataTable.Rows[i]["K"].ToString()),
                        PlaqueHealing = getNone(dataTable.Rows[i]["L"].ToString()),

                    });
                }
                catch (Exception)
                {

                    errorRow.Add(i+1);
                }

            }
      



            if (errorRow.Count() > 0)
            {
                var errorRows = string.Join(',', errorRow.Select(i => i.ToString()));
                throw new BusinessValidationFailedException(_localizer["Service_TemplateException", errorRows]);
            }

            Dictionary<string, string> isPresent = new Dictionary<string, string>()
            {
                { "1","1"},
                { "0","0"},
                { "有","1"},
                { "无","0"},
                { "Existence","1"},
                { "Non-existence","0"},
                { string.Empty,string.Empty},
            };

            int row = 8;
            foreach (var item in measuredValueList)
            {
                row++;
                try
                {
                    if (isPresent[item.MacrophageInfiltrationMeasurement] == "1"&& item.MacrophageInfiltrationAngle==null)
                    {
                        errorRow.Add(row);
                        continue;
                    }

                    if ((isPresent[item.MacrophageInfiltrationMeasurement] == "0"|| isPresent[item.MacrophageInfiltrationMeasurement]==string.Empty) && item.MacrophageInfiltrationAngle != null)
                    {
                        errorRow.Add(row);
                        continue;
                    }
                }
                catch (Exception)
                {

                    errorRow.Add(row);
                    continue;
                }
            }

            if (errorRow.Count() > 0)
            {
                var errorRows = string.Join(',', errorRow.Select(i => i.ToString()));
                throw new BusinessValidationFailedException(_localizer["Service_TemplateException", errorRows]);
            }

            var questionInfo = await _readingQuestionTrialRepository.Where(x => x.ReadingQuestionCriterionTrialId == taskinfo.TrialReadingCriterionId && x.LesionType == LesionType.ROI).FirstNotNullAsync();
            var tableQuestionList = await _readingTableQuestionTrialRepository.Where(x => x.ReadingQuestionId == questionInfo.Id).ToListAsync();
            List<ReadingTableAnswerRowInfo> tableAnsweRowInfos = new List<ReadingTableAnswerRowInfo>();
            List<ReadingTableQuestionAnswer> tableAnswers = new List<ReadingTableQuestionAnswer>();

            var maxnum = 0;

         

            foreach (var item in measuredValueList)
            {
                maxnum = maxnum + 1;
                var newRowId = NewId.NextGuid();
                // 斑块数据统计
                tableAnsweRowInfos.Add(new ReadingTableAnswerRowInfo()
                {
                    Id = newRowId,
                    QuestionId = questionInfo.Id,
                    VisitTaskId = taskinfo.Id,
                    TrialId = taskinfo.TrialId,
                    RowIndex = maxnum,
                    IsCurrentTaskAdd = true,
                    BlindName = taskinfo.TaskBlindName,
                    OrderMark = questionInfo.OrderMark,
                    FristAddTaskId = taskinfo.Id,
                    RowMark = questionInfo.OrderMark + decimal.Parse(maxnum.ToString()).GetLesionMark()
                });

                // 编号
                //tableAnswers.Add(new ReadingTableQuestionAnswer()
                //{
                //    Answer = item.PlaqueNum.ToString(),
                //    QuestionId = questionInfo.Id,
                //    TrialId = taskinfo.TrialId,
                //    VisitTaskId = taskinfo.Id,
                //    RowId = newRowId,
                //    RowIndex = maxnum,
                //    TableQuestionId = tableQuestionList.Where(x => x.ReadingQuestionId == questionInfo.Id && x.QuestionMark == QuestionMark.PlaqueNumber).Select(x => x.Id).FirstOrDefault(),
                //});

                // 帧数
                tableAnswers.Add(new ReadingTableQuestionAnswer()
                {
                    Answer = item.FrameNumber,
                    QuestionId = questionInfo.Id,
                    TrialId = taskinfo.TrialId,
                    VisitTaskId = taskinfo.Id,
                    RowId = newRowId,
                    RowIndex = maxnum,
                    TableQuestionId = tableQuestionList.Where(x => x.ReadingQuestionId == questionInfo.Id && x.QuestionMark == QuestionMark.FrameNumber).Select(x => x.Id).FirstOrDefault(),
                });



                // 第一次
                tableAnswers.Add(new ReadingTableQuestionAnswer()
                {
                    Answer = item.FirstData.DecimalNullToString(digitPlaces),
                    QuestionId = questionInfo.Id,
                    TrialId = taskinfo.TrialId,
                    VisitTaskId = taskinfo.Id,
                    RowId = newRowId,
                    RowIndex = maxnum,
                    TableQuestionId = tableQuestionList.Where(x => x.ReadingQuestionId == questionInfo.Id && x.QuestionMark == QuestionMark.FirstFCT).Select(x => x.Id).FirstOrDefault(),
                });

                tableAnswers.Add(new ReadingTableQuestionAnswer()
                {
                    Answer = item.SecondData.DecimalNullToString(digitPlaces),
                    QuestionId = questionInfo.Id,
                    TrialId = taskinfo.TrialId,
                    VisitTaskId = taskinfo.Id,
                    RowId = newRowId,
                    RowIndex = maxnum,
                    TableQuestionId = tableQuestionList.Where(x => x.ReadingQuestionId == questionInfo.Id && x.QuestionMark == QuestionMark.SecondFCT).Select(x => x.Id).FirstOrDefault(),
                });

                tableAnswers.Add(new ReadingTableQuestionAnswer()
                {
                    Answer = item.ThirdData.DecimalNullToString(digitPlaces),
                    QuestionId = questionInfo.Id,
                    TrialId = taskinfo.TrialId,
                    VisitTaskId = taskinfo.Id,
                    RowId = newRowId,
                    RowIndex = maxnum,
                    TableQuestionId = tableQuestionList.Where(x => x.ReadingQuestionId == questionInfo.Id && x.QuestionMark == QuestionMark.ThirdFCT).Select(x => x.Id).FirstOrDefault(),
                });

                tableAnswers.Add(new ReadingTableQuestionAnswer()
                {
                    Answer = item.Avg.DecimalNullToString(digitPlaces),
                    QuestionId = questionInfo.Id,
                    TrialId = taskinfo.TrialId,
                    VisitTaskId = taskinfo.Id,
                    RowId = newRowId,
                    RowIndex = maxnum,
                    TableQuestionId = tableQuestionList.Where(x => x.ReadingQuestionId == questionInfo.Id && x.QuestionMark == QuestionMark.AvgFCT).Select(x => x.Id).FirstOrDefault(),
                });

                try
                {
                    // 新加的5个问题
                    // 巨噬细胞浸润测量
                    tableAnswers.Add(new ReadingTableQuestionAnswer()
                    {
                        Answer = isPresent[item.MacrophageInfiltrationMeasurement.ToString()],
                        QuestionId = questionInfo.Id,
                        TrialId = taskinfo.TrialId,
                        VisitTaskId = taskinfo.Id,
                        RowId = newRowId,
                        RowIndex = maxnum,
                        TableQuestionId = tableQuestionList.Where(x => x.ReadingQuestionId == questionInfo.Id && x.QuestionMark == QuestionMark.MacrophageInfiltrationMeasurement).Select(x => x.Id).FirstOrDefault(),
                    });

                    // 巨噬细胞浸润角度测量
                    tableAnswers.Add(new ReadingTableQuestionAnswer()
                    {
                        Answer = item.MacrophageInfiltrationAngle.ToString(),
                        QuestionId = questionInfo.Id,
                        TrialId = taskinfo.TrialId,
                        VisitTaskId = taskinfo.Id,
                        RowId = newRowId,
                        RowIndex = maxnum,
                        TableQuestionId = tableQuestionList.Where(x => x.ReadingQuestionId == questionInfo.Id && x.QuestionMark == QuestionMark.MacrophageInfiltrationAngle).Select(x => x.Id).FirstOrDefault(),
                    });

                    // 微通道测量
                    tableAnswers.Add(new ReadingTableQuestionAnswer()
                    {
                        Answer = isPresent[item.MicrochannelMeasurement.ToString()],
                        QuestionId = questionInfo.Id,
                        TrialId = taskinfo.TrialId,
                        VisitTaskId = taskinfo.Id,
                        RowId = newRowId,
                        RowIndex = maxnum,
                        TableQuestionId = tableQuestionList.Where(x => x.ReadingQuestionId == questionInfo.Id && x.QuestionMark == QuestionMark.MicrochannelMeasurement).Select(x => x.Id).FirstOrDefault(),
                    });

                    // 胆固醇结晶测量
                    tableAnswers.Add(new ReadingTableQuestionAnswer()
                    {
                        Answer = isPresent[item.CholesterolCrystalMeasurement.ToString()],
                        QuestionId = questionInfo.Id,
                        TrialId = taskinfo.TrialId,
                        VisitTaskId = taskinfo.Id,
                        RowId = newRowId,
                        RowIndex = maxnum,
                        TableQuestionId = tableQuestionList.Where(x => x.ReadingQuestionId == questionInfo.Id && x.QuestionMark == QuestionMark.CholesterolCrystalMeasurement).Select(x => x.Id).FirstOrDefault(),
                    });

                    // 官腔面积测量
                    tableAnswers.Add(new ReadingTableQuestionAnswer()
                    {
                        Answer = item.LumenAreaMeasurement.ToString(),
                        QuestionId = questionInfo.Id,
                        TrialId = taskinfo.TrialId,
                        VisitTaskId = taskinfo.Id,
                        RowId = newRowId,
                        RowIndex = maxnum,
                        TableQuestionId = tableQuestionList.Where(x => x.ReadingQuestionId == questionInfo.Id && x.QuestionMark == QuestionMark.LumenAreaMeasurement).Select(x => x.Id).FirstOrDefault(),
                    });

                    // 脂质角度
                    tableAnswers.Add(new ReadingTableQuestionAnswer()
                    {
                        Answer = item.LipidAngle.ToString(),
                        QuestionId = questionInfo.Id,
                        TrialId = taskinfo.TrialId,
                        VisitTaskId = taskinfo.Id,
                        RowId = newRowId,
                        RowIndex = maxnum,
                        TableQuestionId = tableQuestionList.Where(x => x.ReadingQuestionId == questionInfo.Id && x.QuestionMark == QuestionMark.LipidAngle).Select(x => x.Id).FirstOrDefault(),
                    });

                    // 斑块破裂
                    tableAnswers.Add(new ReadingTableQuestionAnswer()
                    {
                        Answer = yesOrNo[item.PlaqueRupture.ToString()],
                        QuestionId = questionInfo.Id,
                        TrialId = taskinfo.TrialId,
                        VisitTaskId = taskinfo.Id,
                        RowId = newRowId,
                        RowIndex = maxnum,
                        TableQuestionId = tableQuestionList.Where(x => x.ReadingQuestionId == questionInfo.Id && x.QuestionMark == QuestionMark.PlaqueRupture).Select(x => x.Id).FirstOrDefault(),
                    });

                    // 斑块愈合
                    tableAnswers.Add(new ReadingTableQuestionAnswer()
                    {
                        Answer = yesOrNo[item.PlaqueHealing.ToString()],
                        QuestionId = questionInfo.Id,
                        TrialId = taskinfo.TrialId,
                        VisitTaskId = taskinfo.Id,
                        RowId = newRowId,
                        RowIndex = maxnum,
                        TableQuestionId = tableQuestionList.Where(x => x.ReadingQuestionId == questionInfo.Id && x.QuestionMark == QuestionMark.PlaqueHealing).Select(x => x.Id).FirstOrDefault(),
                    });

                }
                catch (Exception)
                {
                    throw new BusinessValidationFailedException(_localizer["IVUS_UplpadDataError"]);
                }


                // 添加其他问题答案
                foreach (var otherQuestion in tableQuestionList.Where(x => !tableAnswers.Any(y => y.TableQuestionId == x.Id && y.RowId == newRowId)))
                {
                    tableAnswers.Add(new ReadingTableQuestionAnswer()
                    {
                        Answer = string.Empty,
                        QuestionId = questionInfo.Id,
                        TrialId = taskinfo.TrialId,
                        VisitTaskId = taskinfo.Id,
                        RowId = newRowId,
                        RowIndex = maxnum,
                        TableQuestionId = otherQuestion.Id,
                    });
                }

            }

            #region 构造外层问题答案
            List<ReadingTaskQuestionAnswer> questionAnswers = new List<ReadingTaskQuestionAnswer>();

            var readingQuestionList = await _readingQuestionTrialRepository.Where(x => x.ReadingQuestionCriterionTrialId == taskinfo.TrialReadingCriterionId).ToListAsync();
            var targetSegmentAnswer = dataTable.Rows[2]["B"].ToString();

            if (targetSegmentAnswer.IsNotNullOrEmpty())
            {
                var targetSegmentValues = targetSegmentAnswer.Replace(" ", "").Replace("，", ",").Split(",").ToList();
                var targetSegmentdic = await _dictionaryRepository.Where(x => x.Parent.Code == "TargetSegment").ToListAsync();
                targetSegmentAnswer = JsonConvert.SerializeObject(targetSegmentdic.Where(x => targetSegmentValues.Contains(x.ValueCN.Replace(" ", ""))).Select(x => x.Code).ToList());
            }

            questionAnswers.Add(new ReadingTaskQuestionAnswer()
            {
                Answer = targetSegmentAnswer ?? string.Empty,
                ReadingQuestionCriterionTrialId = taskinfo.TrialReadingCriterionId,
                ReadingQuestionTrialId = readingQuestionList.Where(x => x.QuestionType == QuestionType.TargetSegment).Select(x => x.Id).FirstOrDefault(),
                TrialId = taskinfo.TrialId,
                SubjectId = taskinfo.SubjectId,
                VisitTaskId = taskinfo.Id,
            });

            questionAnswers.Add(new ReadingTaskQuestionAnswer()
            {
                Answer = dataTable.Rows[3]["B"].ToString() ?? string.Empty,
                ReadingQuestionCriterionTrialId = taskinfo.TrialReadingCriterionId,
                ReadingQuestionTrialId = readingQuestionList.Where(x => x.QuestionType == QuestionType.TargetSegmentRemarks).Select(x => x.Id).FirstOrDefault(),
                TrialId = taskinfo.TrialId,
                SubjectId = taskinfo.SubjectId,
                VisitTaskId = taskinfo.Id,
            });


            questionAnswers.Add(new ReadingTaskQuestionAnswer()
            {
                Answer = dataTable.Rows[4]["B"].ToString() ?? string.Empty,
                ReadingQuestionCriterionTrialId = taskinfo.TrialReadingCriterionId,
                ReadingQuestionTrialId = readingQuestionList.Where(x => x.QuestionType == QuestionType.ROIAllLength).Select(x => x.Id).FirstOrDefault(),
                TrialId = taskinfo.TrialId,
                SubjectId = taskinfo.SubjectId,
                VisitTaskId = taskinfo.Id,
            });


            var plaqueTypeAnswer = dataTable.Rows[5]["B"].ToString();

            if (plaqueTypeAnswer.IsNotNullOrEmpty())
            {
                var plaqueTypeAnswerValues = plaqueTypeAnswer.Replace(" ", "").Replace("，", ",").Split(",").ToList();
                var plaqueTypeAnswerdic = await _dictionaryRepository.Where(x => x.Parent.Code == "PlaqueType").ToListAsync();
                plaqueTypeAnswer = JsonConvert.SerializeObject(plaqueTypeAnswerdic
                   .Where(x => plaqueTypeAnswerValues.Any(val => x.ValueCN.Replace(" ", "").Contains(val)))
                   .Select(x => x.Code)
                   .ToList());
            }

            questionAnswers.Add(new ReadingTaskQuestionAnswer()
            {
                Answer = plaqueTypeAnswer ?? string.Empty,
                ReadingQuestionCriterionTrialId = taskinfo.TrialReadingCriterionId,
                ReadingQuestionTrialId = readingQuestionList.Where(x => x.QuestionType == QuestionType.PlaqueType).Select(x => x.Id).FirstOrDefault(),
                TrialId = taskinfo.TrialId,
                SubjectId = taskinfo.SubjectId,
                VisitTaskId = taskinfo.Id,
            });

            questionAnswers.Add(new ReadingTaskQuestionAnswer()
            {
                Answer = dataTable.Rows[6]["B"].ToString() ?? string.Empty,
                ReadingQuestionCriterionTrialId = taskinfo.TrialReadingCriterionId,
                ReadingQuestionTrialId = readingQuestionList.Where(x => x.QuestionType == QuestionType.AdjustReason).Select(x => x.Id).FirstOrDefault(),
                TrialId = taskinfo.TrialId,
                SubjectId = taskinfo.SubjectId,
                VisitTaskId = taskinfo.Id,
            });

            var questionids = questionAnswers.Select(x => x.ReadingQuestionTrialId).ToList();
            await _readingTaskQuestionAnswerRepository.DeleteFromQueryAsync(x => x.VisitTaskId == taskinfo.Id && questionids.Contains(x.ReadingQuestionTrialId));
            await _readingTableQuestionAnswerRepository.SaveChangesAsync();
            await _readingTaskQuestionAnswerRepository.AddRangeAsync(questionAnswers);
            await _readingTaskQuestionAnswerRepository.SaveChangesAsync();
            #endregion

            await _readingTableAnswerRowInfoRepository.DeleteFromQueryAsync(x => x.QuestionId == questionInfo.Id && x.VisitTaskId == taskinfo.Id);
            await _readingTableQuestionAnswerRepository.DeleteFromQueryAsync(x => x.QuestionId == questionInfo.Id && x.VisitTaskId == taskinfo.Id);
            await _readingTableQuestionAnswerRepository.SaveChangesAsync();
            await _readingTableAnswerRowInfoRepository.AddRangeAsync(tableAnsweRowInfos);
            await _readingTableQuestionAnswerRepository.AddRangeAsync(tableAnswers);
            await _readingTableQuestionAnswerRepository.SaveChangesAsync();

            await this.CalculateTask(new CalculateTaskInDto()
            {

                VisitTaskId = taskinfo.Id,
            });
        }

        /// <summary>
        /// 获取OCT-脂质角度模板
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<FileResult> GetOCTLipidAngleTemplate(GetExportTemplateInDto inDto)
        {
            var taskinfo = await _visitTaskRepository.Where(x => x.Id == inDto.VisitTaskId).Include(x => x.Subject).FirstNotNullAsync();
            var values =  new TemplateData()
            {
                SubjectID = (taskinfo.BlindSubjectCode.IsNullOrEmpty() ? taskinfo.Subject.Code : taskinfo.BlindSubjectCode),
                TaskBlindName = taskinfo.TaskBlindName,
            };
            return await _visitTaskHelpeService.ExportTemplateAsync(new IRaCIS.Application.Contracts.ExportTemplateAsyncDto()
            {
                ExportFileName = "OCT_LipidAngle_Template",
                TemplateCode = StaticData.Export.OCT_LipidAngle_Template,
                Data = values
            });
        }

        /// <summary>
        /// 导入OCT-脂质角度数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task UploadOCTLipidAngleTemplate()
        {
            #region 这个导入没有了 代码全部注释
            //var request = httpContext.HttpContext!.Request;
            //var file = request.Form.Files[0];
            //Guid visitTaskId = Guid.Parse(request.Form["VisitTaskId"]);
            //var taskinfo = await _visitTaskRepository.Where(x => x.Id == visitTaskId).Include(x => x.Subject).Include(x => x.TrialReadingCriterion).FirstNotNullAsync();
            //var uploadInfo = await _generalCalculateService.GetDataTableFromUpload(file, "OCTLipidAngle", taskinfo.TrialId);
            //List<string> sheetNames = new List<string>()
            //{
            //    "脂质角度","LipidAngle"
            //};

            //if (sheetNames.Intersect(uploadInfo.SheetNames).Count() == 0)
            //{
            //    throw new BusinessValidationFailedException(_localizer["IVUS_UplpadDataError"]);
            //}
            //var dataTable = uploadInfo.DataTable;

            //var values = new TemplateData()
            //{
            //    SubjectID = taskinfo.BlindSubjectCode.IsNullOrEmpty() ? taskinfo.Subject.Code : taskinfo.BlindSubjectCode,
            //    TaskBlindName = taskinfo.TaskBlindName,
            //};

            //if (values.SubjectID != dataTable.Rows[0]["B"].ToString() || values.TaskBlindName != dataTable.Rows[1]["B"].ToString())
            //{
            //    throw new BusinessValidationFailedException(_localizer["IVUS_UploadVisitTaskError"]);
            //}

            //var digitPlaces = taskinfo.TrialReadingCriterion.DigitPlaces ?? 0;
            //decimal getdecimalData(string value)
            //{
            //    return decimal.Parse(decimal.Round(decimal.Parse(value ?? "0"), digitPlaces, MidpointRounding.AwayFromZero).ToString("F" + digitPlaces.ToString()));
            //}
            //;

            //List<OCTFCTUploadData> measuredValueList = new List<OCTFCTUploadData>();
            //var errorRow = new List<int> { };

            //for (int i = 3; i < dataTable.Rows.Count; i++)
            //{
            //    try
            //    {
            //        measuredValueList.Add(new OCTFCTUploadData()
            //        {
            //            PlaqueNum = int.Parse(dataTable.Rows[i]["A"].ToString()),
            //            FirstData = getdecimalData(dataTable.Rows[i]["B"].ToString()),

            //        });
            //    }
            //    catch (Exception)
            //    {

            //        errorRow.Add(i + 1);
            //    }

            //}

            //measuredValueList = measuredValueList.OrderBy(x => x.PlaqueNum).ToList();

            //if (errorRow.Count() > 0)
            //{
            //    var errorRows = string.Join(',', errorRow.Select(i => i.ToString()));
            //    throw new BusinessValidationFailedException(_localizer["Service_TemplateException", errorRows]);
            //}


            //List<int> nums = new List<int>() { 1, 2, 3 };
            //if (measuredValueList.Any(x => !nums.Contains(x.PlaqueNum)))
            //{
            //    throw new BusinessValidationFailedException(_localizer["IVUSOCT_PlaqueNum123"]);
            //}


            //foreach (var item in measuredValueList)
            //{
            //    if (item.FirstData > 360)
            //    {
            //        throw new BusinessValidationFailedException(_localizer["IVUS_LipidAngleLess360"]);
            //    }
            //}

            //var questionInfo = await _readingQuestionTrialRepository.Where(x => x.ReadingQuestionCriterionTrialId == taskinfo.TrialReadingCriterionId && x.LesionType == LesionType.LipidAngle).FirstNotNullAsync();
            //var tableQuestionList = await _readingTableQuestionTrialRepository.Where(x => x.ReadingQuestionId == questionInfo.Id).ToListAsync();
            //List<ReadingTableAnswerRowInfo> tableAnsweRowInfos = new List<ReadingTableAnswerRowInfo>();
            //List<ReadingTableQuestionAnswer> tableAnswers = new List<ReadingTableQuestionAnswer>();

            //var maxnum = 0;


            //foreach (var item in measuredValueList)
            //{
            //    maxnum = maxnum + 1;
            //    var newRowId = NewId.NextGuid();
            //    // 斑块数据统计
            //    tableAnsweRowInfos.Add(new ReadingTableAnswerRowInfo()
            //    {
            //        Id = newRowId,
            //        QuestionId = questionInfo.Id,
            //        VisitTaskId = taskinfo.Id,
            //        TrialId = taskinfo.TrialId,
            //        RowIndex = maxnum,
            //        IsCurrentTaskAdd = true,
            //        BlindName = taskinfo.TaskBlindName,
            //        OrderMark = questionInfo.OrderMark,
            //        FristAddTaskId = taskinfo.Id,
            //        RowMark = questionInfo.OrderMark + decimal.Parse(maxnum.ToString()).GetLesionMark()
            //    });

            //    // 编号
            //    tableAnswers.Add(new ReadingTableQuestionAnswer()
            //    {
            //        Answer = item.PlaqueNum.ToString(),
            //        QuestionId = questionInfo.Id,
            //        TrialId = taskinfo.TrialId,
            //        VisitTaskId = taskinfo.Id,
            //        RowId = newRowId,
            //        RowIndex = maxnum,
            //        TableQuestionId = tableQuestionList.Where(x => x.ReadingQuestionId == questionInfo.Id && x.QuestionMark == QuestionMark.PlaqueNumber).Select(x => x.Id).FirstOrDefault(),
            //    });

            //    var avg = item.Avg.ToString();


            //    if (taskinfo.TrialReadingCriterion.DigitPlaces != -1)
            //    {
            //        avg = decimal.Round(decimal.Parse(avg ?? "0"), digitPlaces, MidpointRounding.AwayFromZero).ToString("F" + digitPlaces.ToString());

            //    }

            //    // 脂质角度
            //    tableAnswers.Add(new ReadingTableQuestionAnswer()
            //    {
            //        Answer = item.FirstData.ToString(),
            //        QuestionId = questionInfo.Id,
            //        TrialId = taskinfo.TrialId,
            //        VisitTaskId = taskinfo.Id,
            //        RowId = newRowId,
            //        RowIndex = maxnum,
            //        TableQuestionId = tableQuestionList.Where(x => x.ReadingQuestionId == questionInfo.Id && x.QuestionMark == QuestionMark.LipidAngle).Select(x => x.Id).FirstOrDefault(),
            //    });

            //    // 添加其他问题答案
            //    foreach (var otherQuestion in tableQuestionList.Where(x => !tableAnswers.Any(y => y.TableQuestionId == x.Id && y.RowId == newRowId)))
            //    {
            //        tableAnswers.Add(new ReadingTableQuestionAnswer()
            //        {
            //            Answer = string.Empty,
            //            QuestionId = questionInfo.Id,
            //            TrialId = taskinfo.TrialId,
            //            VisitTaskId = taskinfo.Id,
            //            RowId = newRowId,
            //            RowIndex = maxnum,
            //            TableQuestionId = otherQuestion.Id,
            //        });
            //    }
            //}
            //await _readingTableAnswerRowInfoRepository.DeleteFromQueryAsync(x => x.QuestionId == questionInfo.Id && x.VisitTaskId == taskinfo.Id);
            //await _readingTableQuestionAnswerRepository.DeleteFromQueryAsync(x => x.QuestionId == questionInfo.Id && x.VisitTaskId == taskinfo.Id);
            //await _readingTableQuestionAnswerRepository.SaveChangesAsync();
            //await _readingTableAnswerRowInfoRepository.AddRangeAsync(tableAnsweRowInfos);
            //await _readingTableQuestionAnswerRepository.AddRangeAsync(tableAnswers);
            //await _readingTableQuestionAnswerRepository.SaveChangesAsync();

            //await this.CalculateTask(new CalculateTaskInDto()
            //{

            //    VisitTaskId = taskinfo.Id,
            //});
            #endregion

        }


        /// <summary>
        /// 自动计算
        /// </summary>
        /// <param name="inDto"></param>
        /// <param name="calculateType"></param>
        /// <returns></returns>
        public async Task ReadingCalculate(ReadingCalculateDto inDto, List<QuestionType>? calculateType = null)
        {

            #region 计算  这里顺序非常重要 后面计算的值要依赖前面计算的结果
            var needAddList = new List<ReadingTaskQuestionAnswer>();

            List< ComputationTrigger > computationTriggers = new List<ComputationTrigger>()
            {
                ComputationTrigger.PatchDataStatistics,
                ComputationTrigger.SaveEICRFQuestions,
              
            };
            //if (!computationTriggers.Contains(inDto.ComputationTrigger)) 
            //{
            //    // 计算斑块统计数据
            //    await this.CalculatePatchDataStatistics(inDto);
            //    inDto = await _generalCalculateService.GetReadingCalculateDto(inDto.VisitTaskId);
            //}
           
            List<ReadingCalculateData> calculateList = new List<ReadingCalculateData>()
            {
				//// 斑块1-匹配动脉段最小FCT
				//new ReadingCalculateData (){QuestionType=QuestionType.Plaque1MinFCT,GetDecimalNullFun=GetPlaque1MinFCT},

    //            // 斑块2-匹配动脉段最小FCT
				//new ReadingCalculateData (){QuestionType=QuestionType.Plaque2MinFCT,GetDecimalNullFun=GetPlaque2MinFCT},

    //            // 斑块3-匹配动脉段最小FCT
				//new ReadingCalculateData (){QuestionType=QuestionType.Plaque3MinFCT,GetDecimalNullFun=GetPlaque3MinFCT},


                // 匹配动脉段最小FCT
				new ReadingCalculateData (){QuestionType=QuestionType.MatchingTheMinimumFCT,GetDecimalNullFun=GetMinFCT},

                // 平均最小FCT
				new ReadingCalculateData (){QuestionType=QuestionType.AvgMinFCT,GetDecimalNullFun=GetAvgFCT},

                // 脂质角度平均值
				new ReadingCalculateData (){QuestionType=QuestionType.AvgLipidAngle,GetDecimalNullFun=GetAvgLipidAngle},

                // 脂质角度最大值
				new ReadingCalculateData (){QuestionType=QuestionType.MaxLipidAngle,GetDecimalNullFun=GetMaxLipidAngle},

                //巨噬细胞浸润测量
                new ReadingCalculateData (){QuestionType=QuestionType.MacrophageInfiltrationMeasurement,GetStringFun=GetMacrophageInfiltration},

                  //巨噬细胞浸润角度测量
                new ReadingCalculateData (){QuestionType=QuestionType.MacrophageInfiltrationAngle,GetStringFun=GetMacrophageExtensionAngle},

                  //微通道测量
                new ReadingCalculateData (){QuestionType=QuestionType.MicrochannelMeasurement,GetStringFun=GetMicrochannels},

                  //胆固醇结晶测量
                new ReadingCalculateData (){QuestionType=QuestionType.CholesterolCrystalMeasurement,GetStringFun=GetCholesterolCrystallization},
            };


            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 ? "NA" : value.Value.ToString();
                    }
                    else if (calculate.GetStringFun != null)
                    {
                        item.Answer = await calculate.GetStringFun(inDto);
                    }
                    #endregion
                    // 修改修约小数位数

                    List<ValueOfType?> valueOfTypes = new List<ValueOfType?>() {

                               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, MidpointRounding.AwayFromZero).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


        }


        /// <summary>
        /// 计算斑块的统计数据
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task CalculatePatchDataStatistics(ReadingCalculateDto inDto)
        {
            // FCT 问题信息
            var fCTQuestionInfo = inDto.QuestionInfo.Where(x => x.LesionType == LesionType.ROI).FirstOrDefault();

            List<OCTInfo> oCTFCTInfos=new List<OCTInfo> ();
         

            foreach (var item in fCTQuestionInfo!.TableRowInfoList)
            {
                oCTFCTInfos.Add(new OCTInfo()
                {
                    PlaqueNum = item.TableQuestionList.Where(x => x.QuestionMark == QuestionMark.PlaqueNumber).Select(x => int.Parse(x.Answer)).FirstOrDefault(),
                    Data = item.TableQuestionList.Where(x => x.QuestionMark == QuestionMark.AvgFCT).Select(x => decimal.Parse(x.Answer)).FirstOrDefault(),
                    MacrophageInfiltrationMeasurement = item.TableQuestionList.Where(x => x.QuestionMark == QuestionMark.MacrophageInfiltrationMeasurement).Select(x => x.Answer).FirstOrDefault()??string.Empty,
                    MacrophageInfiltrationAngle = item.TableQuestionList.Where(x => x.QuestionMark == QuestionMark.MacrophageInfiltrationAngle).Select(x => x.Answer.IsNullOrEmptyReturnNull()).FirstOrDefault(),
                    MicrochannelMeasurement = item.TableQuestionList.Where(x => x.QuestionMark == QuestionMark.MicrochannelMeasurement).Select(x => x.Answer).FirstOrDefault() ?? string.Empty,
                    CholesterolCrystalMeasurement = item.TableQuestionList.Where(x => x.QuestionMark == QuestionMark.CholesterolCrystalMeasurement).Select(x => x.Answer).FirstOrDefault() ?? string.Empty,
                });
            }
         
            // 脂质角度 问题信息
            var lipidAngleQuestionInfo = inDto.QuestionInfo.Where(x => x.LesionType == LesionType.LipidAngle).FirstOrDefault();
            List<OCTInfo> lipidAngleInfos = new List<OCTInfo>();
            foreach (var item in lipidAngleQuestionInfo!.TableRowInfoList)
            {
                lipidAngleInfos.Add(new OCTInfo()
                {
                    PlaqueNum = item.TableQuestionList.Where(x => x.QuestionMark == QuestionMark.PlaqueNumber).Select(x => int.Parse(x.Answer)).FirstOrDefault(),
                    Data = item.TableQuestionList.Where(x => x.QuestionMark == QuestionMark.LipidAngle).Select(x => decimal.Parse(x.Answer)).FirstOrDefault(),
                });
            }

            // 所有的斑块编号
            var plaqueNumbers = oCTFCTInfos.Select(x => x.PlaqueNum).ToList().Union(lipidAngleInfos.Select(x => x.PlaqueNum).ToList()).Distinct().OrderBy(x => x).ToList();

            List<ReadingTableAnswerRowInfo> tableAnsweRowInfos = new List<ReadingTableAnswerRowInfo>();
            List<ReadingTableQuestionAnswer> tableAnswers = new List<ReadingTableQuestionAnswer>();

            // 斑块统计问题的Id
            var patchDataStatisticsInfo = await _readingQuestionTrialRepository.Where(x => x.ReadingQuestionCriterionTrialId == inDto.TrialReadingCriterionId && x.LesionType == LesionType.PatchDataStatistics).FirstNotNullAsync();

            // 斑块统计表格问题

            var patchDataTableQuestion = await _readingTableQuestionTrialRepository.Where(x => x.ReadingQuestionId == patchDataStatisticsInfo.Id).ToListAsync();

            #region 取小数
            string GetDigitPlacesData(string value)
            {
                if (inDto.DigitPlaces != -1)
                {
                    value = Math.Round(decimal.Parse(value ?? "0"), inDto.DigitPlaces, MidpointRounding.AwayFromZero).ToString("F" + inDto.DigitPlaces.ToString());

                }
                return value;
            }
            #endregion


            foreach (var item in plaqueNumbers)
            {
                var newRowId = NewId.NextGuid();

                var thisnumTableRows = inDto.QuestionInfo.Where(x => x.LesionType == LesionType.PatchDataStatistics).SelectMany(x => x.TableRowInfoList).Where(x => x.TableQuestionList.Any(y => y.QuestionMark == QuestionMark.PlaqueNumber && y.Answer == item.ToString())).ToList();

                // 斑块数据统计
                tableAnsweRowInfos.Add(new ReadingTableAnswerRowInfo()
                {
                    Id = newRowId,
                    QuestionId = patchDataStatisticsInfo.Id,
                    VisitTaskId = inDto.VisitTaskId,
                    TrialId = inDto.TrialId,
                    RowIndex = item,
                    IsCurrentTaskAdd = true,
                    BlindName = inDto.BlindName,
                    OrderMark = patchDataStatisticsInfo.OrderMark,
                    FristAddTaskId = inDto.VisitTaskId,
                    RowMark = patchDataStatisticsInfo.OrderMark + decimal.Parse(item.ToString()).GetLesionMark()
                });


                // 斑块编号
                tableAnswers.Add(new ReadingTableQuestionAnswer()
                {
                    Answer = item.ToString(),
                    Id = NewId.NextGuid(),
                    QuestionId = patchDataStatisticsInfo.Id,
                    TrialId = inDto.TrialId,
                    VisitTaskId = inDto.VisitTaskId,
                    RowId = newRowId,
                    RowIndex = item,
                    TableQuestionId = patchDataTableQuestion.Where(x => x.QuestionMark == QuestionMark.PlaqueNumber).Select(x => x.Id).FirstOrDefault(),
                });



                // 匹配动脉段最小FCT
                tableAnswers.Add(new ReadingTableQuestionAnswer()
                {
                    Answer = oCTFCTInfos.Where(x => x.PlaqueNum == item).Count()==0? string.Empty : GetDigitPlacesData(oCTFCTInfos.Where(x => x.PlaqueNum == item).MinOrDefault(x => x.Data).ToString()),
                    Id = NewId.NextGuid(),
                    QuestionId = patchDataStatisticsInfo.Id,
                    TrialId = inDto.TrialId,
                    VisitTaskId = inDto.VisitTaskId,
                    RowId = newRowId,
                    RowIndex = item,
                    TableQuestionId = patchDataTableQuestion.Where(x => x.QuestionMark == QuestionMark.MiniMumFCT).Select(x => x.Id).FirstOrDefault(),
                });

                // 平均最小FCT
                tableAnswers.Add(new ReadingTableQuestionAnswer()
                {
                    Answer = oCTFCTInfos.Where(x => x.PlaqueNum == item).Count() == 0 ? string.Empty : GetDigitPlacesData(oCTFCTInfos.Where(x => x.PlaqueNum == item).Average(x => x.Data).ToString()),
                    Id = NewId.NextGuid(),
                    QuestionId = patchDataStatisticsInfo.Id,
                    TrialId = inDto.TrialId,
                    VisitTaskId = inDto.VisitTaskId,
                    RowId = newRowId,
                    RowIndex = item,
                    TableQuestionId = patchDataTableQuestion.Where(x => x.QuestionMark == QuestionMark.AvgMinFCT).Select(x => x.Id).FirstOrDefault(),
                });

                // 巨噬细胞浸润测量
                tableAnswers.Add(new ReadingTableQuestionAnswer()
                {
                    Answer = oCTFCTInfos.Any(x => x.PlaqueNum == item && x.MacrophageInfiltrationMeasurement != string.Empty) ?
                    oCTFCTInfos.Any(x => x.PlaqueNum == item&&x.MacrophageInfiltrationMeasurement.EqEnum(IsPresent.Existence))? IsPresent.Existence.GetEnumInt(): IsPresent.NonExistence.GetEnumInt()
                    :string.Empty,
                    Id = NewId.NextGuid(),
                    QuestionId = patchDataStatisticsInfo.Id,
                    TrialId = inDto.TrialId,
                    VisitTaskId = inDto.VisitTaskId,
                    RowId = newRowId,
                    RowIndex = item,
                    TableQuestionId = patchDataTableQuestion.Where(x => x.QuestionMark == QuestionMark.MacrophageInfiltration).Select(x => x.Id).FirstOrDefault(),
                });

                // 巨噬细胞浸润角度测量
                tableAnswers.Add(new ReadingTableQuestionAnswer()
                {
                    Answer = oCTFCTInfos.Where(x => x.PlaqueNum == item&&x.MacrophageInfiltrationAngle!=null).Count() == 0 ? string.Empty : oCTFCTInfos.Where(x => x.PlaqueNum == item).Max(x=>x.MacrophageInfiltrationAngle??0).ToString(),
                    Id = NewId.NextGuid(),
                    QuestionId = patchDataStatisticsInfo.Id,
                    TrialId = inDto.TrialId,
                    VisitTaskId = inDto.VisitTaskId,
                    RowId = newRowId,
                    RowIndex = item,
                    TableQuestionId = patchDataTableQuestion.Where(x => x.QuestionMark == QuestionMark.MacrophageExtensionAngle).Select(x => x.Id).FirstOrDefault(),
                });

                // 微通道
                tableAnswers.Add(new ReadingTableQuestionAnswer()
                {
                    Answer = oCTFCTInfos.Any(x => x.PlaqueNum == item && x.MicrochannelMeasurement != string.Empty) ?
                    oCTFCTInfos.Any(x => x.PlaqueNum == item && x.MicrochannelMeasurement.EqEnum(IsPresent.Existence)) ? IsPresent.Existence.GetEnumInt() : IsPresent.NonExistence.GetEnumInt()
                    :string.Empty,
                    Id = NewId.NextGuid(),
                    QuestionId = patchDataStatisticsInfo.Id,
                    TrialId = inDto.TrialId,
                    VisitTaskId = inDto.VisitTaskId,
                    RowId = newRowId,
                    RowIndex = item,
                    TableQuestionId = patchDataTableQuestion.Where(x => x.QuestionMark == QuestionMark.Microchannels).Select(x => x.Id).FirstOrDefault(),
                });

                // 胆固醇结晶测量
                tableAnswers.Add(new ReadingTableQuestionAnswer()
                {
                    Answer = oCTFCTInfos.Any(x => x.PlaqueNum == item && x.CholesterolCrystalMeasurement != string.Empty) ?
                    oCTFCTInfos.Any(x => x.PlaqueNum == item && x.CholesterolCrystalMeasurement.EqEnum(IsPresent.Existence)) ? IsPresent.Existence.GetEnumInt() : IsPresent.NonExistence.GetEnumInt()
                    :string.Empty,
                    Id = NewId.NextGuid(),
                    QuestionId = patchDataStatisticsInfo.Id,
                    TrialId = inDto.TrialId,
                    VisitTaskId = inDto.VisitTaskId,
                    RowId = newRowId,
                    RowIndex = item,
                    TableQuestionId = patchDataTableQuestion.Where(x => x.QuestionMark == QuestionMark.CholesterolCrystallization).Select(x => x.Id).FirstOrDefault(),
                });



                // 脂质角度平均值
                tableAnswers.Add(new ReadingTableQuestionAnswer()
                {
                    Answer = lipidAngleInfos.Where(x => x.PlaqueNum == item).Count() == 0 ? string.Empty : GetDigitPlacesData(lipidAngleInfos.Where(x => x.PlaqueNum == item).Average(x => x.Data).ToString()),
                    Id = NewId.NextGuid(),
                    QuestionId = patchDataStatisticsInfo.Id,
                    TrialId = inDto.TrialId,
                    VisitTaskId = inDto.VisitTaskId,
                    RowId = newRowId,
                    RowIndex = item,
                    TableQuestionId = patchDataTableQuestion.Where(x => x.QuestionMark == QuestionMark.AvgLipidAngle).Select(x => x.Id).FirstOrDefault(),
                });

                // 脂质角度最大值
                tableAnswers.Add(new ReadingTableQuestionAnswer()
                {
                    Answer = lipidAngleInfos.Where(x => x.PlaqueNum == item).Count() == 0 ? string.Empty : GetDigitPlacesData(lipidAngleInfos.Where(x => x.PlaqueNum == item).MaxOrDefault(x => x.Data).ToString()),
                    Id = NewId.NextGuid(),
                    QuestionId = patchDataStatisticsInfo.Id,
                    TrialId = inDto.TrialId,
                    VisitTaskId = inDto.VisitTaskId,
                    RowId = newRowId,
                    RowIndex = item,
                    TableQuestionId = patchDataTableQuestion.Where(x => x.QuestionMark == QuestionMark.MaxAvgLipidAngle).Select(x => x.Id).FirstOrDefault(),
                });

                // 斑块类型
                tableAnswers.Add(new ReadingTableQuestionAnswer()
                {
                    Answer = string.Empty,
                    Id = NewId.NextGuid(),
                    QuestionId = patchDataStatisticsInfo.Id,
                    TrialId = inDto.TrialId,
                    VisitTaskId = inDto.VisitTaskId,
                    RowId = newRowId,
                    RowIndex = item,
                    TableQuestionId = patchDataTableQuestion.Where(x => x.QuestionMark == QuestionMark.Undetermined).Select(x => x.Id).FirstOrDefault(),
                });


                // 添加其他问题答案
                foreach (var otherQuestion in patchDataTableQuestion.Where(x => !tableAnswers.Any(y => y.TableQuestionId == x.Id && y.RowId == newRowId)))
                {
                    tableAnswers.Add(new ReadingTableQuestionAnswer()
                    {
                        Answer = string.Empty,
                        QuestionId = patchDataStatisticsInfo.Id,
                        TrialId = inDto.TrialId,
                        VisitTaskId = inDto.VisitTaskId,
                        RowId = newRowId,
                        RowIndex = item,
                        TableQuestionId = otherQuestion.Id,
                    });
                }


            }
            await _readingTableAnswerRowInfoRepository.BatchDeleteNoTrackingAsync(x =>x.QuestionId== patchDataStatisticsInfo.Id && x.VisitTaskId == inDto.VisitTaskId);
            await _readingTableQuestionAnswerRepository.BatchDeleteNoTrackingAsync(x => x.QuestionId == patchDataStatisticsInfo.Id && x.VisitTaskId == inDto.VisitTaskId);
            await _readingTableAnswerRowInfoRepository.AddRangeAsync(tableAnsweRowInfos);
            await _readingTableQuestionAnswerRepository.AddRangeAsync(tableAnswers);
            await _readingTableQuestionAnswerRepository.SaveChangesAsync();
        }



        /// <summary>
        /// 斑块1-匹配动脉段最小FCT
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<decimal?> GetPlaque1MinFCT(ReadingCalculateDto inDto)
        {
            return inDto.QuestionInfo.Where(x => x.LesionType == LesionType.PatchDataStatistics).SelectMany(x => x.TableRowInfoList).Where(x => x.TableQuestionList.Any(y => y.QuestionMark == QuestionMark.PlaqueNumber && y.Answer.IsNullOrEmptyReturn0() == 1)).SelectMany(x => x.TableQuestionList)
             .Where(x => x.QuestionMark == QuestionMark.MiniMumFCT).Select(x => x.Answer).FirstIsNullReturnEmpty().IsNullOrEmptyReturnNull();
        }

        /// <summary>
        /// 斑块2-匹配动脉段最小FCT
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<decimal?> GetPlaque2MinFCT(ReadingCalculateDto inDto)
        {
            return inDto.QuestionInfo.Where(x => x.LesionType == LesionType.PatchDataStatistics).SelectMany(x => x.TableRowInfoList).Where(x => x.TableQuestionList.Any(y => y.QuestionMark == QuestionMark.PlaqueNumber && y.Answer.IsNullOrEmptyReturn0() == 2)).SelectMany(x => x.TableQuestionList)
             .Where(x => x.QuestionMark == QuestionMark.MiniMumFCT).Select(x => x.Answer).FirstIsNullReturnEmpty().IsNullOrEmptyReturnNull();
        }

        /// <summary>
        /// 斑块3-匹配动脉段最小FCT
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<decimal?> GetPlaque3MinFCT(ReadingCalculateDto inDto)
        {
            return inDto.QuestionInfo.Where(x => x.LesionType == LesionType.PatchDataStatistics).SelectMany(x => x.TableRowInfoList).Where(x => x.TableQuestionList.Any(y => y.QuestionMark == QuestionMark.PlaqueNumber && y.Answer.IsNullOrEmptyReturn0() == 3)).SelectMany(x => x.TableQuestionList)
             .Where(x => x.QuestionMark == QuestionMark.MiniMumFCT).Select(x => x.Answer).FirstIsNullReturnEmpty().IsNullOrEmptyReturnNull();
        }


        /// <summary>
        /// 匹配动脉段最小FCT （平均值的最小值）
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<decimal?> GetMinFCT(ReadingCalculateDto inDto)
        {
            return inDto.QuestionInfo.Where(x => x.LesionType == LesionType.ROI).SelectMany(x => x.TableRowInfoList).SelectMany(x => x.TableQuestionList)
             .Where(x => x.QuestionMark == QuestionMark.AvgFCT).Select(x => x.Answer.IsNullOrEmptyReturn0()).Where(x => x != 0).MinOrDefault();
        }

        /// <summary>
        /// 平均最小FCT （平均值的平均值）
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<decimal?> GetAvgFCT(ReadingCalculateDto inDto)
        {
            return inDto.QuestionInfo.Where(x => x.LesionType == LesionType.ROI).SelectMany(x => x.TableRowInfoList).SelectMany(x => x.TableQuestionList)
             .Where(x => x.QuestionMark == QuestionMark.AvgFCT).Select(x => x.Answer.IsNullOrEmptyReturn0()).Where(x=>x!=0).DefaultIfEmpty(0).Average();
        }

        /// <summary>
        /// 脂质角度平均值
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<decimal?> GetAvgLipidAngle(ReadingCalculateDto inDto)
        {
            return inDto.QuestionInfo.Where(x => x.LesionType == LesionType.ROI).SelectMany(x => x.TableRowInfoList).SelectMany(x => x.TableQuestionList)
             .Where(x => x.QuestionMark == QuestionMark.LipidAngle&&x.Answer.IsNotNullOrEmpty()).Select(x => x.Answer.IsNullOrEmptyReturn0()).DefaultIfEmpty(0).Average();
        }


        /// <summary>
        /// 脂质角度最大
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<decimal?> GetMaxLipidAngle(ReadingCalculateDto inDto)
        {
            return inDto.QuestionInfo.Where(x => x.LesionType == LesionType.ROI).SelectMany(x => x.TableRowInfoList).SelectMany(x => x.TableQuestionList)
             .Where(x => x.QuestionMark == QuestionMark.LipidAngle).Select(x => x.Answer.IsNullOrEmptyReturn0()).MaxOrDefault();
        }


        public async Task<List<OCTInfo>> GetOCTInfo(ReadingCalculateDto inDto)
        {
             var fCTQuestionInfo = inDto.QuestionInfo.Where(x => x.LesionType == LesionType.ROI).FirstOrDefault();
            List<OCTInfo> oCTFCTInfos = new List<OCTInfo>();
            foreach (var item in fCTQuestionInfo!.TableRowInfoList)
            {
                oCTFCTInfos.Add(new OCTInfo()
                {
               
                   // Data = item.TableQuestionList.Where(x => x.QuestionMark == QuestionMark.AvgFCT).Select(x => decimal.Parse(x.Answer)).FirstOrDefault(),
                    MacrophageInfiltrationMeasurement = item.TableQuestionList.Where(x => x.QuestionMark == QuestionMark.MacrophageInfiltrationMeasurement).Select(x => x.Answer).FirstOrDefault() ?? string.Empty,
                    MacrophageInfiltrationAngle = item.TableQuestionList.Where(x => x.QuestionMark == QuestionMark.MacrophageInfiltrationAngle).Select(x => x.Answer.IsNullOrEmptyReturnNull()).FirstOrDefault(),
                    MicrochannelMeasurement = item.TableQuestionList.Where(x => x.QuestionMark == QuestionMark.MicrochannelMeasurement).Select(x => x.Answer).FirstOrDefault() ?? string.Empty,
                    CholesterolCrystalMeasurement = item.TableQuestionList.Where(x => x.QuestionMark == QuestionMark.CholesterolCrystalMeasurement).Select(x => x.Answer).FirstOrDefault() ?? string.Empty,
                });
            }

            return oCTFCTInfos;
        }

        /// <summary>
        /// 获取巨噬细胞浸润测量
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<string> GetMacrophageInfiltration(ReadingCalculateDto inDto)
        {
            List<OCTInfo> oCTFCTInfos = await GetOCTInfo(inDto);
            return oCTFCTInfos.Any(x => x.MacrophageInfiltrationMeasurement != string.Empty) ?
            oCTFCTInfos.Any(x => x.MacrophageInfiltrationMeasurement.EqEnum(IsPresent.Existence)) ? IsPresent.Existence.GetEnumInt() : IsPresent.NonExistence.GetEnumInt()
            : IsPresent.NonExistence.GetEnumInt();
        }

        /// <summary>
        /// 巨噬细胞浸润角度测量
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<string> GetMacrophageExtensionAngle(ReadingCalculateDto inDto)
        {
            List<OCTInfo> oCTFCTInfos = await GetOCTInfo(inDto);
            return oCTFCTInfos.Where(x =>x.MacrophageInfiltrationAngle != null).Count() == 0 ? string.Empty : oCTFCTInfos.Max(x => x.MacrophageInfiltrationAngle ?? 0).ToString();
        }

        /// <summary>
        /// 获取微通道汇总
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<string> GetMicrochannels(ReadingCalculateDto inDto)
        {
            List<OCTInfo> oCTFCTInfos = await GetOCTInfo(inDto);
            return oCTFCTInfos.Any(x =>  x.MicrochannelMeasurement != string.Empty) ?
            oCTFCTInfos.Any(x =>  x.MicrochannelMeasurement.EqEnum(IsPresent.Existence)) ? IsPresent.Existence.GetEnumInt() : IsPresent.NonExistence.GetEnumInt()
            : IsPresent.NonExistence.GetEnumInt();
        }

        /// <summary>
        /// 获取胆固醇结晶汇总
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<string> GetCholesterolCrystallization(ReadingCalculateDto inDto)
        {
            List<OCTInfo> oCTFCTInfos = await GetOCTInfo(inDto);
            return oCTFCTInfos.Any(x => x.CholesterolCrystalMeasurement != string.Empty) ?
            oCTFCTInfos.Any(x => x.CholesterolCrystalMeasurement.EqEnum(IsPresent.Existence)) ? IsPresent.Existence.GetEnumInt() : IsPresent.NonExistence.GetEnumInt()
            : IsPresent.NonExistence.GetEnumInt();
        }

        /// <summary>
        /// 验证访视提交
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task VerifyVisitTaskQuestions(VerifyVisitTaskQuestionsInDto inDto)
        {
            var taskinfo = await _visitTaskRepository.Where(x => x.Id == inDto.VisitTaskId).Include(x => x.Subject).Include(x => x.TrialReadingCriterion).FirstNotNullAsync();

            var noneDicomFiles = await _noneDicomStudyFileRepository.Where(x => x.VisitTaskId == inDto.VisitTaskId)
                .Select(x => new { x.FileType, x.FileName }).ToListAsync();
            var hasDicom = await _taskStudyRepository.AnyAsync(x => x.VisitTaskId == inDto.VisitTaskId);
            var hasZip = noneDicomFiles.Any(x => x.FileType == "application/zip"
                || x.FileType == "application/x-zip-compressed"
                || x.FileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase));

            if (!hasDicom || !hasZip)
            {
                throw new BusinessValidationFailedException(_localizer["OCTCriterionImageFileVerify"]);
            }

            var question = await _readingQuestionTrialRepository.Where(x => x.LesionType == LesionType.ROI && x.ReadingQuestionCriterionTrialId == taskinfo.TrialReadingCriterionId).FirstNotNullAsync();


            var tableQuestions = await _readingTableQuestionTrialRepository.Where(x => x.ReadingQuestionId== question.Id)
                .Where(x => x.IsRequired == IsRequired.Required && x.ShowQuestion == ShowQuestion.Show).ToListAsync();

            var rowinfoList = await _readingTableAnswerRowInfoRepository.Where(x => x.VisitTaskId == inDto.VisitTaskId && x.QuestionId == question.Id).Include(x=>x.ReadingQuestionTrial).OrderBy(x => x.RowIndex).ToListAsync();

            var tableQuesionAnswerList = await _readingTableQuestionAnswerRepository.Where(x => x.VisitTaskId == inDto.VisitTaskId && x.QuestionId == question.Id).ToListAsync();

            foreach (var item in rowinfoList)
            {
                foreach (var tq in tableQuestions)
                {
                    var answer =  tableQuesionAnswerList.Where(x => x.TableQuestionId == tq.Id && x.RowId == item.Id).FirstOrDefault();
                    if (answer == null || answer.Answer.IsNullOrEmpty())
                    {
                        throw new BusinessValidationFailedException(_localizer["OCTTableRequired", item.ReadingQuestionTrial.OrderMark+ item.RowIndex.GetLesionMark()]);
                    }
                }
            }

        }

        /// <summary>
        /// 匹配动脉段最小FCT
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<decimal?> GetAllMinFCT(ReadingCalculateDto inDto)
        {

            var allMinFCT = inDto.QuestionInfo.Where(x => x.LesionType == LesionType.ROI).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;
        }

        /// <summary>
        /// 所有FCT最小值中的平均值
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<decimal?> GetAvgMinFCT(ReadingCalculateDto inDto)
        {
            var allMinFCT = inDto.QuestionInfo.Where(x => x.LesionType == LesionType.ROI).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(); ;
        }


        /// <summary>
        /// 脂质角度最大值
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<decimal?> 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;
        }

        /// <summary>
        /// 脂质角度平均值
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<decimal?> 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 将上一次的访视病灶添加到这一次

        /// <summary>
        /// 将上一次的访视病灶添加到这一次
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<AddTaskLesionAnswerFromLastTaskOutDto> AddTaskLesionAnswerFromLastTask(AddTaskLesionAnswerFromLastTaskInDto inDto)
        {
            var visitTaskId = inDto.VisitTaskId;

            var taskinfo = await _visitTaskRepository.Where(x => x.Id == visitTaskId).ProjectTo<VisitTaskDto>(_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



    }

}
