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

namespace IRaCIS.Core.Application.Service.RC
{


    [ApiExplorerSettings(GroupName = "Reading")]
    public class ReadingQuestionService : BaseService
    {

        private readonly IRepository<ReadingQuestionCriterionSystem> _readingQuestionCriterionSystemRepository;
        private readonly IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository;
        private readonly IRepository<ReadingQuestionTrial> _readingQuestionTrialRepository;
        private readonly IRepository<ReadingTaskQuestionAnswer> _readingTaskQuestionAnswer;
        private readonly IRepository<ReadingCriterionPage> _readingCriterionPageRepository;
        private readonly IRepository<ReadingCriterionDictionary> _readingCriterionDictionaryRepository;
        private readonly IRepository<VisitTask> _visitTaskRepository;
        private readonly IRepository<SystemCriterionDictionaryCode> _systemCriterionDictionaryCodeRepository;
        private readonly IRepository<ReadingTableQuestionAnswer> _readingTableQuestionAnswerRepository;
        private readonly IRepository<ReadingTableAnswerRowInfo> _readingTableAnswerRowInfoRepository;

        private readonly IRepository<ReadingTableQuestionTrial> _readingTableQuestionTrialRepository;

        public ReadingQuestionService(
            IRepository<ReadingQuestionCriterionSystem> readingQuestionCriterionSystemRepository,
            IRepository<ReadingQuestionCriterionTrial> readingQuestionCriterionTrialRepository,
            IRepository<ReadingQuestionTrial> readingQuestionTrialRepository,
               IRepository<ReadingCriterionDictionary> readingCriterionDictionaryRepository,
              IRepository<VisitTask> visitTaskRepository,
                 IRepository<SystemCriterionDictionaryCode> systemCriterionDictionaryCodeRepository,
                IRepository<ReadingTableQuestionTrial> readingTableQuestionTrialRepository,
               IRepository<ReadingTableQuestionAnswer> readingTableQuestionAnswerRepository,
                 IRepository<ReadingTableAnswerRowInfo> readingTableAnswerRowInfoRepository,
            IRepository<ReadingTaskQuestionAnswer> readingTaskQuestionAnswer,
             IRepository<ReadingCriterionPage> readingCriterionPageRepository)
        {
            this._readingQuestionCriterionSystemRepository = readingQuestionCriterionSystemRepository;
            this._readingQuestionCriterionTrialRepository = readingQuestionCriterionTrialRepository;
            this._readingQuestionTrialRepository = readingQuestionTrialRepository;
            this._readingTableQuestionTrialRepository = readingTableQuestionTrialRepository;
            this._readingCriterionPageRepository = readingCriterionPageRepository;
            this._readingCriterionDictionaryRepository = readingCriterionDictionaryRepository;
            this._visitTaskRepository = visitTaskRepository;
            this._systemCriterionDictionaryCodeRepository = systemCriterionDictionaryCodeRepository;
            this._readingTableQuestionAnswerRepository = readingTableQuestionAnswerRepository;
            this._readingTableAnswerRowInfoRepository = readingTableAnswerRowInfoRepository;
            this._readingTaskQuestionAnswer = readingTaskQuestionAnswer;
        }


        /// <summary>
        /// 删除系统标准字典Code
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> DeleteSystemCriterionDictionary(DeleteSystemCriterionDictionaryIndto inDto)
        {
          var criterionDictionaryCode=  await _systemCriterionDictionaryCodeRepository.Where(x => x.Id == inDto.Id).FirstNotNullAsync();

            await _readingCriterionDictionaryRepository.BatchDeleteNoTrackingAsync(x => x.ParentCode == criterionDictionaryCode.Code && x.CriterionId == criterionDictionaryCode.SystemCriterionId);

            await _systemCriterionDictionaryCodeRepository.DeleteFromQueryAsync(inDto.Id);
            await _systemCriterionDictionaryCodeRepository.SaveChangesAsync();

            return ResponseOutput.Ok();
        }


