//--------------------------------------------------------------------
//     此代码由T4模板自动生成  byzhouhang 20210918
//	   生成时间 2023-06-15 15:06:06 
//     对此文件的更改可能会导致不正确的行为，并且如果重新生成代码，这些更改将会丢失。
//--------------------------------------------------------------------

using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.Service.Reading.Dto;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infra.EFCore.Common;
using MassTransit;
using Microsoft.AspNetCore.Mvc;

namespace IRaCIS.Core.Application.Service
{
    /// <summary>
    /// 临床数据问题
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Reading")]
    public class ClinicalQuestionService(IRepository<TrialClinicalQuestion> _trialClinicalQuestionRepository,
        IRepository<SystemClinicalQuestion> _systemClinicalQuestionRepository,
        IRepository<SystemClinicalTableQuestion> _systemClinicalTableQuestionRepository,
        IRepository<TrialClinicalTableQuestion> _trialClinicalTableQuestionRepository, IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService, IClinicalQuestionService
    {


        /// <summary>
        /// 获取问题计算关系 
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<GetTrialClinicalQuestionCalculateRelationOutDto>> GetTrialClinicalQuestionCalculateRelation(GetTrialClinicalQuestionCalculateRelationInDto inDto)
        {

            var result = await _trialClinicalQuestionRepository.Where(x => x.TrialClinicalId == inDto.TrialClinicalId)
                   .Where(x => x.ClinicalQuestionType == "number")
                   .Where(x => x.CustomCalculateMark != null && x.CustomCalculateMark > ClinicalCalculateMark.None)
                      .Select(x => new GetTrialClinicalQuestionCalculateRelationOutDto()
                      {
                          QuestionId = x.Id,
                          DigitPlaces=x.DigitPlaces,
                          QuestionName = x.QuestionName,
                          CustomCalculateMark = x.CustomCalculateMark,
                          CalculateQuestionList = x.CalculateQuestionList,
                      }).ToListAsync();
            result = result.Where(x => x.CalculateQuestionList.Count() > 0).ToList();
            return result;
        }

        /// <summary>
        /// 获取计算问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<GetClinicalCalculateQuestionsOutDto>> GetClinicalCalculateQuestions(GetClinicalCalculateQuestionsInDto inDto)
        {
            var result = await _trialClinicalQuestionRepository

         .Where(x => x.TrialClinicalId == inDto.TrialClinicalId)
          .WhereIf(!inDto.ClinicalQuestionType.IsNullOrEmpty(), x => x.ClinicalQuestionType == inDto.ClinicalQuestionType)
         .OrderBy(x => x.ShowOrder)
         .Select(x => new GetClinicalCalculateQuestionsOutDto
         ()
         {
             QuestionId = x.Id,
             QuestionName = x.QuestionName.LanguageName(x.QuestionEnName, _userInfo.IsEn_Us)

         }).ToListAsync();

            var tablequestion = await _trialClinicalTableQuestionRepository.Where(x => x.TrialClinicalId == inDto.TrialClinicalId && x.ClinicalTableQuestionType == "number").Select(x =>
                   new
                   {
                       TableQuestionId = x.Id,
                       QuestionId = x.QuestionId,
                       QuestionName = x.QuestionName.LanguageName(x.QuestionEnName, _userInfo.IsEn_Us)
                   }).ToListAsync();


            result.ForEach(x =>
            {
                x.TableQuestions = tablequestion.Where(y => x.QuestionId == y.QuestionId).Select(y => new CalculateQuestion()
                {

                    QuestionId = y.QuestionId,
                    QuestionName = y.QuestionName

                }).ToList();
            });

            return result;
        }

        /// <summary>
        /// 获取系统临床数据预览
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<(List<ClinicalQuestionPreviewDto>, bool)> GetSystemClinicalQuestionPreview(GetSystemClinicalQuestionPreviewDto inDto)
        {
            var questions = await _systemClinicalQuestionRepository.Where(x => x.SystemClinicalId == inDto.SystemClinicalId)
                .ProjectTo<ClinicalQuestionPreviewDto>(_mapper.ConfigurationProvider).OrderBy(x => x.ShowOrder).ToListAsync();

            if (_userInfo.IsEn_Us)
            {
                questions.ForEach(x =>
                {
                    x.GroupName = x.GroupEnName;
                    x.QuestionName = x.QuestionEnName;
                });
            }
            var tableQuestions = await _systemClinicalTableQuestionRepository.Where(x => x.SystemClinicalId == inDto.SystemClinicalId)
                .ProjectTo<ClinicalTablePreviewDto>(_mapper.ConfigurationProvider).OrderBy(x => x.ShowOrder).ToListAsync();


            if (_userInfo.IsEn_Us)
            {
                tableQuestions.ForEach(x =>
                {
                    x.QuestionName = x.QuestionEnName;
                });
            }
            questions.ForEach(x => x.CreateTime = null);
            var result = questions.Where(x => x.ClinicalQuestionType == ReadingQestionType.Group).ToList();

            result.ForEach(x =>
            {
                FindChildQuestion(x, questions, tableQuestions, new List<ClinicalFormQuestionAnswer>(), new List<ClinicalFormTableQuestionAnswer>());
            });

            return (result, true);
        }


        /// <summary>
        /// 获取项目临床数据预览
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<(List<ClinicalQuestionPreviewDto>, bool)> GetTrialClinicalQuestionPreview(GetTrialClinicalQuestionPreviewDto inDto)
        {
            var questions = await _trialClinicalQuestionRepository.Where(x => x.TrialClinicalId == inDto.TrialClinicalId)
                .ProjectTo<ClinicalQuestionPreviewDto>(_mapper.ConfigurationProvider).OrderBy(x => x.ShowOrder).ToListAsync();

            if (_userInfo.IsEn_Us)
            {
                questions.ForEach(x =>
                {
                    x.GroupName = x.GroupEnName;
                    x.QuestionName = x.QuestionEnName;
                });
            }


            var tableQuestions = await _trialClinicalTableQuestionRepository.Where(x => x.TrialClinicalId == inDto.TrialClinicalId)
                .ProjectTo<ClinicalTablePreviewDto>(_mapper.ConfigurationProvider).OrderBy(x => x.ShowOrder).ToListAsync();

            if (_userInfo.IsEn_Us)
            {
                tableQuestions.ForEach(x =>
                {
                    x.QuestionName = x.QuestionEnName;
                });
            }

            questions.ForEach(x => x.CreateTime = null);
            var result = questions.Where(x => x.ClinicalQuestionType == ReadingQestionType.Group).OrderBy(x => x.ShowOrder).ToList();

            result.ForEach(x =>
            {
                FindChildQuestion(x, questions, tableQuestions, new List<ClinicalFormQuestionAnswer>(), new List<ClinicalFormTableQuestionAnswer>());
            });

            return (result, true);
        }



        /// <summary>
        /// 获取子元素
        /// </summary>
        /// <param name="item"></param>
        /// <param name="questions"></param>
        /// <param name="tableQuestions"></param>
        /// <param name="answers"></param>
        /// <param name="tableAnswers"></param>
        public void FindChildQuestion(ClinicalQuestionPreviewDto item, List<ClinicalQuestionPreviewDto> questions, List<ClinicalTablePreviewDto> tableQuestions, List<ClinicalFormQuestionAnswer> answers, List<ClinicalFormTableQuestionAnswer> tableAnswers)
        {
            item.Childrens = questions.Where(x => (x.ParentId == item.Id) || (x.GroupId == item.Id && x.ParentId == null)).OrderBy(x => x.ShowOrder).ToList();

            item.RelationQuestions = questions.Where(x => x.RelevanceId == item.Id).ToList();

            item.Answer = answers.Where(x => x.QuestionId == item.Id).Select(x => x.Answer).FirstOrDefault() ?? string.Empty;

            var tableIndexs = tableAnswers.Where(x => x.QuestionId == item.Id).Select(x => x.RowIndex).Distinct().OrderBy(x => x).ToList();

            item.TableAnswer = new List<Dictionary<Guid, string>>();

            tableIndexs.ForEach(x =>
            {
                item.TableAnswer.Add(tableAnswers.Where(y => y.RowIndex == x).ToDictionary(y => y.TableQuestionId, y => y.Answer));


            });


            item.TableQuestions = tableQuestions.Where(x => x.QuestionId == item.Id).OrderBy(x => x.ShowOrder).OrderBy(x => x.ShowOrder).ToList();

            item.RelationQuestions.ForEach(x =>
            {
                FindChildQuestion(x, questions, tableQuestions, answers, tableAnswers);
            });

            item.Childrens.ForEach(x =>
            {
                FindChildQuestion(x, questions, tableQuestions, answers, tableAnswers);
            });
        }

        #region 项目问题

        /// <summary>
        /// 获取项目临床问题
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<TrialClinicalQuestionDto>> GetTrialClinicalQuestionList(TrialClinicalQuestionQuery inQuery)
        {

            var trialClinicalQuestionQueryable = _trialClinicalQuestionRepository.Where(x => x.TrialClinicalId == inQuery.TrialClinicalId)
                .WhereIf(!inQuery.QuestionName.IsNullOrEmpty(), x => x.QuestionName.Contains(inQuery.QuestionName) || x.QuestionEnName.Contains(inQuery.QuestionName))
             .ProjectTo<TrialClinicalQuestionDto>(_mapper.ConfigurationProvider);
            var pageList = await trialClinicalQuestionQueryable
            .ToPagedListAsync(inQuery, nameof(TrialClinicalQuestion.ShowOrder));
            return pageList;
        }


        /// <summary>
        /// 新增或者修改项目临床问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> AddOrUpdateTrialClinicalQuestion(TrialClinicalQuestionDto inDto)
        {
            if (inDto.IsVerify)
            {
                if (await _trialClinicalQuestionRepository.AnyAsync(x => x.TrialClinicalId == inDto.TrialClinicalId && x.Id != inDto.Id && x.QuestionName == inDto.QuestionName))
                {
                    return ResponseOutput.NotOk(_localizer["ClinicalQuestion_Repeat"], string.Empty, ApiResponseCodeEnum.NeedTips);
                }

            }


            if (await _trialClinicalQuestionRepository.AnyAsync(x => x.TrialClinicalId == inDto.TrialClinicalId && x.Id != inDto.Id && x.ShowOrder == inDto.ShowOrder))
            {
                return ResponseOutput.NotOk("问题序号存在重复！");
            }

            if (await _trialClinicalQuestionRepository.AnyAsync(x => x.TrialClinicalId == inDto.TrialClinicalId && x.Id != inDto.Id && x.IsCheckDate == inDto.IsCheckDate && inDto.IsCheckDate))
            {
                return ResponseOutput.NotOk("已经添加过类型为检查日期的问题！");
            }

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

        }

        /// <summary>
        /// 删除项目临床数据问题
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("{id:guid}")]
        public async Task<IResponseOutput> DeleteTrialClinicalQuestion(Guid id)
        {
            var success = await _trialClinicalQuestionRepository.DeleteFromQueryAsync(t => t.Id == id, true);
            return ResponseOutput.Ok();
        }

        /// <summary>
        /// 获取项目问题分组
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<TrialClinicalQuestionDto>> GetTrialClinicalGroupQuestionList(GetTrialGroupDto inDto)
        {
            return await _trialClinicalQuestionRepository.Where(x => x.TrialClinicalId == inDto.TrialClinicalId && x.ClinicalQuestionType == "group")
                .ProjectTo<TrialClinicalQuestionDto>(_mapper.ConfigurationProvider).ToListAsync();
        }

        /// <summary>
        /// 获取项目标准其他问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<TrialClinicalQuestionDto>> GetTrialClinicalOtherQuestionList(GetTrialGroupDto inDto)
        {
            var types = new List<string>()
            {
                "select","radio"
            };
            return await _trialClinicalQuestionRepository.Where(x => x.TrialClinicalId == inDto.TrialClinicalId && types.Contains(x.ClinicalQuestionType))
              .ProjectTo<TrialClinicalQuestionDto>(_mapper.ConfigurationProvider).ToListAsync();
        }

        #endregion


        #region 系统问题

        /// <summary>
        /// 获取系统临床问题
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<SystemClinicalQuestionDto>> GetSystemClinicalQuestionList(SystemClinicalQuestionQuery inQuery)
        {

            var systemClinicalQuestionQueryable = _systemClinicalQuestionRepository
                .Where(x => x.SystemClinicalId == inQuery.SystemClinicalId)
                .WhereIf(!inQuery.QuestionName.IsNullOrEmpty(), x => x.QuestionName.Contains(inQuery.QuestionName) || x.QuestionEnName.Contains(inQuery.QuestionName))
             .ProjectTo<SystemClinicalQuestionDto>(_mapper.ConfigurationProvider);
            var pageList = await systemClinicalQuestionQueryable
            .ToPagedListAsync(inQuery, nameof(SystemClinicalQuestion.ShowOrder));
            return pageList;
        }


        /// <summary>
        /// 新增或者修改系统临床问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> AddOrUpdateSystemClinicalQuestion(SystemClinicalQuestionDto inDto)
        {

            if (inDto.IsVerify)
            {
                if (await _systemClinicalQuestionRepository.AnyAsync(x => x.SystemClinicalId == inDto.SystemClinicalId && x.Id != inDto.Id && x.QuestionName == inDto.QuestionName))
                {
                    return ResponseOutput.NotOk(_localizer["ClinicalQuestion_Repeat"], string.Empty, ApiResponseCodeEnum.NeedTips);
                }
            }


            if (await _systemClinicalQuestionRepository.AnyAsync(x => x.SystemClinicalId == inDto.SystemClinicalId && x.Id != inDto.Id && x.ShowOrder == inDto.ShowOrder))
            {
                return ResponseOutput.NotOk("问题序号存在重复！");
            }
            if (await _systemClinicalQuestionRepository.AnyAsync(x => x.SystemClinicalId == inDto.SystemClinicalId && x.Id != inDto.Id && x.IsCheckDate == inDto.IsCheckDate && inDto.IsCheckDate))
            {
                return ResponseOutput.NotOk("已经添加过类型为检查日期的问题！");
            }
            var entity = await _systemClinicalQuestionRepository.InsertOrUpdateAsync(inDto, true);
            return ResponseOutput.Ok(entity.Id.ToString());

        }


        /// <summary>
        /// 删除系统临床数据问题
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("{id:guid}")]
        public async Task<IResponseOutput> DeleteSystemClinicalQuestion(Guid id)
        {
            var success = await _systemClinicalQuestionRepository.DeleteFromQueryAsync(t => t.Id == id, true);
            return ResponseOutput.Ok();
        }


