using DocumentFormat.OpenXml.Office.SpreadSheetML.Y2023.MsForms;
using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Application.Service.Reading.Dto;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infra.EFCore.Common;
using IRaCIS.Core.Infrastructure;
using MassTransit;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Panda.DynamicWebApi.Attributes;

namespace IRaCIS.Core.Application.Service
{
    /// <summary>
    /// 阅片问题.标准
    /// </summary>
    [ApiExplorerSettings(GroupName = "Reading")]
    public class ReadingQuestionService(IRepository<SubjectVisit> _subjectVisitRepository,
        IRepository<ReadingQuestionCriterionSystem> _readingQuestionCriterionSystemRepository,
        IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository,
        IRepository<ReadingQuestionSystem> _readingQuestionSystemRepository,
        IRepository<ReadingQuestionTrial> _readingQuestionTrialRepository,
        IRepository<ClinicalDataTrialSet> _clinicalDataTrialSetRepository,
        IRepository<ClinicalDataSystemSet> _clinicalDataSystemSetRepository,
        IRepository<Dictionary> _dictionaryRepository,
            IRepository<CriterionNidusSystem> _criterionNidusSystemRepository,
          IRepository<SystemCriterionDictionaryCode> _systemCriterionDictionaryCodeRepository,
        IReadingImageTaskService _iReadingImageTaskService,
        IRepository<ReadingSystemCriterionDictionary> _readingSystemCriterionDictionaryRepository,
        IRepository<ReadingTableQuestionTrial> _readingTableQuestionTrialRepository,
        IRepository<ReadingCriterionPage> _readingCriterionPageRepository,
        IRepository<Trial> _trialRepository,
        IRepository<TumorAssessment_RECIST1Point1> _tumorAssessmentRepository,
        IRepository<OrganInfo> _organInfoRepository,
        IRepository<ReadingTableQuestionSystem> _readingTableQuestionSystemRepository,
        IRepository<ReadingTaskQuestionAnswer> _readingTaskQuestionAnswer,
        IRepository<PreviousPDF> _previousPDFRepository,
        IRepository<ReadingQuestionVisitJudgeRule> _readingQuestionVisitJudgeRuleRepository,
        IRepository<VisitStage> _visitStageRepository,
        IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService, IReadingQuestionService

    {

        #region 项目访视裁判规则

        /// <summary>
        /// 获取项目阅片标准各访视的裁判规则配置。
        /// 未配置规则的访视问题也会返回，供前端直接进行配置。
        /// </summary>
        [HttpPost]
        public async Task<List<TrialQuestionVisitJudgeRuleItemDto>> GetTrialQuestionVisitJudgeRule(GetTrialQuestionVisitJudgeRuleInDto inDto)
        {
            var questionList = await _readingQuestionTrialRepository
                .Where(x => x.ReadingQuestionCriterionTrialId == inDto.TrialReadingCriterionId && x.IsJudgeQuestion)
                .Where(x => x.LimitShow == LimitShow.AllShow
                    || (x.LimitShow == LimitShow.BaseLineShow && inDto.VisitNum == 0)
                    || (x.LimitShow == LimitShow.FollowShow && inDto.VisitNum != 0)
                    || (x.LimitShow == LimitShow.ExcludeSomeVisits && !x.ExcludeShowVisitList.Contains(inDto.VisitNum)))
                .WhereIf(inDto.ReadingQuestionId != null, x => x.Id == inDto.ReadingQuestionId)
                .OrderBy(x => x.ShowOrder)
                .Select(x => new TrialQuestionVisitJudgeRuleItemDto
                {
                    ReadingQuestionTrialId = x.Id,
                    QuestionName = x.QuestionName.LanguageName(x.QuestionEnName, _userInfo.IsEn_Us),
                    ShowOrder = x.ShowOrder,
                    Type = x.Type,
                    TypeValue = x.TypeValue,
                    QuestionGenre = x.QuestionGenre,
                    DictionaryCode = x.DictionaryCode,
                    Unit = x.Unit,
                    CustomUnit = x.CustomUnit,
                })
                .ToListAsync();

            var questionIds = questionList.Select(x => x.ReadingQuestionTrialId).ToList();
            var ruleList = await _readingQuestionVisitJudgeRuleRepository
                .Where(x => x.VisitNum == inDto.VisitNum && questionIds.Contains(x.ReadingQuestionId))
                .ToListAsync();

            return questionList.Select(question =>
            {
                var rule = ruleList.FirstOrDefault(x => x.ReadingQuestionId == question.ReadingQuestionTrialId);
                return new TrialQuestionVisitJudgeRuleItemDto
                {
                    ReadingQuestionTrialId = question.ReadingQuestionTrialId,
                    QuestionName = question.QuestionName,
                    ShowOrder = question.ShowOrder,
                    Type = question.Type,
                    PageName = question.PageName,
                    TypeValue = question.TypeValue,
                    QuestionGenre = question.QuestionGenre,
                    DictionaryCode = question.DictionaryCode,
                    Unit = question.Unit,
                    CustomUnit = question.CustomUnit,
                    AnswerGroup = rule?.AnswerGroup ?? new List<string>(),
                    AnswerCombination = rule?.AnswerCombination ?? new List<AnswerCombinationDto>(),
                    JudgeType = rule?.JudgeType ?? JudgeTypeEnum.None,
                    JudgeDifferenceValue = rule?.JudgeDifferenceValue,
                    JudgeDifferenceType = rule?.JudgeDifferenceType ?? default,
                };
            }).ToList();
        }

        /// <summary>
        /// 编辑项目阅片标准各访视的裁判规则配置。
        /// </summary>
        [HttpPost]
        public async Task<IResponseOutput> SetTrialQuestionVisitJudgeRule(SetTrialQuestionVisitJudgeRuleInDto inDto)
        {
            var questionIds = inDto.QuestionList.Select(x => x.ReadingQuestionTrialId).ToList();

            await _readingQuestionVisitJudgeRuleRepository.BatchDeleteNoTrackingAsync(x =>
                x.VisitNum == inDto.VisitNum && questionIds.Contains(x.ReadingQuestionId));

            var rules = inDto.QuestionList.Select(question => new ReadingQuestionVisitJudgeRule
            {
                Id = NewId.NextGuid(),
                ReadingQuestionId = question.ReadingQuestionTrialId,
                VisitNum = inDto.VisitNum,
                AnswerGroup = question.AnswerGroup ?? new List<string>(),
                AnswerCombination = question.AnswerCombination ?? new List<AnswerCombinationDto>(),
                JudgeType = question.JudgeType,
                JudgeDifferenceValue = question.JudgeDifferenceValue,
                JudgeDifferenceType = question.JudgeDifferenceType,
            }).ToList();

            if (rules.Count > 0)
            {
                await _readingQuestionVisitJudgeRuleRepository.AddRangeAsync(rules);
            }

            return ResponseOutput.Result(await _readingQuestionVisitJudgeRuleRepository.SaveChangesAsync());
        }

        #endregion


        #region 获取计算问题

        ///// <summary>
        ///// 获取自定义问题预览
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost]
        //public async Task<(List<DicomReadingQuestionAnswer>,bool)> GetCustomQuestionPreview(GetCustomQuestionPreviewInDto inDto)
        //{
        //   return (await _iReadingImageTaskService.GetReadingQuestion(inDto.TrialReadingCriterionId, null),true);
        //}

        /// <summary>
        /// 设置项目问题导出
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> SetTrialQuestionExportResult(SetTrialQuestionExportResultInDto inDto)
        {

            var cDISCCodeList = inDto.QuestionList.Where(x => x.CDISCCode.IsNotNullOrEmpty()).Select(x => x.CDISCCode).ToList();

            cDISCCodeList.AddRange(inDto.TableQuestionList.Where(x => x.CDISCCode.IsNotNullOrEmpty()).Select(x => x.CDISCCode).ToList());

            if (cDISCCodeList.Distinct().Count() != cDISCCodeList.Count)
            {
                throw new BusinessValidationFailedException(_localizer["ReadingQuestion_CDISCCodeRepeat"]);
            }

            if(inDto.QuestionList.Any(x=>x.ExportResult.Contains(ExportResult.NoneTumorCDISC)&&x.CDISCCode.IsNullOrEmpty())
                || inDto.TableQuestionList.Any(x => x.ExportResult.Contains(ExportResult.NoneTumorCDISC) && x.CDISCCode.IsNullOrEmpty())
                )
            {
                throw new BusinessValidationFailedException(_localizer["ReadingQuestion_CDISCCodeCannotEmpty"]);
            }

            List<ExportResult> needAdd = new List<ExportResult>()
            {
                ExportResult.DetailedTableOfAdjudicationResults,
                ExportResult.DetailedTableOfIntraReaderAnalysisResults,
                ExportResult.DetailedTableOfInterReaderAnalysisResults
            };
            foreach (var item in inDto.QuestionList) 
             {
                item.ExportResult= item.ExportResult.Except(needAdd).ToList();
                if (item.ExportResult.Contains(ExportResult.TableOfAssessmentResults))
                {
                    item.ExportResult.AddRange(needAdd);
                }
                var ExportResultStr=JsonConvert.SerializeObject(item.ExportResult);
                await _readingQuestionTrialRepository.UpdatePartialFromQueryAsync(x => x.Id == item.QuestionId, x => new ReadingQuestionTrial()
                {
                    ExportResultStr = ExportResultStr,
                    CDISCCode = item.CDISCCode,
                });

            }

            foreach (var item in inDto.TableQuestionList)
            {
                item.ExportResult = item.ExportResult.Except(needAdd).ToList();
                if (item.ExportResult.Contains(ExportResult.TableOfAssessmentResults))
                {
                    item.ExportResult.AddRange(needAdd);
                }

                var ExportResultStr = JsonConvert.SerializeObject(item.ExportResult);


                await _readingTableQuestionTrialRepository.UpdatePartialFromQueryAsync(x => x.Id == item.TableQuestionId, x => new ReadingTableQuestionTrial()
                {
                    ExportResultStr = ExportResultStr,
                    CDISCCode = item.CDISCCode,
                });
            }

            return   await _readingTableQuestionTrialRepository.SaveChangesAsync();
        }

        /// <summary>
        /// 获取项目的导出信息
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<GetTrialQuestionExportResultOutDto> GetTrialQuestionExportResult(GetTrialQuestionExportResultInDto inDto)
        {
            List<string> notShowType=new List<string>() { ReadingQestionType.Group, ReadingQestionType.Screenshot, ReadingQestionType.Summary, ReadingQestionType.Upload };

            var criterionInfo = await _readingQuestionCriterionTrialRepository.Where(x => x.Id == inDto.TrialReadingCriterionId).FirstNotNullAsync();
            
            var groupList = await _readingQuestionTrialRepository.Where(x => x.Type== ReadingQestionType.Group && x.ReadingQuestionCriterionTrialId == inDto.TrialReadingCriterionId)
                .OrderBy(x => x.ShowOrder).Select(x => new TrialQuestionExport()
                {
                    QuestionId = x.Id,
                    QuestionName = _userInfo.IsEn_Us ? x.GroupEnName : x.GroupName,
                    ExportResult = x.ExportResult,
                    GroupId= x.GroupId,
                    IsGroup= true,
                    ShowOrder = x.ShowOrder,
                    IsTableQuestion = false,
                    CDISCCode = x.CDISCCode,
                }).ToListAsync();


            var questionList = await _readingQuestionTrialRepository.Where(x => !notShowType.Contains(x.Type) && x.ReadingQuestionCriterionTrialId == inDto.TrialReadingCriterionId)
                .OrderBy(x => x.ShowOrder).Select(x => new TrialQuestionExport()
                {
                    QuestionId = x.Id,
                    GroupId=x.GroupId,
                    QuestionName = _userInfo.IsEn_Us ? x.QuestionEnName : x.QuestionName,
                    ExportResult = x.ExportResult,
                    ShowOrder = x.ShowOrder,
                    IsTableQuestion=false,
                    CDISCCode = x.CDISCCode,
                }).ToListAsync();

            var questionid = questionList.Select(x => x.QuestionId).ToList();

            var tableQuestionList = await _readingTableQuestionTrialRepository.Where(x => questionid.Contains(x.ReadingQuestionId))
                .Where(x => !notShowType.Contains(x.Type))
               .OrderBy(x => x.ShowOrder).Select(x => new TrialQuestionExport()
               {
                   QuestionId = x.ReadingQuestionId,
                   TableQuestionId = x.Id,
                   QuestionName = _userInfo.IsEn_Us ? x.QuestionEnName : x.QuestionName,
                   ExportResult = x.ExportResult,
                   ShowOrder = x.ShowOrder,
                   IsTableQuestion=true,
                   CDISCCode = x.CDISCCode,
               }).ToListAsync();

            questionList.ForEach(x =>
            {
                x.Children = tableQuestionList.Where(y => y.QuestionId == x.QuestionId).OrderBy(y => y.ShowOrder).ToList();
            });

            groupList.ForEach(x =>
            {
                x.Children = questionList.Where(y => y.GroupId == x.QuestionId).OrderBy(y => y.ShowOrder).ToList();
            });

            List<string> dicCode = new List<string>() { "1","2","8" };
            var dicList = await _dictionaryRepository.Where(x => x.Parent.Code == "ExportResult")
                .Where(x=> dicCode.Contains(x.Code))
                .OrderBy(x => x.ShowOrder)
                .Select(x => new TrialQuestionExportDic()
                {

                    Code = int.Parse(x.Code),
                    Value = _userInfo.IsEn_Us ? x.Value : x.ValueCN,
                    ValueCN = _userInfo.IsEn_Us ? x.Value : x.ValueCN,
                }).ToListAsync();

            return new GetTrialQuestionExportResultOutDto()
            {
                CriterionType = criterionInfo.CriterionType,
                CriterionGroup = criterionInfo.CriterionGroup,
                DicList = dicList,
                QuestionList = groupList
            };
        }



        /// <summary>
        /// 获取自定义表格问题预览
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<(GetReadingTableQuestionOutDto, bool)> GetCustomTableQuestionPreview(GetCustomQuestionPreviewInDto inDto)
        {
            List<ReadingTableQuestionAnswerInfo> tableAnswers = new List<ReadingTableQuestionAnswerInfo>();
            List<TableAnsweRowInfo> tableAnsweRowInfos = new List<TableAnsweRowInfo>();
            return (await _iReadingImageTaskService.GetReadingTableQuestion(

                new GetReadingTableQuestionOrAnswerInDto()
                {
                    TrialReadingCriterionId = inDto.TrialReadingCriterionId,
                    TableAnswers = tableAnswers,
                    TableAnsweRowInfos = tableAnsweRowInfos,
                    IsGetallQuestion = true,
                    IsGetPreview = true
                }

               ), true);
        }



        public async Task<Object> Test()
        {
            return await _readingQuestionTrialRepository.Select(x => x.QuestionName.LanguageName(x.QuestionEnName, _userInfo.IsEn_Us)).FirstAsync();
        }

        /// <summary>
        /// 获取问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<(List<GetCalculateQuestionsOutDto>,bool)> GetCalculateQuestions(GetCalculateQuestionsInDto inDto)
        {
            var result = await _readingQuestionTrialRepository

         .Where(x => x.ReadingQuestionCriterionTrialId == inDto.TrialCriterionId)
         .WhereIf(!inDto.Type.IsNullOrEmpty(), x => x.Type == inDto.Type)
         .WhereIf(inDto.TypeList.Count()>0, x => inDto.TypeList.Contains(x.Type))
         .OrderBy(x => x.ShowOrder)
         .ProjectTo<GetCalculateQuestionsOutDto>(_mapper.ConfigurationProvider).ToListAsync();


            var tablequestion=await _readingTableQuestionTrialRepository.Where(x=>x.TrialCriterionId==inDto.TrialCriterionId).ToListAsync();

            result.ForEach(x =>
            {
                x.TableQuestions = tablequestion.Where(y => y.ReadingQuestionId == x.Id).ToList();
            });

            return (result,true);
        }

        /// <summary>
        /// 获取系统计算问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<GetSystemCalculateQuestionsOutDto>> GetSystemCalculateQuestions(GetSystemCalculateQuestionsInDto inDto)
        {
            var result = await _readingQuestionSystemRepository

         .Where(x => x.ReadingQuestionCriterionSystemId == inDto.SystemCriterionId)
         .WhereIf(!inDto.Type.IsNullOrEmpty(), x => x.Type == inDto.Type)
         .WhereIf(inDto.TypeList.Count() > 0, x => inDto.TypeList.Contains(x.Type))
         .OrderBy(x => x.ShowOrder)
        .ProjectTo<GetSystemCalculateQuestionsOutDto>(_mapper.ConfigurationProvider).ToListAsync() ;


            var tablequestion = await _readingTableQuestionSystemRepository.Where(x => x.SystemCriterionId == inDto.SystemCriterionId).ToListAsync();

            result.ForEach(x =>
            {

                x.TableQuestions = tablequestion.Where(y => y.ReadingQuestionId == x.Id).ToList();
            });

            return result;
        }


        /// <summary>
        /// 获取表格问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<GetCalculateTableQuestionsOutDto>> GetCalculateTableQuestions(GetCalculateTableQuestionsInDto inDto)
        {

            var result = await _readingTableQuestionTrialRepository

         .Where(x => x.ReadingQuestionId == inDto.QuestionId)
         .WhereIf(!inDto.Type.IsNullOrEmpty(), x => x.Type == inDto.Type)
         .WhereIf(inDto.TypeList.Count() > 0, x => inDto.TypeList.Contains(x.Type))


         .OrderBy(x => x.ShowOrder)
          .ProjectTo<GetCalculateTableQuestionsOutDto>(_mapper.ConfigurationProvider, new
          {
              isEn_Us = _userInfo.IsEn_Us,
          }).ToListAsync();

            return result;
        }

        /// <summary>
        /// 获取系统表格问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<GetCalculateTableQuestionsOutDto>> GetSystemCalculateTableQuestions(GetCalculateTableQuestionsInDto inDto)
        {

            var result = await _readingTableQuestionSystemRepository

         .Where(x => x.ReadingQuestionId == inDto.QuestionId)
         .WhereIf(!inDto.Type.IsNullOrEmpty(), x => x.Type == inDto.Type)
         .WhereIf(inDto.TypeList.Count() > 0, x => inDto.TypeList.Contains(x.Type))
         .OrderBy(x => x.ShowOrder)
          .ProjectTo<GetCalculateTableQuestionsOutDto>(_mapper.ConfigurationProvider, new
          {
              isEn_Us = _userInfo.IsEn_Us,
          }).ToListAsync();

            return result;
        }


        #endregion


        #region 系统标准问题

        /// <summary>
        /// 获取系统问题分组
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<GetTrialGroupNameOutDto>> GetSystemGroupNameList(GetTrialGroupNameListInDto inDto)
        {
            var result = await _readingQuestionSystemRepository.Where(x => x.ReadingQuestionCriterionSystemId == inDto.CriterionId && x.Type == ReadingQestionType.Group).OrderBy(t => t.ShowOrder)
                  .Select(x => new GetTrialGroupNameOutDto()
                  {
                      GroupId = x.Id,
                      GroupName = x.GroupName,

                  }).ToListAsync();
            return result;

        }

        /// <summary>
        /// 获取系统问题
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<ReadingQuestionSystemView>> GetReadingQuestionSystemList(ReadingQuestionSystemViewInDto inDto)
        {
            var query = _readingQuestionSystemRepository.AsQueryable()
                .Where(x => x.ReadingQuestionCriterionSystemId == inDto.ReadingQuestionCriterionSystemId)
                 .WhereIf(!inDto.QuestionName.IsNullOrEmpty(), x => x.QuestionName.Contains(inDto.QuestionName))
                  .WhereIf(!inDto.Type.IsNullOrEmpty(), x => x.Type.Contains(inDto.Type))
                 .ProjectTo<ReadingQuestionSystemView>(_mapper.ConfigurationProvider);
            return await query.ToPagedListAsync(inDto, nameof(ReadingQuestionSystemView.ShowOrder));
        }

        /// <summary>
        /// 获取系统标准的其他问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<CriterionOtherQuestionOutDto>> GetSystemCriterionOtherQuestion(GetSystemCriterionOtherQuestionInDto inDto)
        {
            var types = new List<string>()
            {
                "select","radio"
            };
            var questionList = await _readingQuestionSystemRepository.Where(x => x.ReadingQuestionCriterionSystemId == inDto.ReadingQuestionCriterionSystemId)
                .Where(x => types.Contains(x.Type))
                .WhereIf(inDto.Id != null, x => x.Id != inDto.Id && x.ParentId != inDto.Id)
                .Select(x => new CriterionOtherQuestionOutDto()
                {
                    QuestionId = x.Id,
                    DictionaryCode = x.DictionaryCode,
                    QuestionGenre = x.QuestionGenre,
                    QuestionName = x.QuestionName.LanguageName(x.QuestionEnName, _userInfo.IsEn_Us),
                    TypeValue = x.TypeValue,
                    GroupName = x.GroupName,
                    GroupId = x.GroupId,
                }).ToListAsync();

            return questionList;
        }

        /// <summary>
        /// 新增修改系统问题
        /// </summary>
        /// <param name="indto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> AddOrUpdateReadingQuestionSystem(AddOrUpdateReadingQuestionSystemInDto indto)
        {
            indto.ParentTriggerValue = string.Join(',', indto.ParentTriggerValueList);
            indto.RelevanceValue = string.Join(',', indto.RelevanceValueList);

            indto.ExportResultStr = JsonConvert.SerializeObject(indto.ExportResult);
            indto.HighlightAnswer = JsonConvert.SerializeObject(indto.HighlightAnswerList);
            if (indto.Id != null)
            {
                var trialIdList = await _readingQuestionTrialRepository.Where(x => x.ReadingQuestionSystemId == indto.Id && x.IsJudgeQuestion && x.JudgeType != JudgeTypeEnum.None)
                    .Select(x => x.TrialId).ToListAsync();

                //if (trialIdList.Count>0)
                //{
                //    var trialNames = await _trialRepository.Where(x => trialIdList.Contains(x.Id)).Select(x => x.ExperimentName).ToListAsync();
                //    throw new BusinessValidationFailedException("当前问题在项目"+ string.Join(',', trialNames)  + "设置了裁判标准了,修改失败");
                //}
            }

            if (await _readingQuestionSystemRepository.AnyAsync(x => x.Id != indto.Id && x.ShowOrder == indto.ShowOrder && x.ReadingQuestionCriterionSystemId == indto.ReadingQuestionCriterionSystemId))
            {
                //---问题编号重复
                throw new BusinessValidationFailedException(_localizer["ReadingQuestion_IdDup"]);
            }
            var entity = await _readingQuestionSystemRepository.InsertOrUpdateAsync(indto, true);
            return ResponseOutput.Ok(entity.Id.ToString());
        }


        /// <summary>
        /// 删除系统问题
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id:guid}")]
        public async Task<IResponseOutput> DeleteReadingQuestionSystem(Guid id)
        {
            if (await _readingQuestionSystemRepository.AnyAsync(x => x.ParentId == id))
            {
                //---此问题存在子问题,请先删除子问题
                return ResponseOutput.NotOk(_localizer["ReadingQuestion_ChildrenExist"]);
            }

            if (await _readingQuestionSystemRepository.AnyAsync(x => x.GroupId == id))
            {
                //---此分组已被引用,请先删除被引用的问题
                return ResponseOutput.NotOk(_localizer["ReadingQuestion_GroupReferenced"]);
            }
            await _readingQuestionSystemRepository.DeleteFromQueryAsync(t => t.Id == id);
            var success = await _readingQuestionSystemRepository.SaveChangesAsync();
            return ResponseOutput.Result(success);
        }