        /// <summary>
        /// 添加系统标准字典Code
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> AddSystemCriterionDictionaryCode(AddSystemCriterionDictionaryCodeInDto inDto)
        {

            var codes=  await _systemCriterionDictionaryCodeRepository.Where(x => x.SystemCriterionId == inDto.SystemCriterionId).Select(x => x.Code).ToListAsync();

            inDto.CodeList=  inDto.CodeList.Except(codes).ToList();

            

            await _systemCriterionDictionaryCodeRepository.AddRangeAsync(inDto.CodeList.Select(x=> new SystemCriterionDictionaryCode()
            {
                SystemCriterionId = inDto.SystemCriterionId,
                Code = x
            }).ToList());

            await _systemCriterionDictionaryCodeRepository.SaveChangesAsync();

            return ResponseOutput.Ok();
        }

        /// <summary>
        /// 重置项目标准的重置状态
        /// </summary>
        /// <param name="trialReadingCriterionId">项目标准Id</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> ResetTrialCriterionAsyncState(Guid trialReadingCriterionId)
        {
            await _readingQuestionCriterionTrialRepository.BatchUpdateNoTrackingAsync(x => x.Id == trialReadingCriterionId, x => new ReadingQuestionCriterionTrial
            {
                SynchronizeOriginalTime = null,
                SynchronizeTime = DateTime.Now.AddYears(-20),
                IsSigned=false,
                ReadingInfoSignTime=null,

            });


            return ResponseOutput.Ok();
        }

        /// <summary>
        /// 设置系统全局阅片阅片信息
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        [UnitOfWork]
        public async Task<IResponseOutput> SetSystemGlobalInfo(SetSystemGlobalInfoInDto inDto)
        {

            await _readingCriterionDictionaryRepository.BatchDeleteNoTrackingAsync(x => x.CriterionId == inDto.SystemCriterionId && x.ParentCode == ReadingCommon.CriterionDictionary.GlobalAssess);

            await _readingCriterionDictionaryRepository.AddRangeAsync(inDto.DictionaryList.Select(x => new ReadingCriterionDictionary
            {
                CriterionId = inDto.SystemCriterionId,
                DictionaryId = x.DictionaryId,
                IsSystemCriterion = true,
                ParentCode = ReadingCommon.CriterionDictionary.GlobalAssess,
                IsBaseLineUse=x.IsBaseLineUse,
                IsFollowVisitUse=x.IsFollowVisitUse,
            }));

            await _readingQuestionCriterionSystemRepository.UpdatePartialFromQueryAsync(inDto.SystemCriterionId, x => new ReadingQuestionCriterionSystem()
            {
                IsMustGlobalReading = inDto.IsMustGlobalReading

            });

            var result = await _readingQuestionCriterionTrialRepository.SaveChangesAsync();

            return ResponseOutput.Ok(result);
        }

        /// <summary>
        /// 获取系统全局阅片信息
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<GetSystemGlobalInfoOutDto> GetSystemGlobalInfo(GetSystemOncologyInfoInDto inDto)
        {
            GetSystemGlobalInfoOutDto result = new GetSystemGlobalInfoOutDto()
            {
                IsMustGlobalReading = await _readingQuestionCriterionSystemRepository.Where(x => x.Id == inDto.SystemCriterionId).Select(x => x.IsMustGlobalReading).FirstOrDefaultAsync(),
                DictionaryList = await _readingCriterionDictionaryRepository.AsQueryable().Where(x => x.CriterionId == inDto.SystemCriterionId && x.ParentCode == ReadingCommon.CriterionDictionary.GlobalAssess)
              .ProjectTo<CriterionDictionaryInfo>(_mapper.ConfigurationProvider).OrderBy(x => x.ShowOrder).ToListAsync()

            };

            return result;
        }