        /// <summary>
        /// 获取系统问题分组
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<SystemClinicalQuestionDto>> GetSystemClinicalGroupQuestionList(GetSystemGroupDto inDto)
        {
            return await _systemClinicalQuestionRepository.Where(x => x.SystemClinicalId == inDto.SystemClinicalId && x.ClinicalQuestionType == "group")
                .ProjectTo<SystemClinicalQuestionDto>(_mapper.ConfigurationProvider).ToListAsync();
        }


        /// <summary>
        /// 获取系统其他问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<SystemClinicalQuestionDto>> GetSystemClinicalOtherQuestionList(GetSystemGroupDto inDto)
        {
            var types = new List<string>()
            {
                "select","radio"
            };
            return await _systemClinicalQuestionRepository.Where(x => x.SystemClinicalId == inDto.SystemClinicalId && types.Contains(x.ClinicalQuestionType))
                .ProjectTo<SystemClinicalQuestionDto>(_mapper.ConfigurationProvider).ToListAsync();
        }


        #endregion

        #region 系统表格问题

        /// <summary>
        /// 获取系统表格问题
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<SystemClinicalTableQuestionDto>> GetSystemClinicalTableQuestionList(SystemClinicalTableQuestionQuery inQuery)
        {

            var systemClinicalTableQuestionQueryable = _systemClinicalTableQuestionRepository
             .Where(x => x.QuestionId == inQuery.QuestionId)
             .ProjectTo<SystemClinicalTableQuestionDto>(_mapper.ConfigurationProvider);

            var pageList = await systemClinicalTableQuestionQueryable.ToPagedListAsync(inQuery, nameof(SystemClinicalTableQuestion.ShowOrder));

            return pageList;
        }