        #endregion

        #region 系统标准表格问题

        /// <summary>
        /// 获取系统的表格问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<ReadingTableQuestionSystemView>> GetReadingTableQuestionSystemList(ReadingTableQuestionSystemQuery inDto)
        {
            var readingTableQuestionSystemQueryable = _readingTableQuestionSystemRepository
            .WhereIf(inDto.TableQuestionType != null, x => x.TableQuestionType == inDto.TableQuestionType!)
            .Where(x => x.ReadingQuestionId == inDto.ReadingQuestionId).ProjectTo<ReadingTableQuestionSystemView>(_mapper.ConfigurationProvider);

            var result = await readingTableQuestionSystemQueryable.OrderBy(x => x.ShowOrder).ToListAsync();
            return result;
        }

        /// <summary>
        /// 获取系统表格其他问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<CriterionOtherQuestionOutDto>> GetReadingTableOtherQuestionSystem(GetReadingTableOtherQuestionSystemInDto inDto)
        {
            var types = new List<string>()
            {
                "select","radio","class",
            };
            var questionList = await _readingTableQuestionSystemRepository.Where(x => x.ReadingQuestionId == inDto.ReadingQuestionId)
                   .Where(x => types.Contains(x.Type))
                .WhereIf(inDto.Id != null, x => x.Id != inDto.Id && x.ParentId != inDto.Id)

                .Select(x => new CriterionOtherQuestionOutDto()
                {
                    DictionaryCode = x.DictionaryCode,
                    QuestionGenre = x.TableQuestionType,
                    QuestionId = x.Id,
                    QuestionName = x.QuestionName,
                    TypeValue = x.TypeValue,
                }).ToListAsync();

            return questionList;
        }