        /// <summary>
        /// 获取系统肿瘤信息
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<GetSystemOncologyInfoOutDto> GetSystemOncologyInfo(GetSystemOncologyInfoInDto inDto)
        {

            GetSystemOncologyInfoOutDto result = new GetSystemOncologyInfoOutDto() {
                IsOncologyReading = await _readingQuestionCriterionSystemRepository.Where(x => x.Id == inDto.SystemCriterionId).Select(x => x.IsOncologyReading).FirstOrDefaultAsync(),
                DictionaryList = await _readingCriterionDictionaryRepository.AsQueryable().Where(x => x.CriterionId == inDto.SystemCriterionId && x.ParentCode == ReadingCommon.CriterionDictionary.OncologyAssess)
            .ProjectTo<CriterionDictionaryInfo>(_mapper.ConfigurationProvider).OrderBy(x => x.ShowOrder).ToListAsync()

            };

            return result;
        }

        /// <summary>
        /// 设置系统肿瘤学阅片信息
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        [UnitOfWork]
        public async Task<IResponseOutput> SetSystemOncologyInfo(SetSystemOncologyInfoInDto inDto)
        {

            await _readingCriterionDictionaryRepository.BatchDeleteNoTrackingAsync(x => x.CriterionId == inDto.SystemCriterionId && x.ParentCode == ReadingCommon.CriterionDictionary.OncologyAssess);

            await _readingCriterionDictionaryRepository.AddRangeAsync(inDto.DictionaryIds.Select(x => new ReadingCriterionDictionary
            {
                CriterionId = inDto.SystemCriterionId,
                DictionaryId = x,
                IsSystemCriterion = true,
                ParentCode = ReadingCommon.CriterionDictionary.OncologyAssess
            }));

            await _readingQuestionCriterionSystemRepository.UpdatePartialFromQueryAsync(inDto.SystemCriterionId, x => new ReadingQuestionCriterionSystem()
            {
                IsOncologyReading = inDto.IsOncologyReading

            });

            var result = await _readingQuestionCriterionTrialRepository.SaveChangesAsync();

            return ResponseOutput.Ok(result);
        }


        #region 系统标准
        /// <summary>
        /// 获取获取系统阅片标准下拉
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<GetSystemCriterionListOutDto>> GetSystemCriterionList()
        {
            List<GetSystemCriterionListOutDto> result = await _readingQuestionCriterionSystemRepository.Select(x => new GetSystemCriterionListOutDto()
            {

                CriterionId = x.Id,
                CriterionName = x.CriterionName,

            }).ToListAsync();

            return result;
        }

        /// <summary>
        /// 获取系统问题标准
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<ReadingQuestionCriterionSystemView>> GetReadingQuestionCriterionSystemList(ReadingQuestionCriterionSystemViewInDto inDto)
        {
            //await AddSystemQuestionCriterion();
            var query = _readingQuestionCriterionSystemRepository.AsQueryable()
                 .WhereIf(!inDto.CriterionName.IsNullOrEmpty(), x => x.CriterionName.Contains(inDto.CriterionName))
                 .ProjectTo<ReadingQuestionCriterionSystemView>(_mapper.ConfigurationProvider);

            return await query.ToPagedListAsync(inDto.PageIndex, inDto.PageSize, inDto.SortField.IsNullOrEmpty() ? nameof(ReadingQuestionCriterionSystemView.ShowOrder) : inDto.SortField,
             inDto.Asc);
        }

        /// <summary>
        /// 获取系统问题标准下拉
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<GetSystemCriterionSelectDto>> GetSystemCriterionSelectList()
        {
            var criterionList = await _readingQuestionCriterionSystemRepository.AsQueryable()
                .OrderBy(x => x.ShowOrder)
               .Select(x => new GetSystemCriterionSelectDto()
               {
                   Id = x.Id,
                   CriterionName = x.CriterionName,

               }).ToListAsync();
            return criterionList;
        }

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