        /// <summary>
        /// 新增或修改系统表格问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> AddOrUpdateSystemClinicalTableQuestion(SystemClinicalTableQuestionDto inDto)
        {
            if (inDto.IsVerify)
            {
                if (await _systemClinicalTableQuestionRepository.AnyAsync(x => x.QuestionId == inDto.QuestionId && x.Id != inDto.Id && x.QuestionName == inDto.QuestionName))
                {
                    return ResponseOutput.NotOk(_localizer["ClinicalQuestion_Repeat"], string.Empty, ApiResponseCodeEnum.NeedTips);
                }
            }

            if (await _systemClinicalTableQuestionRepository.AnyAsync(x => x.QuestionId == inDto.QuestionId && x.Id != inDto.Id && x.ShowOrder == inDto.ShowOrder))
            {
                return ResponseOutput.NotOk("问题序号存在重复!");
            }

            var entity = await _systemClinicalTableQuestionRepository.InsertOrUpdateAsync(inDto, true);

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

        }

        /// <summary>
        /// 删除系统表格问题
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("{id:guid}")]
        public async Task<IResponseOutput> DeleteSystemClinicalTableQuestion(Guid id)
        {
            var success = await _systemClinicalTableQuestionRepository.DeleteFromQueryAsync(t => t.Id == id, true);
            return ResponseOutput.Ok();
        }

        /// <summary>
        /// 获取系统其他表格问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<SystemClinicalTableQuestionDto>> GetSystemClinicalOtherTableQuestionList(GetClinicalOtherTableQuestionListInDto inDto)
        {
            var types = new List<string>()
            {
                "select","radio"
            };
            return await _systemClinicalTableQuestionRepository.Where(x => x.QuestionId == inDto.QuestionId && types.Contains(x.ClinicalTableQuestionType))
                .Where(x => x.Id != inDto.TableQuestionId)
                .ProjectTo<SystemClinicalTableQuestionDto>(_mapper.ConfigurationProvider).ToListAsync();
        }
        #endregion


        #region 项目表格问题


        /// <summary>
        /// 获取项目其他表格问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<TrialClinicalTableQuestionDto>> GetTrialClinicalOtherTableQuestionList(GetClinicalOtherTableQuestionListInDto inDto)
        {
            var types = new List<string>()
            {
                "select","radio"
            };
            return await _trialClinicalTableQuestionRepository.Where(x => x.QuestionId == inDto.QuestionId && types.Contains(x.ClinicalTableQuestionType))
                .Where(x => x.Id != inDto.TableQuestionId)
                .ProjectTo<TrialClinicalTableQuestionDto>(_mapper.ConfigurationProvider).ToListAsync();
        }

        /// <summary>
        /// 获取项目表格问题
        /// </summary>
        /// <param name="inQuery"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<TrialClinicalTableQuestionDto>> GetTrialClinicalTableQuestionList(TrialClinicalTableQuestionQuery inQuery)
        {

            var trialClinicalTableQuestionQueryable = _trialClinicalTableQuestionRepository
             .Where(x => x.QuestionId == inQuery.QuestionId)
             .ProjectTo<TrialClinicalTableQuestionDto>(_mapper.ConfigurationProvider);

            var pageList = await trialClinicalTableQuestionQueryable.ToPagedListAsync(inQuery, nameof(TrialClinicalTableQuestion.ShowOrder));

            return pageList;
        }


        /// <summary>
        /// 新增或修改项目表格问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IResponseOutput> AddOrUpdateTrialClinicalTableQuestion(TrialClinicalTableQuestionDto inDto)
        {
            if (inDto.IsVerify)
            {
                if (await _trialClinicalTableQuestionRepository.AnyAsync(x => x.QuestionId == inDto.QuestionId && x.Id != inDto.Id && x.QuestionName == inDto.QuestionName))
                {
                    return ResponseOutput.NotOk(_localizer["ClinicalQuestion_Repeat"], string.Empty, ApiResponseCodeEnum.NeedTips);
                }
            }

            if (await _trialClinicalTableQuestionRepository.AnyAsync(x => x.QuestionId == inDto.QuestionId && x.Id != inDto.Id && x.ShowOrder == inDto.ShowOrder))
            {
                return ResponseOutput.NotOk("问题序号存在重复!");
            }
            var entity = await _trialClinicalTableQuestionRepository.InsertOrUpdateAsync(inDto, true);

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

        }

        /// <summary>
        /// 删除项目表格问题
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("{id:guid}")]
        public async Task<IResponseOutput> DeleteTrialClinicalTableQuestion(Guid id)
        {
            var success = await _trialClinicalTableQuestionRepository.DeleteFromQueryAsync(t => t.Id == id, true);
            return ResponseOutput.Ok();
        }
        #endregion


        #region 同步系统问题

        /// <summary>
        /// 同步系统问题
        /// </summary>
        /// <param name="inDto"></param>
        /// <returns></returns>
        public async Task SynchronizationQuestion(List<SynchronizationQuestionDto> inDto)
        {
            var trialClinicalId = inDto.Select(x => x.TrialClinicalId).ToList();

            var systemClinicalId = inDto.Select(x => x.SystemClinicalId).ToList();
            var questionRelationList = await _trialClinicalQuestionRepository.Where(x => trialClinicalId.Contains(x.TrialClinicalId)).Select(x => new QuestionDic()
            {
                SystemQuestionId = x.SystemClinicalQuestionId ?? default(Guid),
                TrialQuestionId = x.Id,
                TrialClinicalId = x.TrialClinicalId,
            }).ToListAsync();

            var tableQuestionRelationList = await _trialClinicalTableQuestionRepository.Where(x => trialClinicalId.Contains(x.TrialClinicalId)).Select(x => new QuestionDic()
            {
                SystemQuestionId = x.SystemTableQuestionId ?? default(Guid),
                TrialQuestionId = x.Id,
                TrialClinicalId = x.TrialClinicalId,
            }).ToListAsync();

            var newTrialQuestionAll = await _systemClinicalQuestionRepository.Where(x => systemClinicalId.Contains(x.SystemClinicalId))
                  .ProjectTo<TrialClinicalQuestionSynchronize>(_mapper.ConfigurationProvider).ToListAsync();

            var newTrialTableQuestionAll = await _systemClinicalTableQuestionRepository.Where(x => systemClinicalId.Contains(x.SystemClinicalId))
                .ProjectTo<TrialClinicalTableQuestionSynchronize>(_mapper.ConfigurationProvider).ToListAsync();


            List<TrialClinicalQuestion> addTrialDataList = new List<TrialClinicalQuestion>();
            List<TrialClinicalTableQuestion> addTrialTableList = new List<TrialClinicalTableQuestion>();
            foreach (var item in inDto)
            {
                var questionRelation = questionRelationList.Where(x => x.TrialClinicalId == item.TrialClinicalId).ToDictionary(
                    x => x.SystemQuestionId,
                    x => x.TrialQuestionId
                    );

                var newTrialQuestionList = newTrialQuestionAll.Where(x => x.SystemClinicalId == item.SystemClinicalId).ToList();
                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.TrialClinicalId = item.TrialClinicalId;
                });

                var copyNewQuestionList = newTrialQuestionList.Clone();
                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)];
                    }
                    addTrialDataList.Add(question);
                };



                var tableQuestionRelation = tableQuestionRelationList.Where(x => x.TrialClinicalId == item.TrialClinicalId).ToDictionary(
                 x => x.SystemQuestionId,
                 x => x.TrialQuestionId
                 );

                var newTrialTableQuestionList = newTrialTableQuestionAll.Where(x => x.SystemClinicalId == item.SystemClinicalId)
                   .ToList();


                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;
                    }

                    if (x.RelevanceId != null)
                    {
                        x.RelevanceId = questionRelation[x.RelevanceId ?? default(Guid)];
                    }
                });

                foreach (var x in newTrialTableQuestionList)
                {
                    var tableQuestion = x.Clone();
                    tableQuestion.TrialClinicalId = item.TrialClinicalId;

                    tableQuestion.QuestionId = copyNewQuestionList.Where(y => y.SystemClinicalQuestionId == x.QuestionId).Select(y => y.Id).FirstOrDefault();


                    addTrialTableList.Add(tableQuestion);
                }
            }


            await _trialClinicalQuestionRepository.BatchDeleteNoTrackingAsync(x => trialClinicalId.Contains(x.TrialClinicalId));
            await _trialClinicalQuestionRepository.AddRangeAsync(addTrialDataList);
            await _trialClinicalTableQuestionRepository.BatchDeleteNoTrackingAsync(x => trialClinicalId.Contains(x.TrialClinicalId));
            await _trialClinicalTableQuestionRepository.AddRangeAsync(addTrialTableList);
            await _trialClinicalQuestionRepository.SaveChangesAsync();
        }


        #endregion

    }
}