        /// <summary>
        /// 新增修改系统表格问题
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> AddOrUpdateReadingTableQuestionSystem(ReadingTableQuestionSystemAddOrEdit indto)
        {
            indto.ParentTriggerValue = string.Join(',', indto.ParentTriggerValueList);
            indto.RelevanceValue = string.Join(',', indto.RelevanceValueList);
            indto.ExportResultStr = JsonConvert.SerializeObject(indto.ExportResult);
            var entity = await _readingTableQuestionSystemRepository.InsertOrUpdateAsync(indto, true);

            return ResponseOutput.Ok(entity.Id.ToString());

        }

        /// <summary>
        /// 删除系统表格问题
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete("{Id:guid}")]
        public async Task<IResponseOutput> DeleteReadingTableQuestionSystem(Guid Id)
        {
            if (await _readingTableQuestionSystemRepository.AnyAsync(x => x.ParentId == Id || x.RelevanceId == Id))
            {
                //---此问题存在子问题,请先删除子问题
                return ResponseOutput.NotOk(_localizer["ReadingQuestion_ChildrenExist"]);
            }

            await _readingTableQuestionSystemRepository.DeleteFromQueryAsync(t => t.Id == Id);
            var success = await _readingTableQuestionSystemRepository.SaveChangesAsync();
            return ResponseOutput.Result(success);
        }

        #endregion

        #region 项目标准问题

        /// <summary>
        /// 新增修改项目问题（项目）
        /// </summary>
        /// <param name="indto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> AddOrUpdateReadingQuestionTrial(AddOrUpdateReadingQuestionTrialInDto indto)
        {
            if (indto.Id != null)
            {
                var isArbitrationReading = await _readingQuestionCriterionTrialRepository.Where(x => x.Id == indto.ReadingQuestionCriterionTrialId).Select(x => x.IsArbitrationReading).FirstOrDefaultAsync();

                if (isArbitrationReading && (await _readingQuestionTrialRepository.AnyAsync(x => x.Id == indto.Id && x.IsJudgeQuestion && x.JudgeType != JudgeTypeEnum.None)))
                {
                    //---当前问题已经设置了裁判标准了,修改失败
                    throw new BusinessValidationFailedException(_localizer["ReadingQuestion_JudgmentSet"]);
                }
            }

            if (indto.ParentId == indto.RelevanceId && indto.ParentId != null && indto.ParentTriggerValue != indto.RelevanceValue)
            {
                //---显示依赖父问题和必填依赖的问题为同一个,但答案互斥,操作失败
                throw new BusinessValidationFailedException(_localizer["ReadingQuestion_ExcludeWithDependency"]);
            }


            if (await _readingQuestionTrialRepository.AnyAsync(x => x.Id != indto.Id && x.ShowOrder == indto.ShowOrder && x.TrialId == indto.TrialId && x.ReadingQuestionCriterionTrialId == indto.ReadingQuestionCriterionTrialId && x.ReadingCriterionPageId == indto.ReadingCriterionPageId))
            {
                //---问题编号重复
                throw new BusinessValidationFailedException(_localizer["ReadingQuestion_IdDup"]);
            }
            indto.ParentTriggerValue = string.Join(',', indto.ParentTriggerValueList);
            indto.ExportResultStr = JsonConvert.SerializeObject(indto.ExportResult);
            indto.RelevanceValue = string.Join(',', indto.RelevanceValueList);
            indto.HighlightAnswer = JsonConvert.SerializeObject(indto.HighlightAnswerList);

            if (indto.Id != null)
            {
                var relationList = await GetQuestionCalculateRelation(new GetQuestionCalculateRelationInDto()
                {
                    IsGetAll = true,
                    TrialReadingCriterionId = indto.ReadingQuestionCriterionTrialId,
                });

                var relation = relationList.FirstOrDefault(x => x.QuestionId == indto.Id);
                List<CalculateInfo> calculateInfoList = new List<CalculateInfo>();
                try
                {
                    var result = JsonConvert.DeserializeObject<List<CalculateInfo>>(indto.CalculateQuestions);
                    calculateInfoList = result == null ? new List<CalculateInfo>() : result;
                }
                catch (Exception)
                {


                }
                if (relation != null)
                {
                    relation.CalculateQuestionList = calculateInfoList;
                }

                this.VerifyCalculateRelation(relationList, indto.Id.Value, indto.Id.Value);
            }

            var entity = await _readingQuestionTrialRepository.InsertOrUpdateAsync(indto, true);
            await AddNAJudgeRule(entity);
            return ResponseOutput.Ok(entity.Id.ToString());
        }

        /// <summary>
        /// 添加问题的不适用规则
        /// </summary>
        /// <returns></returns>
        private async Task AddNAJudgeRule(ReadingQuestionTrial entity)
        {
            List<decimal> visitNums = new List<decimal>();
            if (entity.IsJudgeQuestion)
            {
                var visitStageNums = await _visitStageRepository
               .Where(x => x.TrialId == entity.TrialId)
               .Select(x => x.VisitNum)
               .Distinct()
               .ToListAsync();

                switch (entity.LimitShow)
                {
                    case LimitShow.BaseLineShow:
                        visitNums = visitStageNums.Where(x => x > 0).ToList();
                        visitNums.Add(-1);
                        break;
                    case LimitShow.FollowShow:
                        visitNums.Add(0);
                        break;
                    case LimitShow.ExcludeSomeVisits:
                        visitNums = entity.ExcludeShowVisitList;
                        break;
                }
            }

            if (visitNums.Count==0)
            {
                return;
            }


            await _readingQuestionVisitJudgeRuleRepository.BatchDeleteNoTrackingAsync(x =>
                x.ReadingQuestionId == entity.Id && visitNums.Contains(x.VisitNum));

            var rules = visitNums.Select(visitNum => new ReadingQuestionVisitJudgeRule
            {
                Id = NewId.NextGuid(),
                ReadingQuestionId = entity.Id,
                VisitNum = visitNum,
                JudgeType = JudgeTypeEnum.None,
            }).ToList();

            await _readingQuestionVisitJudgeRuleRepository.AddRangeAsync(rules);
            await _readingQuestionVisitJudgeRuleRepository.SaveChangesAsync();
        }

        /// <summary>
        /// 获取项目问题（项目）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<ReadingQuestionTrialView>> GetReadingQuestionTrialList(ReadingQuestionTrialViewInDto inDto)
        {
            var query = _readingQuestionTrialRepository.AsQueryable()
                .Where(x => x.ReadingQuestionCriterionTrialId == inDto.ReadingQuestionCriterionTrialId)
                 .WhereIf(!inDto.QuestionName.IsNullOrEmpty(), x => x.QuestionName.Contains(inDto.QuestionName) || x.QuestionEnName.Contains(x.QuestionEnName))
                  .WhereIf(!inDto.Type.IsNullOrEmpty(), x => x.Type.Contains(inDto.Type))
                   .Where(x => x.ReadingCriterionPageId == inDto.ReadingCriterionPageId)
                 .ProjectTo<ReadingQuestionTrialView>(_mapper.ConfigurationProvider).OrderBy(x => x.ShowOrder);
            return await query.ToListAsync();
        }

        /// <summary>
        ///  验证计算关系
        /// </summary>
        /// <param name="relationList"></param>
        /// <param name="QuestionId"></param>
        /// <param name="originalId"></param>
        /// <param name="count"></param>
        /// <exception cref="BusinessValidationFailedException"></exception>
        private void VerifyCalculateRelation(List<CalculateRelationDto> relationList, Guid QuestionId, Guid originalId, int count = 1)
        {
            // 防止有脏数据 循环验证 最多10000次
            if (count >= 10000)
            {
                //---计算依赖循环了！
                throw new BusinessValidationFailedException(_localizer["ReadingQuestion_CircularDependency"]);
            }

            var relation = relationList.Where(x => x.CalculateQuestionList.Any(y => y.QuestionId == QuestionId || y.TableQuestionId == QuestionId)).ToList();

            if (relation.Select(x => x.QuestionId).ToList().Contains(originalId))
            {
                //---计算依赖循环了！
                throw new BusinessValidationFailedException(_localizer["ReadingQuestion_CircularDependency"]);
            }

            else
            {

                relation.ForEach(x =>
                {

                    VerifyCalculateRelation(relationList, x.QuestionId, originalId, count++);
                });
            }

        }

        /// <summary>
        /// 获取问题计算关系
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<CalculateRelationDto>> GetQuestionCalculateRelation(GetQuestionCalculateRelationInDto inDto)
        {
            if (inDto.TrialReadingCriterionId != null)
            {
                return await _readingQuestionTrialRepository.Where(x => x.ReadingQuestionCriterionTrialId == inDto.TrialReadingCriterionId)
                    .WhereIf(inDto.IsGetJudge,x=>x.IsJudgeQuestion)
                    .WhereIf(!inDto.IsGetAll, x => x.DataSource == DataSources.Automatic && x.Type == "number")
                       .Select(x => new CalculateRelationDto()
                       {
                           QuestionId = x.Id,
                           QuestionName = x.QuestionName,
                           CustomCalculateMark = x.CustomCalculateMark,
                           CalculateQuestionList = x.CalculateQuestionList,
                           ValueType = x.ValueType,
                           Unit = x.Unit,
                           CustomUnit = x.CustomUnit,

                       }).ToListAsync();
            }
            else
            {
                return await _readingTableQuestionTrialRepository.Where(x => x.ReadingQuestionId == inDto.ReadingQuestionId)
                    .WhereIf(!inDto.IsGetAll, x => x.DataSource == DataSources.Automatic && x.Type == "number")
                      .Select(x => new CalculateRelationDto()
                      {
                          QuestionId = x.Id,
                          QuestionName = x.QuestionName,
                          CustomCalculateMark = x.CustomCalculateMark,
                          CalculateQuestionList = x.CalculateQuestionList,
                          ValueType = x.ValueType,
                          Unit = x.Unit,
                          CustomUnit = x.CustomUnit,

                      }).ToListAsync();
            }
        }


        /// <summary>
        /// 获取项目标准的其他问题(项目)
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<CriterionOtherQuestionOutDto>> GetTrialCriterionOtherQuestion(GetTrialCriterionOtherQuestionInDto inDto)
        {
            var types = new List<string>()
            {
                "select","radio","class",
            };
            var questionList = await _readingQuestionTrialRepository.Where(x => x.ReadingQuestionCriterionTrialId == inDto.ReadingQuestionCriterionTrialId)
                 .Where(x => types.Contains(x.Type)||(x.Type=="number"&&x.TypeValue!=string.Empty))
               
                .WhereIf(inDto.Id != null, x => x.Id != inDto.Id && x.ParentId != inDto.Id)
                 .Where(x => x.ReadingCriterionPageId == inDto.ReadingCriterionPageId)

                .Select(x => new CriterionOtherQuestionOutDto()
                {
                    QuestionId = x.Id,
                    DictionaryCode = x.DictionaryCode,
                    QuestionGenre = x.QuestionGenre,
                    QuestionName = x.QuestionName.LanguageName(x.QuestionEnName, _userInfo.IsEn_Us),
                    TypeValue = x.TypeValue,
                    GroupName = x.GroupName,
                }).ToListAsync();

            return questionList;
        }

        /// <summary>
        /// 删除项目问题（项目）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id:guid}")]
        public async Task<IResponseOutput> DeleteReadingQuestionTrial(Guid id)
        {
            if (await _readingQuestionTrialRepository.AnyAsync(x => x.ParentId == id))
            {
                //---此问题存在子问题,请先删除子问题
                return ResponseOutput.NotOk(_localizer["ReadingQuestion_ChildrenExist"]);
            }

            if (await _readingQuestionTrialRepository.AnyAsync(x => x.GroupId == id))
            {
                //---此分组已被引用,请先删除被引用的问题
                return ResponseOutput.NotOk(_localizer["ReadingQuestion_GroupReferenced"]);
            }
            await _readingQuestionTrialRepository.DeleteFromQueryAsync(t => t.Id == id);
            var success = await _readingQuestionTrialRepository.SaveChangesAsync();
            return ResponseOutput.Result(success);
        }

        /// <summary>
        /// 获取项目问题分组
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<GetTrialGroupNameOutDto>> GetTrialGroupNameList(GetTrialGroupNameListInDto inDto)
        {
            var result = await _readingQuestionTrialRepository.Where(x => x.ReadingQuestionCriterionTrialId == inDto.CriterionId && x.Type == ReadingQestionType.Group)
                .Where(x => x.ReadingCriterionPageId == inDto.ReadingCriterionPageId).OrderBy(t => t.ShowOrder)
                  .Select(x => new GetTrialGroupNameOutDto
                  {
                      GroupId = x.Id,
                      GroupName =_userInfo.IsEn_Us?x.GroupEnName: x.GroupName,
                  }).ToListAsync();

            return result;

        }

        #endregion

        #region 项目标准表格问题


        /// <summary>
        /// 获取项目的表格问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<(List<ReadingTableQuestionTrialView>, bool)> GetReadingTableQuestionTrialList(ReadingTableQuestionSystemQuery inDto)
        {

            var readingTableQuestionSystemQueryable = _readingTableQuestionTrialRepository
            .WhereIf(inDto.TableQuestionType != null, x => x.TableQuestionType == inDto.TableQuestionType)
            .Where(x => x.ReadingQuestionId == inDto.ReadingQuestionId).ProjectTo<ReadingTableQuestionTrialView>(_mapper.ConfigurationProvider);

            var result = await readingTableQuestionSystemQueryable.OrderBy(x => x.ShowOrder).ToListAsync();
            return (result, true);
        }

        /// <summary>
        /// 获取项目表格其他问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<CriterionOtherQuestionOutDto>> GetReadingTableOtherQuestionTrial(GetReadingTableOtherQuestionSystemInDto inDto)
        {

            var types = new List<string>()
            {
                "select","radio","class"
            };
            var questionList = await _readingTableQuestionTrialRepository.Where(x => x.ReadingQuestionId == inDto.ReadingQuestionId)
                   .Where(x => types.Contains(x.Type) || (x.Type == "number" && x.TypeValue != string.Empty))
                .WhereIf(inDto.Id != null, x => x.Id != inDto.Id && x.ParentId != inDto.Id)

                .Select(x => new CriterionOtherQuestionOutDto()
                {
                    QuestionId = x.Id,
                    QuestionGenre = x.TableQuestionType,
                    DictionaryCode = x.DictionaryCode,
                    QuestionName = x.QuestionName.LanguageName(x.QuestionEnName, _userInfo.IsEn_Us),
                    TypeValue = x.TypeValue,
                }).ToListAsync();

            return questionList;
        }




        /// <summary>
        /// 新增修改项目表格问题
        /// </summary>
        /// <param name="indto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> AddOrUpdateReadingTableQuestionTrial(ReadingTableQuestionTrialAddOrEdit indto)
        {

            var list = await _readingTableQuestionTrialRepository.Where(x => x.Id != indto.Id && x.ShowOrder == indto.ShowOrder && x.ReadingQuestionId == indto.ReadingQuestionId).ToListAsync();
            if (await _readingTableQuestionTrialRepository.AnyAsync(x => x.Id != indto.Id && x.ShowOrder == indto.ShowOrder && x.ReadingQuestionId == indto.ReadingQuestionId))
            {
                //---问题编号重复
                throw new BusinessValidationFailedException(_localizer["ReadingQuestion_IdDup"]);
            }
            if (indto.IsPreinstall)
            {
                if (await _readingTableQuestionTrialRepository.AnyAsync(x => x.ReadingQuestionId == indto.ReadingQuestionId && x.Id != indto.Id && x.IsPreinstall))
                {
                    throw new BusinessValidationFailedException(_localizer["ReadingQuestion_OnlyOnePreinstall"]);
                }
            }

            indto.ParentTriggerValue = string.Join(',', indto.ParentTriggerValueList);
            indto.RelevanceValue = string.Join(',', indto.RelevanceValueList);

            indto.ExportResultStr = JsonConvert.SerializeObject(indto.ExportResult);
            if (indto.Id != null)
            {
                var relationList = await GetQuestionCalculateRelation(new GetQuestionCalculateRelationInDto()
                {
                    IsGetAll = true,
                    ReadingQuestionId = indto.ReadingQuestionId,
                });

                var relation = relationList.FirstOrDefault(x => x.QuestionId == indto.Id);
                List<CalculateInfo> calculateInfoList = new List<CalculateInfo>();
                try
                {
                    var result = JsonConvert.DeserializeObject<List<CalculateInfo>>(indto.CalculateQuestions);
                    calculateInfoList = result == null ? new List<CalculateInfo>() : result;
                }
                catch (Exception)
                {


                }
                if (relation != null)
                {
                    relation.CalculateQuestionList = calculateInfoList;
                }

                this.VerifyCalculateRelation(relationList, indto.Id.Value, indto.Id.Value);
            }


            var entity = await _readingTableQuestionTrialRepository.InsertOrUpdateAsync(indto, true);

            return ResponseOutput.Ok(entity.Id.ToString());

        }





        /// <summary>
        /// 删除项目表格问题
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete("{Id:guid}")]
        public async Task<IResponseOutput> DeleteReadingTableQuestionTrial(Guid Id)
        {
            if (await _readingTableQuestionTrialRepository.AnyAsync(x => x.ParentId == Id || x.RelevanceId == Id))
            {
                //---此问题存在子问题,请先删除子问题
                return ResponseOutput.NotOk(_localizer["ReadingQuestion_ChildrenExist"]);
            }

            await _readingTableQuestionTrialRepository.DeleteFromQueryAsync(t => t.Id == Id);
            var success = await _readingTableQuestionTrialRepository.SaveChangesAsync();
            return ResponseOutput.Result(success);
        }


        #endregion






        /// <summary>
        /// 复制一个系统标准到另一系统标准
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        /// 
        [HttpPost]
        public async Task<IResponseOutput> CopySystemCriterionData(CopySystemCriterionDataInDto inDto)
        {
           
                var newSystemQuestionList = await _readingQuestionSystemRepository.Where(x => x.ReadingQuestionCriterionSystemId == inDto.SourceSystemCriterionId)
            .ProjectTo<ReadingQuestionSystemData>(_mapper.ConfigurationProvider).ToListAsync();
                newSystemQuestionList.ForEach(x =>
                {
                    x.Id = NewId.NextGuid();
                    x.ReadingQuestionCriterionSystemId = inDto.NewSystemCriterionId;
                });
                var copyNewQuestionList = newSystemQuestionList.Clone();
                var needAddDatas = new List<ReadingQuestionSystemData>();
                foreach (var x in newSystemQuestionList)
                {
                    var question = x.Clone();
                    if (question.ParentId != null)
                    {
                        question.ParentId = copyNewQuestionList.Where(y => x.ParentId == y.OriginalId).Select(y => y.Id).FirstOrDefault();
                    }
                    if (question.RelevanceId != null)
                    {
                        question.RelevanceId = copyNewQuestionList.Where(y => x.RelevanceId == y.OriginalId).Select(y => y.Id).FirstOrDefault();
                    }
                    if (question.GroupId != null)
                    {
                        question.GroupId = copyNewQuestionList.Where(y => x.GroupId == y.OriginalId).Select(y => y.Id).FirstOrDefault();
                    }
                
                needAddDatas.Add(question);
                };

                await _readingQuestionSystemRepository.BatchDeleteNoTrackingAsync(x => x.ReadingQuestionCriterionSystemId == inDto.NewSystemCriterionId);
                await _readingQuestionSystemRepository.AddRangeAsync(needAddDatas);

                #region 表格问题
                var newSystemTableQuestionList = await _readingTableQuestionSystemRepository.Where(x => x.SystemCriterionId == inDto.SourceSystemCriterionId)
               .ProjectTo<ReadingTableQuestionSystemData>(_mapper.ConfigurationProvider).ToListAsync();


                foreach (var question in newSystemTableQuestionList)
                {
                    question.SystemCriterionId = inDto.NewSystemCriterionId;
                    question.Id = NewId.NextGuid();
                }
                
                var copeNewSystemTableQuestionList = newSystemTableQuestionList.Clone();


                var needAddTableDatas = new List<ReadingTableQuestionSystemData>();
                foreach (var x in newSystemTableQuestionList)
                {
                    var tableQuestion = x.Clone();
                
                    tableQuestion.ReadingQuestionId = copyNewQuestionList.Where(y => x.ReadingQuestionId == y.OriginalId).Select(y => y.Id).FirstOrDefault();
                  if (tableQuestion.ParentId != null)
                    {
                        tableQuestion.ParentId = copeNewSystemTableQuestionList.Where(y => x.ParentId == y.OriginalId).Select(y => y.Id).FirstOrDefault();
                    }
                    if (tableQuestion.RelevanceId != null)
                    {
                        tableQuestion.RelevanceId = copeNewSystemTableQuestionList.Where(y => x.RelevanceId == y.OriginalId).Select(y => y.Id).FirstOrDefault();
                    }
                    if (tableQuestion.DependParentId != null)
                    {
                        tableQuestion.DependParentId = copeNewSystemTableQuestionList.Where(y => x.DependParentId == y.OriginalId).Select(y => y.Id).FirstOrDefault();
                    }
                    if (tableQuestion.ClassifyTableQuestionId != null)
                    {
                        tableQuestion.ClassifyTableQuestionId = copeNewSystemTableQuestionList.Where(y => x.ClassifyTableQuestionId == y.OriginalId).Select(y => y.Id).FirstOrDefault();
                    }
                needAddTableDatas.Add(tableQuestion);
                }
                await _readingTableQuestionSystemRepository.BatchDeleteNoTrackingAsync(x => x.SystemCriterionId == inDto.NewSystemCriterionId);
                await _readingTableQuestionSystemRepository.AddRangeAsync(needAddTableDatas);
            #endregion


            #region 器官
            var organData = await _organInfoRepository.Where(x => x.SystemCriterionId == inDto.SourceSystemCriterionId).ToListAsync();

            organData.ForEach(x =>
            {
                x.Id = NewId.NextGuid();
                x.SystemCriterionId = inDto.NewSystemCriterionId;
            });
            await _organInfoRepository.BatchDeleteNoTrackingAsync(x => x.SystemCriterionId == inDto.NewSystemCriterionId);
            await _organInfoRepository.AddRangeAsync(organData);
            #endregion

            #region 字典Code
            var dictionaryCodes = await _systemCriterionDictionaryCodeRepository.Where(x => x.SystemCriterionId == inDto.SourceSystemCriterionId).ToListAsync();

            dictionaryCodes.ForEach(x =>
            {
                x.Id = NewId.NextGuid();
                x.SystemCriterionId = inDto.NewSystemCriterionId;
            });
            await _systemCriterionDictionaryCodeRepository.BatchDeleteNoTrackingAsync(x => x.SystemCriterionId == inDto.NewSystemCriterionId);
            await _systemCriterionDictionaryCodeRepository.AddRangeAsync(dictionaryCodes);
            #endregion

            #region 字典


            var criterionDictionaries  =   await _readingSystemCriterionDictionaryRepository.Where(x => x.CriterionId == inDto.SourceSystemCriterionId).ToListAsync();
               
            criterionDictionaries.ForEach(x =>
            {
                x.Id = NewId.NextGuid();
                x.CriterionId = inDto.NewSystemCriterionId;
            });
            await _readingSystemCriterionDictionaryRepository.BatchDeleteNoTrackingAsync(x => x.CriterionId == inDto.NewSystemCriterionId);
            await _readingSystemCriterionDictionaryRepository.AddRangeAsync(criterionDictionaries);

            #endregion

            #region criterionNidus
            var criterionNidusSystems = await _criterionNidusSystemRepository.Where(x => x.CriterionId == inDto.SourceSystemCriterionId).ToListAsync();

            criterionNidusSystems.ForEach(x =>
            {
                x.Id = NewId.NextGuid();
                x.CriterionId = inDto.NewSystemCriterionId;
            });
            await _criterionNidusSystemRepository.BatchDeleteNoTrackingAsync(x => x.CriterionId == inDto.NewSystemCriterionId);
            await _criterionNidusSystemRepository.AddRangeAsync(criterionNidusSystems);
            #endregion




            await _readingTableQuestionSystemRepository.SaveChangesAsync();
            return ResponseOutput.Ok();
        }

        /// <summary>
        /// 同步系统标准
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task SynchronizeSystemCriterionQuestion(SynchronizeSystemCriterionInDto inDto)
        {
            // 先找到项目系统问题Id和项目问题Id的对应关系
            var questionRelation = _readingQuestionSystemRepository.Where(x => x.ReadingQuestionCriterionSystemId == inDto.FromSystemCriterionId).ToDictionary(
                x => x.Id,
                x => NewId.NextGuid()
                );


            var newQuestionList = await _readingQuestionSystemRepository.Where(x => x.ReadingQuestionCriterionSystemId == inDto.FromSystemCriterionId).ProjectTo<AddOrUpdateReadingQuestionSystemInDto>(_mapper.ConfigurationProvider).ToListAsync();
            var copyNewQuestionList = newQuestionList.Clone();

            var needAddDatas = new List<ReadingQuestionSystem>();

            foreach (var x in newQuestionList)
            {
                var question = x.Clone();
                question.ReadingQuestionCriterionSystemId = inDto.ToSystemCriterionId;
                question.Id = questionRelation[question.Id!.Value];
                if (question.ParentId != null)
                {
                    question.ParentId = questionRelation[question.ParentId ?? default(Guid)];
                }
                if (question.GroupId != null)
                {
                    question.GroupId = questionRelation[question.GroupId ?? default(Guid)];
                }
                if (question.RelevanceId != null)
                {
                    question.RelevanceId = questionRelation[question.RelevanceId ?? default(Guid)];
                }
                needAddDatas.Add(_mapper.Map<ReadingQuestionSystem>(question));
            };

            await _readingQuestionSystemRepository.BatchDeleteNoTrackingAsync(x => x.ReadingQuestionCriterionSystemId == inDto.ToSystemCriterionId);
            await _readingQuestionSystemRepository.AddRangeAsync(needAddDatas);


            var tableQuestionRelation = _readingTableQuestionSystemRepository.Where(x => x.SystemCriterionId == inDto.FromSystemCriterionId).ToDictionary(
                    x => x.Id,
                    x => NewId.NextGuid()
                    );


            var newtableQuestion = await _readingTableQuestionSystemRepository.Where(x => x.SystemCriterionId == inDto.FromSystemCriterionId).ToListAsync();


            var copyNewTableQuestionList = newtableQuestion.Clone();

            var needAddTableDatas = new List<ReadingTableQuestionSystem>();
            foreach (var x in newtableQuestion)
            {
                var tableQuestion = x.Clone();


                tableQuestion.SystemCriterionId = inDto.ToSystemCriterionId;
                tableQuestion.Id = tableQuestionRelation[tableQuestion.Id];
                tableQuestion.ReadingQuestionId = questionRelation[tableQuestion.ReadingQuestionId];
                if (tableQuestion.ParentId != null)
                {
                    tableQuestion.ParentId = tableQuestionRelation[tableQuestion.ParentId.Value];
                }
                if (tableQuestion.RelevanceId != null)
                {
                    tableQuestion.RelevanceId = tableQuestionRelation[tableQuestion.RelevanceId.Value]; ;
                }

                if (tableQuestion.DependParentId != null)
                {
                    tableQuestion.DependParentId = tableQuestionRelation[tableQuestion.DependParentId.Value]; ;
                }

                needAddTableDatas.Add(tableQuestion);
            }


            await _readingTableQuestionSystemRepository.BatchDeleteNoTrackingAsync(x => x.SystemCriterionId == inDto.ToSystemCriterionId);
            await _readingTableQuestionSystemRepository.AddRangeAsync(needAddTableDatas);
            await _readingTableQuestionSystemRepository.SaveChangesAsync();

        }

        /// <summary>
        /// 同步标准到项目新（2022-08-10）
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task SynchronizeCriterion(SynchronizeCriterionInDto inDto)
        {
            var trialCriterion = await _readingQuestionCriterionTrialRepository.Where(x => x.Id == inDto.TrialReadingCriterionId).AsNoTracking().FirstOrDefaultAsync();

            if (trialCriterion != null)
            {
                if (trialCriterion.ReadingQuestionCriterionSystemId != null)
                {
                    // 先找到项目系统问题Id和项目问题Id的对应关系
                    var questionRelation = _readingQuestionTrialRepository.Where(x => x.ReadingQuestionCriterionTrialId == trialCriterion.Id).ToDictionary(
                        x => x.ReadingQuestionSystemId ?? default(Guid),
                        x => x.Id
                        );

                    // 将系统里面的问题转为项目问题
                    var newTrialQuestionList = await _readingQuestionSystemRepository.Where(x => x.ReadingQuestionCriterionSystemId == trialCriterion.ReadingQuestionCriterionSystemId)
                      .ProjectTo<ReadingQuestionTrial>(_mapper.ConfigurationProvider).ToListAsync();
                    newTrialQuestionList.ForEach(x =>
                    {
                        if (questionRelation.ContainsKey(x.Id))
                        {
                            x.Id = questionRelation[x.Id];
                        }
                        else
                        {
                            var newid = NewId.NextGuid();
                            questionRelation.Add(x.Id, newid);
                            x.Id = newid;
                        }

                        x.ReadingQuestionCriterionTrialId = trialCriterion.Id;
                        x.TrialId = trialCriterion.TrialId;
                        x.AnswerGroup = "[]";
                        x.AnswerCombination="[]";
                        x.JudgeDifferenceValue = 0;
                    });
                    var copyNewQuestionList = newTrialQuestionList.Clone();
                    // var trialQuestionList = await _readingQuestionTrialRepository.Where(x => x.ReadingQuestionCriterionTrialId == trialCriterion.Id).ToListAsync();
                    var needAddDatas = new List<ReadingQuestionTrial>();

                    foreach (var x in newTrialQuestionList)
                    {
                        var question = x.Clone();
                        if (question.ParentId != null)
                        {
                            question.ParentId = questionRelation[question.ParentId ?? default(Guid)];
                        }
                        if (question.GroupId != null)
                        {
                            question.GroupId = questionRelation[question.GroupId ?? default(Guid)];
                        }
                        if (question.RelevanceId != null)
                        {
                            question.RelevanceId = questionRelation[question.RelevanceId ?? default(Guid)];
                        }




                        needAddDatas.Add(question);
                    };

                    await _readingQuestionTrialRepository.BatchDeleteNoTrackingAsync(x => x.ReadingQuestionCriterionTrialId == trialCriterion.Id && !x.IsAdditional);
                    await _readingQuestionTrialRepository.AddRangeAsync(needAddDatas);
                    var systemCriterion = await _readingQuestionCriterionSystemRepository.Where(x => x.Id == trialCriterion.ReadingQuestionCriterionSystemId).FirstNotNullAsync();
                    await _readingQuestionCriterionTrialRepository.BatchUpdateNoTrackingAsync(x => x.Id == trialCriterion.Id, x => new ReadingQuestionCriterionTrial()
                    {
                        SynchronizeTime = DateTime.Now,
                        IsMustGlobalReading = systemCriterion.IsMustGlobalReading,
                        IseCRFShowInDicomReading = systemCriterion.IseCRFShowInDicomReading,
                        CriterionGroup = systemCriterion.CriterionGroup,
                        IsGlobalReading = systemCriterion.IsMustGlobalReading ? true : trialCriterion.IsGlobalReading,
                        IsReadingPeriod = systemCriterion.IsMustGlobalReading ? true : trialCriterion.IsReadingPeriod,
                    });


                    #region 表格问题

                    // 先找到项目系统问题Id和项目问题Id的对应关系

                    var questionIds = needAddDatas.Select(x => x.Id).ToList();


                    var tableQuestionRelation = _readingTableQuestionTrialRepository.Where(x => x.TrialCriterionId == trialCriterion.Id && x.SystemTableQuestionId != null).ToDictionary(
                        x => x.SystemTableQuestionId ?? default(Guid),
                        x => x.Id
                        );


                    var newTrialTableQuestionList = await _readingTableQuestionSystemRepository.Where(x => x.SystemCriterionId == trialCriterion.ReadingQuestionCriterionSystemId)
                   .ProjectTo<ReadingTrialTableQuestionData>(_mapper.ConfigurationProvider).ToListAsync();


                    newTrialTableQuestionList.ForEach(x =>
                    {
                        if (tableQuestionRelation.ContainsKey(x.Id))
                        {
                            x.Id = tableQuestionRelation[x.Id];
                        }
                        else
                        {
                            var newid = NewId.NextGuid();
                            tableQuestionRelation.Add(x.Id, newid);
                            x.Id = newid;
                        }
                    });

                    var copyNewTrialTableQuestionList = newTrialTableQuestionList.Clone();

                    var needAddTableDatas = new List<ReadingTrialTableQuestionData>();
                    foreach (var x in newTrialTableQuestionList)
                    {
                        var tableQuestion = x.Clone();
                        tableQuestion.TrialId = trialCriterion.TrialId;
                        tableQuestion.TrialCriterionId = trialCriterion.Id;

                        tableQuestion.ReadingQuestionId = copyNewQuestionList.Where(y => y.ReadingQuestionSystemId == x.ReadingQuestionId).Select(y => y.Id).FirstOrDefault();
                        if (tableQuestion.ParentId != null)
                        {
                            tableQuestion.ParentId = copyNewTrialTableQuestionList.Where(y => x.ParentId == y.OriginalId).Select(y => y.Id).FirstOrDefault();
                        }
                        if (tableQuestion.RelevanceId != null)
                        {
                            tableQuestion.RelevanceId = copyNewTrialTableQuestionList.Where(y => x.RelevanceId == y.OriginalId).Select(y => y.Id).FirstOrDefault();
                        }

                        if (tableQuestion.DependParentId != null)
                        {
                            tableQuestion.DependParentId = copyNewTrialTableQuestionList.Where(y => x.DependParentId == y.OriginalId).Select(y => y.Id).FirstOrDefault();
                        }

                        needAddTableDatas.Add(tableQuestion);
                    }


                    await _readingTableQuestionTrialRepository.BatchDeleteNoTrackingAsync(x => x.TrialCriterionId == trialCriterion.Id);
                    await _readingTableQuestionTrialRepository.AddRangeAsync(_mapper.Map<List<ReadingTableQuestionTrial>>(needAddTableDatas));
                    #endregion

                }
            }

        }


        ///// <summary>
        ///// 更改项目标准（老）
        ///// </summary>
        ///// <param name="systemCriterionId"></param>
        ///// <returns></returns>
        //private async Task UpdateTrialCriterion(Guid systemCriterionId)
        //{
        //    await _readingQuestionCriterionTrialRepository.BatchUpdateNoTrackingAsync(x => x.ReadingQuestionCriterionSystemId == systemCriterionId, x => new ReadingQuestionCriterionTrial()
        //    {
        //        IsCompleteConfig = true,
        //    });
        //    var systemCriterionQuestionList = await _readingQuestionSystemRepository.Where(x => x.ReadingQuestionCriterionSystemId == systemCriterionId).ToListAsync();
        //    var trialCriterionList = await _readingQuestionCriterionTrialRepository.Where(x => x.ReadingQuestionCriterionSystemId == systemCriterionId).Select(x => new
        //    {
        //        x.Id,
        //        x.TrialId,
        //    }).ToListAsync();
        //    var trialCriterionIdList = trialCriterionList.Select(x => x.Id).ToList();
        //    List<ReadingQuestionTrial> needAddQuestionList = new List<ReadingQuestionTrial>();
        //    foreach (var item in trialCriterionList)
        //    {
        //        await _readingQuestionTrialRepository.BatchDeleteNoTrackingAsync(x => trialCriterionIdList.Contains(x.ReadingQuestionCriterionTrialId));
        //        List<ReadingQuestionTrial> trialQuestionList = new List<ReadingQuestionTrial>();
        //        SetChildParentQuestion(item.Id, item.TrialId, systemCriterionQuestionList, trialQuestionList);
        //        needAddQuestionList.AddRange(trialQuestionList);
        //    }
        //    await _readingQuestionTrialRepository.AddRangeAsync(needAddQuestionList);
        //}


        ///// <summary>
        ///// 更改项目标准（新）
        ///// </summary>
        ///// <param name="systemCriterionId"></param>
        ///// <returns></returns>
        //private async Task SynchronizeSystemCriterion(Guid systemCriterionId)
        //{
        //    var systemCriterion = await _readingQuestionCriterionSystemRepository.FirstOrDefaultAsync(x => x.Id == systemCriterionId);

        //    var trialCriterionList = await _readingQuestionCriterionTrialRepository.Where(x => x.ReadingQuestionCriterionSystemId == systemCriterionId).Select(x => new
        //    {
        //        x.Id,
        //        x.TrialId,
        //    }).ToListAsync();

        //    var trialCriterionIds = trialCriterionList.Select(x => x.Id).ToList();
        //    var systemQuestionList = await _readingQuestionSystemRepository.Where(x => x.ReadingQuestionCriterionSystemId == systemCriterionId).ToListAsync();
        //    var trialQuestions = await _readingQuestionTrialRepository.Where(x => trialCriterionIds.Contains(x.ReadingQuestionCriterionTrialId)).Select(x => new TrialQuestion
        //    {
        //        AnswerCombination = x.AnswerCombination,
        //        AnswerGroup = x.AnswerGroup,
        //        Id = x.Id,
        //        JudgeType = x.JudgeType,
        //        ReadingCriterionPageId = x.ReadingCriterionPageId,
        //        RelevanceId = x.RelevanceId,
        //        RelevanceValue = x.RelevanceValue,
        //        ImageCount = x.ImageCount,
        //        ParentId = x.ParentId,
        //        ReadingQuestionCriterionTrialId = x.ReadingQuestionCriterionTrialId,
        //        ReadingQuestionSystemId = x.ReadingQuestionSystemId,
        //        SystemParentId = x.SystemParentId
        //    }).ToListAsync();

        //    List<ReadingQuestionTrial> trialQuestionList = new List<ReadingQuestionTrial>();
        //    foreach (var item in trialCriterionList)
        //    {

        //        var thisTrialQuestions = trialQuestions.Where(x => x.ReadingQuestionCriterionTrialId == item.Id).ToList();

        //        var query = systemQuestionList.GroupJoin(thisTrialQuestions, a => a.Id, b => b.ReadingQuestionSystemId, (a, b) => new
        //        {
        //            a,
        //            trialQuestion = b
        //        }).SelectMany(a => a.trialQuestion, (m, n) => new ReadingQuestionTrial
        //        {
        //            Id = n.Id,

        //        });
        //        var needAddQuestionList = systemQuestionList.GroupJoin(thisTrialQuestions, a => a.Id, b => b.ReadingQuestionSystemId, (x, y) => new { system = x, trial = y })
        //          .SelectMany(
        //          a => a.trial.DefaultIfEmpty(),
        //          (c, d) => new ReadingQuestionTrial
        //          {
        //              Id = (c.trial.FirstOrDefault()?.Id) ?? NewId.NextGuid(),
        //              ShowOrder = c.system.ShowOrder,
        //              SystemParentId = c.system.ParentId,
        //              ReadingQuestionSystemId = c.system.Id,
        //              AnswerCombination = (c.trial.FirstOrDefault()?.AnswerCombination) ?? string.Empty,
        //              AnswerGroup = (c.trial.FirstOrDefault()?.AnswerGroup) ?? string.Empty,
        //              GroupName = c.system.GroupName,
        //              IsEnable = c.system.IsEnable,

        //              ShowQuestion = c.system.ShowQuestion,
        //              IsJudgeQuestion = c.system.IsJudgeQuestion,
        //              IsRequired = c.system.IsRequired,
        //              JudgeType = (c.trial.FirstOrDefault()?.JudgeType) ?? JudgeTypeEnum.None,
        //              ParentId = c.trial.FirstOrDefault()?.ParentId,
        //              ParentTriggerValue = c.system.ParentTriggerValue,
        //              QuestionName = c.system.QuestionName,
        //              ReadingCriterionPageId = c.trial.FirstOrDefault()?.ReadingCriterionPageId,
        //              RelevanceId = c.trial.FirstOrDefault()?.RelevanceId,
        //              ImageCount = c.trial.FirstOrDefault()?.ImageCount ?? 0,
        //              RelevanceValue = c.trial.FirstOrDefault()?.RelevanceValue,
        //              ReadingQuestionCriterionTrialId = item.Id,
        //              Remark = c.system.Remark,
        //              TrialId = item.TrialId,
        //              Type = c.system.Type,

        //              TypeValue = c.system.TypeValue,
        //          }).ToList();
        //        var copydata = needAddQuestionList.Clone();
        //        needAddQuestionList.ForEach(x =>
        //        {
        //            if (x.SystemParentId == null)
        //            {
        //                x.ParentId = null;
        //            }
        //            else
        //            {
        //                x.ParentId = copydata.FirstOrDefault(y => y.ReadingQuestionSystemId == x.SystemParentId).Id;
        //            }
        //        });

        //        trialQuestionList.AddRange(needAddQuestionList);
        //    }
        //    await _readingQuestionTrialRepository.BatchDeleteNoTrackingAsync(x => trialCriterionIds.Contains(x.ReadingQuestionCriterionTrialId));
        //    await _readingQuestionCriterionTrialRepository.BatchUpdateNoTrackingAsync(x => trialCriterionIds.Contains(x.Id), x => new ReadingQuestionCriterionTrial()
        //    {
        //        IsEnable = systemCriterion.IsEnable,
        //        CriterionName = systemCriterion.CriterionName,
        //        ShowOrder = systemCriterion.ShowOrder,
        //        IsCompleteConfig = systemCriterion.IsCompleteConfig,

        //    });

        //    await _readingQuestionTrialRepository.AddRangeAsync(trialQuestionList);


        //    //
        //    await _readingQuestionTrialRepository.SaveChangesAsync();
        //}


        /// <summary>
        /// 验证是否要同步标准
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<NeedSynchronize> VerifyeCriterionNeedSynchronize(VerifyeCriterionNeedSynchronizeInDto inDto)
        {


            #region 验证阅片工具配置
            var trialCriterion = await _readingQuestionCriterionTrialRepository.Where(x => x.Id == inDto.TrialReadingCriterionId).FirstNotNullAsync();

            var toolList = await _readingQuestionTrialRepository.Where(x => x.ReadingQuestionCriterionTrialId == inDto.TrialReadingCriterionId).Where(x => x.ImageTool != string.Empty).Select(x => x.ImageTool).ToListAsync();

            var tabletoolList = await _readingTableQuestionTrialRepository.Where(x => x.ReadingQuestionTrial.ReadingQuestionCriterionTrialId == inDto.TrialReadingCriterionId).Where(x => x.ImageTool != string.Empty).Select(x => x.ImageTool).ToListAsync();

            toolList.AddRange(tabletoolList);

            toolList = toolList.Distinct().ToList();

            var alltool = trialCriterion.ReadingToolList.Union(trialCriterion.SegmentToolList).ToList();

            if (tabletoolList.Except(alltool).Count() > 0)
            {
                //---问题的阅片工具不在标准配置的阅片工具列表中
                throw new BusinessValidationFailedException(_localizer["TrialConfig_TableToolNotInStdTool"]);
            }
            #endregion

            if (trialCriterion == null)
            {
                return NeedSynchronize.NotNeed;
            }
            if (trialCriterion.ReadingQuestionCriterionSystemId != null)
            {
                var systemCriterion = await _readingQuestionCriterionSystemRepository.Where(x => x.Id == trialCriterion.ReadingQuestionCriterionSystemId).FirstNotNullAsync();
                if (systemCriterion.ConfirmTime > trialCriterion.SynchronizeTime)
                {

                    var systemQuestionList = await _readingQuestionSystemRepository.Where(x => x.IsJudgeQuestion && x.ReadingQuestionCriterionSystemId == trialCriterion.ReadingQuestionCriterionSystemId).ToListAsync();
                    var trialQuestionList = await _readingQuestionTrialRepository.Where(x => x.IsJudgeQuestion && x.ReadingQuestionCriterionTrialId == trialCriterion.Id).ToListAsync();
                    if (systemQuestionList.Count != trialQuestionList.Count)
                    {
                        return NeedSynchronize.JudgeNotEqual;
                    }


                    foreach (var item in trialQuestionList)
                    {
                        var systemQuestion = systemQuestionList.Where(x => x.Id == (item.ReadingQuestionSystemId ?? default(Guid))).FirstOrDefault();
                        if (systemQuestion == null)
                        {
                            return NeedSynchronize.JudgeNotEqual;
                        }


                        if (systemQuestion.TypeValue != item.TypeValue)
                        {
                            return NeedSynchronize.JudgeNotEqual;
                        }
                    }


                    return NeedSynchronize.Need;

                }
                else
                {
                    return NeedSynchronize.NotNeed;
                }

            }
            else
            {
                return NeedSynchronize.NotNeed;
            }
        }


        /// <summary>
        /// 添加系统数据到项目里面
        /// </summary>
        /// <returns></returns>  
        [NonDynamicMethod]
        private async Task AddSystemDataToTrila(Guid trialId)
        {
            var trialUsrSystemIds = _readingQuestionCriterionTrialRepository.Where(x => x.TrialId == trialId && x.ReadingQuestionCriterionSystemId != null)
                .Select(x => x.ReadingQuestionCriterionSystemId);
            var trialCriterionNames = _readingQuestionCriterionTrialRepository.Where(x => x.TrialId == trialId)
                .Select(x => x.CriterionName);
            List<ReadingQuestionCriterionTrial> needAddCriterionList = await _readingQuestionCriterionSystemRepository.Where(x => !trialUsrSystemIds.Contains(x.Id) && x.IsEnable && !trialCriterionNames.Contains(x.CriterionName)).ProjectTo<ReadingQuestionCriterionTrial>(_mapper.ConfigurationProvider).ToListAsync();

            List<ReadingQuestionTrial> needAddQuestionList = new List<ReadingQuestionTrial>();
            needAddCriterionList.ForEach(x =>
            {
                //x.IsEnable = false;
                x.TrialId = trialId;
                x.ReadingQuestionCriterionSystemId = x.Id;
                x.Id = NewId.NextGuid();
                // 同步问题暂时注释
                //List<ReadingQuestionTrial> readingQuestionTrialList = new List<ReadingQuestionTrial>();
                //SetChildParentQuestion(criterion.Id, trialId, systemQuestionList, readingQuestionTrialList);
                //needAddQuestionList.AddRange(readingQuestionTrialList);
            });
            await _readingQuestionCriterionTrialRepository.AddRangeAsync(needAddCriterionList);
            await _readingQuestionTrialRepository.AddRangeAsync(needAddQuestionList);
            await _readingQuestionTrialRepository.SaveChangesAsync();
        }

        ///// <summary>
        ///// 设置父子关系
        ///// </summary>
        ///// <param name="ReadingQuestionCriterionTrialId">项目标准ID</param>
        ///// <param name="trialId">项目Id</param>
        ///// <param name="systemQuesitonList">系统问题</param>
        ///// <param name="needQuestionList">需要添加list</param>
        //private void SetChildParentQuestion(Guid ReadingQuestionCriterionTrialId, Guid trialId, List<ReadingQuestionSystem> systemQuesitonList, List<ReadingQuestionTrial> needQuestionList)
        //{
        //    var parentIdIsNullList = systemQuesitonList.Where(x => x.ParentId == null).ToList();
        //    parentIdIsNullList.ForEach(x =>
        //    {
        //        var quesiton = x.Clone();
        //        var oldId = quesiton.Id;
        //        var newId = NewId.NextGuid();
        //        needQuestionList.Add(new ReadingQuestionTrial()
        //        {
        //            Id = newId,
        //            ShowOrder = quesiton.ShowOrder,
        //            IsEnable = quesiton.IsEnable,
        //            IsRequired = quesiton.IsRequired,
        //            ParentTriggerValue = quesiton.ParentTriggerValue,
        //            QuestionName = quesiton.QuestionName,
        //            ReadingQuestionCriterionTrialId = ReadingQuestionCriterionTrialId,
        //            ReadingQuestionSystemId = quesiton.Id,
        //            SystemParentId = quesiton.ParentId,
        //            TrialId = trialId,
        //            AnswerGroup = string.Empty,
        //            Type = quesiton.Type,
        //            GroupName = quesiton.GroupName,
        //            IsJudgeQuestion = quesiton.IsJudgeQuestion,
        //            Remark = quesiton.Remark,
        //            TypeValue = quesiton.TypeValue,
        //        });

        //        CreateQuestionRelation(ReadingQuestionCriterionTrialId, trialId, oldId, newId, systemQuesitonList, needQuestionList);
        //    });
        //}

        ///// <summary>
        ///// 递归处理父子关系
        ///// </summary>
        ///// <param name="ReadingQuestionCriterionTrialId"></param>
        ///// <param name="trialId"></param>
        ///// <param name="oldParentId"></param>
        ///// <param name="newParentId"></param>
        ///// <param name="systemQuesitonList"></param>
        ///// <param name="needQuestionList"></param>
        //private void CreateQuestionRelation(Guid ReadingQuestionCriterionTrialId, Guid trialId, Guid oldParentId, Guid newParentId, List<ReadingQuestionSystem> systemQuesitonList, List<ReadingQuestionTrial> needQuestionList)
        //{
        //    var childList = systemQuesitonList.Where(x => x.ParentId == oldParentId).ToList();
        //    childList.ForEach(x =>
        //    {
        //        var quesiton = x.Clone();
        //        var oldId = quesiton.Id;
        //        var newId = NewId.NextGuid();
        //        needQuestionList.Add(new ReadingQuestionTrial()
        //        {
        //            Id = newId,
        //            ShowOrder = quesiton.ShowOrder,
        //            IsEnable = quesiton.IsEnable,
        //            IsRequired = quesiton.IsRequired,
        //            ParentId = newParentId,
        //            SystemParentId = quesiton.ParentId,
        //            ReadingQuestionSystemId = x.Id,
        //            AnswerGroup = string.Empty,
        //            ParentTriggerValue = quesiton.ParentTriggerValue,
        //            QuestionName = quesiton.QuestionName,
        //            ReadingQuestionCriterionTrialId = ReadingQuestionCriterionTrialId,
        //            TrialId = trialId,
        //            GroupName = quesiton.GroupName,
        //            Type = quesiton.Type,
        //            IsJudgeQuestion = quesiton.IsJudgeQuestion,
        //            Remark = quesiton.Remark,
        //            TypeValue = quesiton.TypeValue,
        //        });

        //        CreateQuestionRelation(ReadingQuestionCriterionTrialId, trialId, oldId, newId, systemQuesitonList, needQuestionList);
        //    });

        //}


        #region 废弃

        ///// <summary>
        ///// 新增修改系统问题标准
        ///// </summary>
        ///// <param name="indto"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public async Task<IResponseOutput> AddOrUpdateReadingQuestionCriterionSystem(AddOrUpdateReadingQuestionCriterionSystemInDto indto)
        //{
        //    var entity = await _readingQuestionCriterionSystemRepository.InsertOrUpdateAsync(indto, true);
        //    return ResponseOutput.Ok(entity.Id.ToString());
        //}


        ///// <summary>
        ///// 设置系统标准被禁用
        ///// </summary>
        ///// <returns></returns>
        //[NonDynamicMethod]
        //public async Task<IResponseOutput> SetSystemCriterionDisable(Guid dictionaryId, Guid? parentId)
        //{
        //    // 判断是否是阅片
        //    if (await _dictionaryRepository.AnyAsync(x => x.Id == parentId && x.Code == "ReadingStandard"))
        //    {
        //        // 判断当前阅片是否在项目里面存在
        //        var systemCriterion = await _readingQuestionCriterionSystemRepository.FirstOrDefaultAsync(x => x.CriterionId == dictionaryId);
        //        if (systemCriterion != null)
        //        {
        //            var trialCriterionIds = await _readingQuestionCriterionTrialRepository.Where(x => x.ReadingQuestionCriterionSystemId == systemCriterion.Id).Select(x=>x.ReadingQuestionCriterionSystemId).ToListAsync();
        //            await _readingQuestionCriterionTrialRepository.BatchDeleteNoTrackingAsync(x => x.ReadingQuestionCriterionSystemId == systemCriterion.Id);
        //            await _readingQuestionTrialRepository.BatchDeleteNoTrackingAsync(x => trialCriterionIds.Contains(x.ReadingQuestionCriterionTrialId));
        //            return ResponseOutput.Ok();
        //        }
        //    }

        //    return ResponseOutput.Ok();
        //}

        ///// <summary>
        ///// 添加系统问题标准
        ///// </summary>
        ///// <returns></returns>
        //[NonDynamicMethod]
        //private async Task AddSystemQuestionCriterion()
        //{
        //    var useSystemQuestionCriterionIds = _readingQuestionCriterionSystemRepository.Select(x => x.CriterionId);
        //    var dictionaryParentId =await _dictionaryRepository.Where(x => x.Code == "ReadingStandard").Select(x => x.Id).FirstOrDefaultAsync();
        //    var criterionList = await _dictionaryRepository.Where(x => x.ParentId == dictionaryParentId && !useSystemQuestionCriterionIds.Contains(x.Id))
        //        .Select(x => new CriterionList()
        //        {
        //            Id = x.Id,
        //            Value = x.Value,
        //            ShowOrder=x.ShowOrder,
        //        }).ToListAsync();
        //    List<ReadingQuestionCriterionSystem> needAddCriterionList = new List<ReadingQuestionCriterionSystem>();
        //    criterionList.ForEach(x =>
        //    {
        //        needAddCriterionList.Add(new ReadingQuestionCriterionSystem()
        //        {
        //            CriterionId = x.Id,
        //            ShowOrder=x.ShowOrder,
        //            CriterionName = x.Value,
        //            IsEnable = false,
        //        });
        //    });
        //   await  _readingQuestionCriterionSystemRepository.AddRangeAsync(needAddCriterionList);
        //   await _readingQuestionCriterionSystemRepository.SaveChangesAsync();
        //}


        ///// <summary>
        ///// 获取预览问题信息
        ///// </summary>
        ///// <param name="inDto"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public async Task<List<GetTrialReadingQuestionOutDto>> GetPreviewTheQuestion(GetPreviewTheQuestionInDto inDto)
        //{
        //    var trialQuestionQuery = from trialQuestion in _readingQuestionTrialRepository.Where(x=>x.ReadingQuestionCriterionTrialId== inDto.Id)
        //                    select new GetTrialReadingQuestionOutDto()
        //                    {
        //                        ReadingQuestionTrialId = trialQuestion.Id,
        //                        ReadingQuestionCriterionTrialId = trialQuestion.ReadingQuestionCriterionTrialId,
        //                        TrialId = trialQuestion.TrialId,
        //                        Type = trialQuestion.Type,
        //                        ParentTriggerValue = trialQuestion.ParentTriggerValue,
        //                        GroupName = trialQuestion.GroupName,
        //                        QuestionName = trialQuestion.QuestionName,
        //                        IsRequired = trialQuestion.IsRequired,
        //                        ShowOrder = trialQuestion.ShowOrder,
        //                        ParentId = trialQuestion.ParentId,
        //                        TypeValue = trialQuestion.TypeValue,
        //                        Answer = string.Empty
        //                    };
        //    var qusetionList = await trialQuestionQuery.OrderBy(x => x.ShowOrder).ToListAsync();
        //    List<GetTrialReadingQuestionOutDto> readingQuestionList = qusetionList.Where(x => x.ParentId == null).ToList();
        //    readingQuestionList.ForEach(x =>
        //    {
        //        _readingImageTaskService.FindChildQuestion(x, qusetionList);
        //    });

        //    return readingQuestionList;
        //}

        ///// <summary>
        ///// 设置项目标准是否生效
        ///// </summary>
        ///// <param name="inDto"></param>
        ///// <returns></returns>
        //public async Task<IResponseOutput> SetTrialReadingQuestionCriterionIsIsEnable(SetSystemReadingQuestionCriterionIsIsEnable inDto)
        //{
        //    await _readingQuestionCriterionTrialRepository.UpdatePartialFromQueryAsync(inDto.Id, x => new ReadingQuestionCriterionTrial()
        //    {
        //        IsEnable = inDto.IsEnable
        //    });

        //    var result = await _readingQuestionCriterionTrialRepository.SaveChangesAsync();

        //    return ResponseOutput.Ok(result);
        //}

        #endregion


        /// <summary>
        /// 根据项目问题id获取项目问题信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ReadingQuestionTrialView> GetReadingQuestionTrialById(Guid id)
        {
            var result = await _readingQuestionTrialRepository.Where(x => x.Id == id).ProjectTo<ReadingQuestionTrialView>(_mapper.ConfigurationProvider).FirstNotNullAsync();
            return result;
        }

        /// <summary>
        /// 根据项目表格问题id获取项目表格问题信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ReadingTableQuestionTrialView> GetReadingTableQuestionTrialById(Guid id)
        {
            var result = await _readingTableQuestionTrialRepository.Where(x => x.Id == id).ProjectTo<ReadingTableQuestionTrialView>(_mapper.ConfigurationProvider).FirstNotNullAsync();
            return result;
        }
    }
}