            if (indto.Id != null)
            {
                await _readingQuestionCriterionTrialRepository.BatchUpdateNoTrackingAsync(x => x.ReadingQuestionCriterionSystemId == indto.Id, x => new ReadingQuestionCriterionTrial()
                {
                    CriterionName = indto.CriterionName,
                    CriterionType = indto.CriterionType,

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

        /// <summary>
        /// 删除系统问题标准
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id:guid}")]
        public async Task<IResponseOutput> DeleteReadingQuestionCriterionSystem(Guid id)
        {


            if (await _readingQuestionCriterionTrialRepository.AnyAsync(x => x.IsConfirm && x.ReadingQuestionCriterionSystemId == id))
            {
                throw new BusinessValidationFailedException("当前标准被引用过了，不可以删除");
            }

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



        /// <summary>
        /// 设置系统问题标准是否完成配置
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> SetSystemReadingQuestionCriterionIsCompleteConfig(SetSystemReadingQuestionCriterionIsIsCompleteConfig inDto)
        {

            if (!inDto.IsCompleteConfig)
            {
                var trialCriterionIds = await _readingQuestionCriterionTrialRepository.Where(x => x.ReadingQuestionCriterionSystemId == inDto.Id).Select(x => x.Id).ToListAsync();
                if (await _readingTaskQuestionAnswer.AnyAsync(x => trialCriterionIds.Contains(x.ReadingQuestionCriterionTrialId)))
                {
                    return ResponseOutput.NotOk("此标准在项目里面已被使用,操作失败");
                }
            }

            var systemCriterion = await _readingQuestionCriterionSystemRepository.Where(x => x.Id == inDto.Id).AsNoTracking().FirstOrDefaultAsync();

            var confirmTime = systemCriterion.ConfirmTime;

            if (inDto.IsCompleteConfig)
            {
                confirmTime = DateTime.Now;
            }

            await _readingQuestionCriterionSystemRepository.UpdatePartialFromQueryAsync(inDto.Id, x => new ReadingQuestionCriterionSystem()
            {
                IsCompleteConfig = inDto.IsCompleteConfig,
                ConfirmTime = confirmTime,
            });

            if (inDto.IsCompleteConfig)
            {
                //await SynchronizeSystemCriterion(inDto.Id);
            }
            else
            {
                await _readingQuestionCriterionTrialRepository.BatchUpdateNoTrackingAsync(x => x.ReadingQuestionCriterionSystemId == inDto.Id, x => new ReadingQuestionCriterionTrial()
                {
                    IsCompleteConfig = inDto.IsCompleteConfig
                });
            }
            var result = await _readingQuestionCriterionSystemRepository.SaveChangesAsync();

            return ResponseOutput.Ok(result);
        }


        #endregion

        #region 项目标准

        /// <summary>
        /// 获取项目裁判信息
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<GetTrialJudgyInfoOutDto> GetTrialJudgyInfo(GetTrialJudgyInfoInDto inDto)
        {
            GetTrialJudgyInfoOutDto result = await _readingQuestionCriterionTrialRepository.Where(x => x.Id == inDto.TrialReadingCriterionId).Select(x => new GetTrialJudgyInfoOutDto
            {
                TrialId = x.TrialId,
                IsReadingTaskViewInOrder = x.IsReadingTaskViewInOrder,
                ArbitrationRule = x.ArbitrationRule,
                IsArbitrationReading = x.IsArbitrationReading

            }).FirstNotNullAsync();

            return result;
        }

        /// <summary>
        /// 新增修改项目问题标准（项目）
        /// </summary>
        /// <param name="indto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> AddOrUpdateReadingQuestionCriterionTrial(AddOrUpdateReadingQuestionCriterionTrialInDto indto)
        {

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



        /// <summary>
        /// 设置项目标准是否完成配置
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> SetTrialReadingQuestionCriterionIsIsCompleteConfig(SetSystemReadingQuestionCriterionIsIsCompleteConfig inDto)
        {
            await _readingQuestionCriterionTrialRepository.UpdatePartialFromQueryAsync(inDto.Id, x => new ReadingQuestionCriterionTrial()
            {
                IsCompleteConfig = inDto.IsCompleteConfig
            });

            var result = await _readingQuestionCriterionTrialRepository.SaveChangesAsync();

            return ResponseOutput.Ok(result);
        }

        /// <summary>
        /// 获取项目问题标准（项目）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<ReadingQuestionCriterionTrialView>> GetReadingQuestionCriterionTrialList(ReadingQuestionCriterionTrialViewInDto inDto)
        {
            await AddSystemDataToTrila(inDto.TrialId);
            var query = _readingQuestionCriterionTrialRepository.AsQueryable()
                .Where(x => x.TrialId == inDto.TrialId)
                .Where(x => (x.ReadingQuestionCriterionSystemId != null && x.IsEnable) || x.ReadingQuestionCriterionSystemId == null)
                 .WhereIf(!inDto.CriterionName.IsNullOrEmpty(), x => x.CriterionName.Contains(inDto.CriterionName))

                 .ProjectTo<ReadingQuestionCriterionTrialView>(_mapper.ConfigurationProvider);
            return await query.ToPagedListAsync(inDto.PageIndex, inDto.PageSize, inDto.SortField.IsNullOrEmpty() ? nameof(ReadingQuestionCriterionTrialView.ShowOrder) : inDto.SortField,
             inDto.Asc);
        }

        /// <summary>
        /// 删除项目问题标准（项目）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id:guid}")]
        public async Task<IResponseOutput> DeleteReadingQuestionCriterionTrial(Guid id)
        {
            await _readingQuestionCriterionTrialRepository.DeleteFromQueryAsync(t => t.Id == id);
            var success = await _readingQuestionCriterionTrialRepository.SaveChangesAsync();
            return ResponseOutput.Result(success);
        }

        /// <summary>
        /// 设置项目裁判信息
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> SetTrialJudgyInfo(SetTrialJudgyInfoInDto inDto)
        {

            var trialCriterion = await _readingQuestionCriterionTrialRepository.Where(x => x.TrialId == inDto.TrialId && x.Id == inDto.TrialReadingCriterionId).FirstOrDefaultAsync();

            var judgeCount = await _readingQuestionTrialRepository.Where(x => x.ReadingQuestionCriterionTrialId == trialCriterion.Id && x.IsJudgeQuestion)
                  .WhereIf(trialCriterion.FormType == FormType.SinglePage, x => x.ReadingCriterionPageId == null)
                 .WhereIf(trialCriterion.FormType == FormType.MultiplePage, x => x.ReadingCriterionPageId != null).CountAsync();

            if (judgeCount == 0 && (inDto.ArbitrationRule == ArbitrationRule.Visit || inDto.ArbitrationRule == ArbitrationRule.Reading))
            {
                throw new BusinessValidationFailedException("无裁判问题却有仲裁对象,操作失败");
            }
            await _readingQuestionCriterionTrialRepository.UpdatePartialFromQueryAsync(inDto.TrialReadingCriterionId, x => new ReadingQuestionCriterionTrial()
            {
                ArbitrationRule = inDto.ArbitrationRule,
                //IsArbitrationReading = inDto.IsArbitrationReading,
            });

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


        #endregion

        #region 项目阅片标准问题分页

        /// <summary>
        /// 新增修改项目标准分页
        /// </summary>
        /// <param name="addOrEditReadingCriterionPage"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> AddOrUpdateReadingCriterionPage(ReadingCriterionPageAddOrEdit addOrEditReadingCriterionPage)
        {

            var entity = await _readingCriterionPageRepository.InsertOrUpdateAsync(addOrEditReadingCriterionPage, true);
            return ResponseOutput.Ok(entity.Id.ToString());

        }

        /// <summary>
        /// 删除标准分页
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete("{Id:guid}")]
        public async Task<IResponseOutput> DeleteReadingCriterionPage(Guid Id)
        {
            var success = await _readingCriterionPageRepository.DeleteFromQueryAsync(t => t.Id == Id, true);
            return ResponseOutput.Ok();
        }


        #endregion



        #region 全局评估类型  肿瘤学评估类型

        /// <summary>
        /// 修改是否是随访使用
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> SetDictionaryFollowVisitUse(SetDictionaryFollowVisitUseInDto inDto)
        {
            await _readingCriterionDictionaryRepository.UpdatePartialFromQueryAsync(inDto.Id, x => new ReadingCriterionDictionary()
            {
                IsFollowVisitUse = inDto.IsFollowVisitUse
            });

            await _readingCriterionDictionaryRepository.SaveChangesAsync();

            return ResponseOutput.Ok(true);
        }


        /// <summary>
        /// 修改是否是基线使用
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> SetDictionaryBaseLineUse(SetDictionaryBaseLineUseInDto inDto)
        {
            await _readingCriterionDictionaryRepository.UpdatePartialFromQueryAsync(inDto.Id, x => new ReadingCriterionDictionary()
            {
                IsBaseLineUse = inDto.IsBaseLineUse
            });

            await _readingCriterionDictionaryRepository.SaveChangesAsync();

            return ResponseOutput.Ok(true);
        }

        /// <summary>
        /// 获取标准字典
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<CriterionDictionaryInfo>> GetAssessType(GetAssessTypeInDto inDto)
        {
            List<CriterionDictionaryInfo> result = await _readingCriterionDictionaryRepository.Where(x => x.CriterionId == inDto.CriterionId
            )
                 .WhereIf(!inDto.ParentCode.IsNullOrEmpty(), x => x.ParentCode ==inDto.ParentCode)
                 .ProjectTo<CriterionDictionaryInfo>(_mapper.ConfigurationProvider).OrderBy(x => x.ParentCode).ThenBy(x => x.ShowOrder).ToListAsync();
            return result;
        }

        /// <summary>
        /// 设置标准字典
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> SetCriterionDictionary(SetCriterionDictionaryInDto inDto)
        {
            await _readingCriterionDictionaryRepository.BatchDeleteNoTrackingAsync(x => x.CriterionId == inDto.CriterionId && x.ParentCode == inDto.ParentCode);


            await _readingCriterionDictionaryRepository.AddRangeAsync(inDto.DictionaryIds.Select(x => new ReadingCriterionDictionary()
            {
                CriterionId = inDto.CriterionId,
                DictionaryId = x,
                IsSystemCriterion = true,
                ParentCode = inDto.ParentCode
            }));
          

            await _readingCriterionDictionaryRepository.SaveChangesAsync();

            return ResponseOutput.Ok(true);
        }

        /// <summary>
        /// 设置评估类型
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> SetAssessType(SetAssessTypeInDto inDto)
        {
            await _readingCriterionDictionaryRepository.BatchDeleteNoTrackingAsync(x => x.CriterionId == inDto.CriterionId && x.ParentCode == inDto.ParentCode);

            await _readingCriterionDictionaryRepository.AddRangeAsync(inDto.DictionaryList.Select(x => new ReadingCriterionDictionary()
            {
                CriterionId = inDto.CriterionId,
                DictionaryId = x.DictionaryId,
                IsBaseLineUse = x.IsBaseLineUse,
                IsFollowVisitUse = x.IsFollowVisitUse,
                IsSystemCriterion = true,
                ParentCode = inDto.ParentCode
            }));

            await _readingCriterionDictionaryRepository.SaveChangesAsync();

            return ResponseOutput.Ok(true);
        }

        #endregion

        /// <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();
        }

    }
}
