using IRaCIS.Core.Domain.Models;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using IRaCIS.Core.Infrastructure.Extention;
using MassTransit;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ZiggyCreatures.Caching.Fusion;
using static IRaCIS.Core.Domain.Share.StaticData;


namespace IRaCIS.Core.Infra.EFCore.Common
{
    public interface IAuditingData
    {

        Task InsertAddEntitys(List<EntityEntry> entitys);
    }
    public static class AuditOpt
    {
        public static readonly string Add = "Add";
        public static readonly string Update = "Update";
        public static readonly string Deleted = "Deleted";
    }

    /// <summary>
    /// 添加稽查稽查数据
    /// </summary>
    public class AuditingData : IAuditingData
    {

        /// <summary>
        /// 数据库对象o
        /// </summary>
        public IRaCISDBContext _dbContext { get; set; }

        /// <summary>
        /// 用户信息
        /// </summary>
        public IUserInfo _userInfo { get; set; }

        public IFusionCache _fusionCache { get; set; }


        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="userInfo"></param>
        public AuditingData(IRaCISDBContext dbContext, IUserInfo userInfo, IFusionCache fusionCache)
        {
            _dbContext = dbContext;
            _userInfo = userInfo;
            _userInfo.BatchId = _userInfo.BatchId == null ? NewId.NextGuid() : _userInfo.BatchId;
            _fusionCache = fusionCache;
        }



        /// <summary>
        /// 特殊删除
        /// </summary>
        private List<Type> NodeleteTableTypes
        {
            get
            {
                return new List<Type>()
                {
                   typeof(TrialUserRole),
                   typeof(TrialIdentityUser),
                   typeof(TrialSiteSurvey),
                   typeof(TrialSiteUserRole),
                   typeof(VisitStage),
                   typeof(TrialSite),
                   typeof(NoneDicomStudy),
                   typeof(NoneDicomStudyFile),
                   typeof(DicomInstance),
                   typeof(DicomSeries),
                   typeof(DicomStudy)

                };
            }
        }

        // 修改为删除
        private List<Type> UpdateIsDelete
        {
            get
            {
                return new List<Type>()
                {
                   typeof(TrialDocument)
                };
            }
        }

        /// <summary>
        /// 翻译单位
        /// </summary>
        /// <param name="answerType">答案类型</param>
        /// <param name="unit">单位</param>
        /// <param name="customUnit">自定义单位</param>
        /// <param name="unitDataList">单位字典</param>
        /// <param name="answer">答案</param>
        /// <returns></returns>
        public string Translationunit(string answerType, ValueUnit? unit, string customUnit, List<UnitData> unitDataList, string? answer)
        {
            if (answer == null || answer == string.Empty)
            {
                return string.Empty;
            }




            if (answerType == "upload")
            {
                return "❄❅❆❇❈❉❊" + answer;
            }

            var answerList = new List<string>() { };

            try
            {
                answerList = JsonConvert.DeserializeObject<List<string>>(answer);
            }
            catch (Exception)
            {

                answerList.Add(answer);
            }

            List<string> transList = new List<string>();
            foreach (var item in answerList)
            {
                if (unit == ValueUnit.Custom)
                {
                    transList.Add(item + string.Empty + customUnit);
                }
                else
                {
                    transList.Add(item + string.Empty + unitDataList.Where(y => y.Unit == unit).Select(x => x.UnitName).FirstIsNullReturnEmpty());
                }


            }

            return string.Join(",", transList);

        }
        public string GetEntityAuditOpt(EntityEntry entityEntry)
        {
            if (entityEntry.State == EntityState.Added)
            {
                return AuditOpt.Add;
            }
            else if (
               UpdateIsDelete.Contains(entityEntry.Entity.GetType())
                && entityEntry.State == EntityState.Modified
                && (bool)entityEntry.Entity.GetType().GetProperty(nameof(ISoftDelete.IsDeleted)).GetValue(entityEntry.Entity)

               )
            {
                return AuditOpt.Deleted;
            }

            else if (entityEntry.State == EntityState.Deleted ||
                      (entityEntry.State == EntityState.Modified
                       && typeof(ISoftDelete).IsAssignableFrom(entityEntry.Entity.GetType())
                       && (bool)entityEntry.Entity.GetType().GetProperty(nameof(ISoftDelete.IsDeleted)).GetValue(entityEntry.Entity)
                       && entityEntry.State == EntityState.Modified
                       && !NodeleteTableTypes.Contains(entityEntry.Entity.GetType())
                       )
                     )
            {
                return AuditOpt.Deleted;
            }
            else
            {
                return AuditOpt.Update;
            }
        }

        /// <summary>
        /// 插入Add的实体
        /// </summary>
        /// <param name="entitys"></param>
        public async Task InsertAddEntitys(List<EntityEntry> entitys)
        {

            // 项目
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(Trial)))
            {

                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as Trial;

                var extraIdentification = string.Empty;

                //阅片标准
                var criterionNameList = await _dbContext.ReadingQuestionCriterionTrial.Where(t => t.TrialId == entity.Id && t.IsConfirm).OrderBy(t => t.ShowOrder).Select(t => t.CriterionName).ToListAsync();

                var memoryCriterionNameList = entitys.Where(x => x.Entity.GetType() == typeof(ReadingQuestionCriterionTrial)).Select(t => t.Entity as ReadingQuestionCriterionTrial)
                    .Where(t => t.TrialId == entity.Id && t.IsConfirm).OrderBy(t => t.ShowOrder).Select(t => t.CriterionName).ToList();

                //临床数据配置
                var clinicalDataSetNameList = await _dbContext.ClinicalDataTrialSet.Where(t => t.TrialId == entity.Id && t.IsConfirm).Select(t => _userInfo.IsEn_Us ? t.ClinicalDataSetEnName : t.ClinicalDataSetName).ToListAsync();

                var memoryClinicalDataSetNameList = entitys.Where(x => x.Entity.GetType() == typeof(ClinicalDataTrialSet)).Select(t => t.Entity as ClinicalDataTrialSet)
                    .Where(t => t.TrialId == entity.Id && t.IsConfirm).Select(t => _userInfo.IsEn_Us ? t.ClinicalDataSetEnName : t.ClinicalDataSetName).ToList();

                //项目字典TrialDictionary

                var memoryModalityIdList = entitys.Where(x => x.Entity.GetType() == typeof(TrialDictionary)).Select(t => t.Entity as TrialDictionary)
                       .Where(t => t.TrialId == entity.Id && t.KeyName == StaticData.Modality).Select(t => t.DictionaryId).ToList();

                var modalityList = _dbContext.Dictionary.Where(t => memoryModalityIdList.Contains(t.Id)).Select(t => _userInfo.IsEn_Us ? t.Value : t.ValueCN).ToList();


                Guid id = entity.Id;
                var oldentity = await _dbContext.Trial.Where(x => x.Id == id).Select(t => new
                {
                    t.IsTrialBasicLogicConfirmed,
                    t.IsTrialProcessConfirmed,
                    t.IsTrialUrgentConfirmed,
                    t.IsConfigureEmail,
                    t.IsTrialPACSConfirmed,
                }).FirstOrDefaultAsync();
                switch (_userInfo.RequestUrl)
                {
                    case "configTrialBasicInfo/ConfigTrialBasicInfoConfirm":
                        extraIdentification = $"/{oldentity.IsTrialBasicLogicConfirmed.ToString()}";
                        break;
                    case "configTrialBasicInfo/ConfigTrialProcessInfoConfirm":
                        extraIdentification = $"/{oldentity.IsTrialProcessConfirmed.ToString()}";
                        break;

                    case "configTrialBasicInfo/ConfigTrialUrgentInfoConfirm":
                        extraIdentification = $"/{oldentity.IsTrialUrgentConfirmed.ToString()}";
                        break;
                    case "configTrialBasicInfo/ConfigTrialPACSInfoConfirm":
                        extraIdentification = $"/{oldentity.IsTrialPACSConfirmed.ToString()}";
                        break;

                    case "TrialEmailNoticeConfig/setTrialEmail":

                        extraIdentification = oldentity.IsConfigureEmail ? "/EmailUpdate" : "/EmailSave";
                        break;
                    case "configTrialBasicInfo/TrialConfigSignatureConfirm":

                        if (entity.IsQCQuestionConfirmed == false)
                        {
                            extraIdentification = $"/ConfirmReset";
                        }
                        break;
                }

                //var trialDicomAE = await _dbContext.TrialDicomAE.Where(t => t.TrialId == entity.Id).FirstOrDefaultAsync();

                await InsertInspection<Trial>(item.Entity as Trial, type, x => new InspectionConvertDTO()
                {
                    TrialId = x.Id,

                    ExtraIndentification = extraIdentification,
                }, new
                {
                    ModalityListStr = string.Join(",", modalityList),
                    //TrialDicList = string.Join(",", trialDics)

                    //CalledAE = trialDicomAE?.CalledAE,
                    //IP = trialDicomAE?.IP,
                    //Port = trialDicomAE?.Port,
                    //IsTestOK = trialDicomAE?.IsTestOK,
                    ImageFormatListStr = string.Join("|", entity.ImageFormatList),
                    StudyNamesStr = string.Join("|", entity.StudyNameList.Where(x => x.IsChoose).Select(x => _userInfo.IsEn_Us ? x.EnName : x.Name)),

                    CriterionNames = string.Join(",", criterionNameList.Union(memoryCriterionNameList).Distinct()),

                    ClinicalDataSetNames = string.Join(",", clinicalDataSetNameList.Union(memoryClinicalDataSetNameList).Distinct().OrderBy(t => t)),


                });
            }


            // 阅片导入
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingImportFile)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ReadingImportFile;


                var visitTaskInfo = await _dbContext.VisitTask.Where(x => x.Id == entity.VisitTaskId).Include(x => x.DoctorUser).FirstOrDefaultAsync();

                await InsertInspection<ReadingImportFile>(entity, type, x => new InspectionConvertDTO()
                {
                    VisitTaskId = entity.VisitTaskId,
                    TrialReadingCriterionId = entity.TrialReadingCriterionId,
                    SubjectVisitId = entity.SubjectVisitId,
                    SubjectId = entity.SubjectId,
                    TrialId = entity.TrialId,
                    ObjectRelationParentId = entity.VisitTaskId

                });
            }

            #region 已修改

            #region 阅片单元配置

            //系统阅片标准
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingQuestionCriterionSystem)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ReadingQuestionCriterionSystem;


                var extraIdentification = string.Empty;

                if (_dbContext.Entry(entity).Property(t => t.IsMustGlobalReading).IsModified == true)
                {
                    extraIdentification = $"/IsGlobalReading";
                }

                if (_dbContext.Entry(entity).Property(t => t.IsOncologyReading).IsModified == true)
                {
                    extraIdentification = $"/IsOncologyReading";
                }

                await InsertInspection<ReadingQuestionCriterionSystem>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = /*type == AuditOpt.Update ? true :*/ false,
                    ExtraIndentification = extraIdentification

                });
            }
            //项目阅片标准
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingQuestionCriterionTrial)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ReadingQuestionCriterionTrial;

                var isDistinctionInterface = false;

                //设置项目配置 肿瘤学配置 和阅片标准配置
                if (_userInfo.RequestUrl == "TrialConfig/setOncologySet"

                    //现在废弃 没用
                    || _userInfo.RequestUrl == "TrialConfig/setTrialReadingCriterion"

                    //项目流程确认
                    || _userInfo.RequestUrl == "configTrialBasicInfo/ConfigTrialProcessInfoConfirm"

                     //确认医学审核问题
                     || _userInfo.RequestUrl == "ReadingMedicineQuestion/ConfirmReadingMedicineQuestion"

                   //阅片单元 保存阅片规则
                   || _userInfo.RequestUrl == "TrialConfig/setCriterionReadingInfo"

                   || _userInfo.RequestUrl == "configTrialBasicInfo/TrialReadingInfoSign")
                {
                    isDistinctionInterface = true;
                }


                //同步的数据 后面加"/Auto"  因为同步的地方可能会改 所以取反
                var extraIdentification = string.Empty;
                if (_userInfo.RequestUrl != "ReadingQuestion/addOrUpdateReadingQuestionCriterionTrial" && type == AuditOpt.Add)
                {
                    extraIdentification = "/Auto";
                }

                //保存肿瘤学配置哪里 强行要将 评估结果（中间字典表的多条数据）存到标准稽查上   

                var dicIdList = entitys.Where(x => x.Entity.GetType() == typeof(ReadingSystemCriterionDictionary)).Select(t => t.Entity as ReadingSystemCriterionDictionary).Where(t => t.CriterionId == entity.Id).Select(t => t.DictionaryId).ToList();

                var dicValueList = new List<string>();
                if (dicIdList.Count() == 0)
                {
                    dicValueList = await _dbContext.ReadingSystemCriterionDictionary.Where(t => t.CriterionId == entity.Id).Select(t => t.Dictionary.Value).ToListAsync();
                }
                else
                {
                    dicValueList = await _dbContext.Dictionary.Where(t => dicIdList.Contains(t.Id)).Select(t => t.Value).ToListAsync();
                }

                // 附加评估

                var addtionalAssesementList = await _dbContext.TrialCriterionAdditionalAssessmentType.Where(t => t.TrialReadingCriterionId == entity.Id && t.IsSelected != null)
                    .Select(t => new { t.AdditionalAssessmentType, t.IsSelected }).ToListAsync();


                var oncologyAssessIdsStr = string.Empty;
                var allList = new List<ReadingTrialCriterionDictionary>();

                if (entitys.Any(x => x.Entity.GetType() == typeof(ReadingTrialCriterionDictionary)))
                {
                    allList = entitys.Where(x => x.Entity.GetType() == typeof(ReadingTrialCriterionDictionary))
                       .Select(t => t.Entity as ReadingTrialCriterionDictionary).ToList().Where(x =>
                       x.CriterionId == entity.Id &&
                       x.ParentCode == ReadingCommon.CriterionDictionary.OncologyAssess).ToList();
                }
                else
                {
                    allList = await _dbContext.ReadingTrialCriterionDictionary.Where(x =>
                        x.CriterionId == entity.Id &&
                        x.ParentCode == ReadingCommon.CriterionDictionary.OncologyAssess).ToListAsync();
                }


                //查询出字典的Value  ValueCN  Des 保存
                var diclistOncologyAssess = allList.Select(t => t.DictionaryId).ToList();

                var selectList = await _dbContext.Dictionary.Where(x => diclistOncologyAssess.Contains(x.Id)).Select(t => t.ValueCN).ToListAsync();

                oncologyAssessIdsStr = string.Join(",", selectList);

                await InsertInspection<ReadingQuestionCriterionTrial>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = isDistinctionInterface,

                    TrialReadingCriterionId = entity.Id,

                    ObjectRelationParentId = x.TrialId,

                    ExtraIndentification = extraIdentification

                }, new
                {
                    OncologyAssessIdsStr = oncologyAssessIdsStr,

                    EvaluationResultTypes = dicValueList.Count > 0 ? string.Join(",", dicValueList) : string.Empty,
                    AdditionalAssessmentTypeList = addtionalAssesementList
                });
            }


            // PACS直连
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TrialSiteDicomAE)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as TrialSiteDicomAE;


                await InsertInspection<TrialSiteDicomAE>(entity, type, x => new InspectionConvertDTO()
                {
                    ObjectRelationParentId = entity.TrialSiteId,
                });
            }

            // PACS直连
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TrialDicomAE)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as TrialDicomAE;


                await InsertInspection<TrialDicomAE>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false
                });
            }

            //系统标准问题
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingQuestionSystem)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ReadingQuestionSystem;


                int? parentQuestionShowOrder = null;
                int? relavantQuestionShowOrder = null;

                if (entity.ParentId != null)
                {
                    parentQuestionShowOrder = await _dbContext.ReadingQuestionSystem.Where(t => t.Id == entity.ParentId).Select(t => t.ShowOrder).FirstOrDefaultAsync();

                }
                if (entity.RelevanceId != null)
                {
                    relavantQuestionShowOrder = await _dbContext.ReadingQuestionSystem.Where(t => t.Id == entity.RelevanceId).Select(t => t.ShowOrder).FirstOrDefaultAsync();

                }


                await InsertInspection<ReadingQuestionSystem>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false

                }, new { ParentQuestionShowOrder = parentQuestionShowOrder, RelavantQuestionShowOrder = relavantQuestionShowOrder });
            }
            //项目标准问题
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingQuestionTrial)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ReadingQuestionTrial;


                var isDistinctionInterface = false;
                var extraIdentification = string.Empty;

                //同步的数据 后面加"/Auto"  因为同步的地方可能会改 所以取反
                if (_userInfo.RequestUrl != "ReadingQuestion/addOrUpdateReadingQuestionTrial" && type == AuditOpt.Add)
                {
                    extraIdentification = "/Auto";
                }

                //重置仲裁规则

                var cloneEntity = entity.Clone();

                if (_userInfo.RequestUrl == "ReadingImageTask/setTrialCriterionJudgeQuestionAnswerGroup")
                {
                    isDistinctionInterface = true;

                    if (entity.JudgeType == JudgeTypeEnum.None)
                    {
                        extraIdentification = "/Reset";
                    }

                    //翻译  可能自己填写的 也有可能是从字典中获取的                 
                    if (entity.QuestionGenre == TableQuestionType.Dictionary && !string.IsNullOrWhiteSpace(entity.DictionaryCode))
                    {
                        var translateList = _dbContext.Dictionary.Where(t => t.Code == entity.DictionaryCode.Trim()).SelectMany(t => t.ChildList).Select(t => new { t.Code, t.Value, t.ValueCN }).ToList();

                        foreach (var translateItem in translateList)
                        {
                            cloneEntity.AnswerCombination = cloneEntity.AnswerCombination.Replace($"\"{translateItem.Code}\"", $"\"{translateItem.Value}\"");

                            cloneEntity.AnswerGroup = cloneEntity.AnswerGroup.Replace($"|{translateItem.Code}|", $"|{translateItem.Value}|");
                        }
                    }
                }

                int? parentQuestionShowOrder = null;
                int? relavantQuestionShowOrder = null;

                if (entity.ParentId != null)
                {
                    parentQuestionShowOrder = await _dbContext.ReadingQuestionSystem.Where(t => t.Id == entity.ParentId).Select(t => t.ShowOrder).FirstOrDefaultAsync();

                }
                if (entity.RelevanceId != null)
                {
                    relavantQuestionShowOrder = await _dbContext.ReadingQuestionSystem.Where(t => t.Id == entity.RelevanceId).Select(t => t.ShowOrder).FirstOrDefaultAsync();

                }


                await InsertInspection<ReadingQuestionTrial>(cloneEntity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = isDistinctionInterface,

                    TrialReadingCriterionId = entity.ReadingQuestionCriterionTrialId,

                    ObjectRelationParentId = x.TrialId,

                    ExtraIndentification = extraIdentification

                }, new
                {
                    ParentQuestionShowOrder = parentQuestionShowOrder,
                    OperatingTime = DateTime.Now,
                    RelavantQuestionShowOrder = relavantQuestionShowOrder
                });
            }

            //系统标准表格问题
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingTableQuestionSystem)))
            {

                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ReadingTableQuestionSystem;

                int? dependQuestionShowOrder = null;
                int? parentQuestionShowOrder = null;
                int? relavantQuestionShowOrder = null;

                if (entity.ParentId != null)
                {
                    parentQuestionShowOrder = await _dbContext.ReadingQuestionSystem.Where(t => t.Id == entity.ParentId).Select(t => t.ShowOrder).FirstOrDefaultAsync();

                }
                if (entity.RelevanceId != null)
                {
                    relavantQuestionShowOrder = await _dbContext.ReadingQuestionSystem.Where(t => t.Id == entity.RelevanceId).Select(t => t.ShowOrder).FirstOrDefaultAsync();

                }
                if (entity.DependParentId != null)
                {
                    dependQuestionShowOrder = await _dbContext.ReadingQuestionSystem.Where(t => t.Id == entity.DependParentId).Select(t => t.ShowOrder).FirstOrDefaultAsync();

                }


                await InsertInspection<ReadingTableQuestionSystem>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false

                }, new { ParentQuestionShowOrder = parentQuestionShowOrder, RelavantQuestionShowOrder = relavantQuestionShowOrder, DependQuestionShowOrder = dependQuestionShowOrder });
            }
            //项目标准表格问题
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingTableQuestionTrial)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ReadingTableQuestionTrial;

                //同步的数据 后面加"/Auto"  因为同步的地方可能会改 所以取反
                var extraIdentification = string.Empty;
                if (_userInfo.RequestUrl != "ReadingQuestion/addOrUpdateReadingTableQuestionTrial" && type == AuditOpt.Add)
                {
                    extraIdentification = "/Auto";
                }


                int? dependQuestionShowOrder = null;
                int? parentQuestionShowOrder = null;
                int? relavantQuestionShowOrder = null;

                if (entity.ParentId != null)
                {
                    parentQuestionShowOrder = await _dbContext.ReadingQuestionSystem.Where(t => t.Id == entity.ParentId).Select(t => t.ShowOrder).FirstOrDefaultAsync();

                }
                if (entity.RelevanceId != null)
                {
                    relavantQuestionShowOrder = await _dbContext.ReadingQuestionSystem.Where(t => t.Id == entity.RelevanceId).Select(t => t.ShowOrder).FirstOrDefaultAsync();

                }
                if (entity.DependParentId != null)
                {
                    dependQuestionShowOrder = await _dbContext.ReadingQuestionSystem.Where(t => t.Id == entity.DependParentId).Select(t => t.ShowOrder).FirstOrDefaultAsync();
                }



                await InsertInspection<ReadingTableQuestionTrial>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,

                    TrialId = x.TrialId,

                    TrialReadingCriterionId = entity.TrialCriterionId,

                    ObjectRelationParentId = x.TrialId,

                    ExtraIndentification = extraIdentification

                }, new { ParentQuestionShowOrder = parentQuestionShowOrder, RelavantQuestionShowOrder = relavantQuestionShowOrder, DependQuestionShowOrder = dependQuestionShowOrder });
            }


            //系统器官
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(OrganInfo)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as OrganInfo;


                await InsertInspection<OrganInfo>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,

                    ObjectRelationParentId = entity.SystemCriterionId


                });
            }

            //项目器官

            if (entitys.Any(x => x.Entity.GetType() == typeof(OrganTrialInfo)))
            {

                var organTrialEntityEnrtyList = entitys.Where(x => x.Entity.GetType() == typeof(OrganTrialInfo));

                var extraIdentification = string.Empty;

                //同步添加
                if (_userInfo.RequestUrl != "OrganInfo/batchAddTrialOrgan" && organTrialEntityEnrtyList.Any(t => GetEntityAuditOpt(t) == AuditOpt.Add))
                {
                    extraIdentification = "/Auto";



                    var list = organTrialEntityEnrtyList.Select(t => t.Entity as OrganTrialInfo);

                    var organIdList = list.Select(t => t.OrganInfoId).ToList();

                    var organList = await _dbContext.OrganInfo.Where(x => organIdList.Contains(x.Id)).ToListAsync();


                    var firstEntity = list.FirstOrDefault();

                    var cloneEntity = firstEntity.Clone();

                    //保证Id 唯一
                    cloneEntity.Id = IdentifierHelper.CreateGuid(firstEntity.TrialId.ToString(), firstEntity.TrialCriterionId.ToString());

                    await InsertInspection<OrganTrialInfo>(cloneEntity, AuditOpt.Add, x => new InspectionConvertDTO()
                    {
                        IsDistinctionInterface = false,

                        TrialReadingCriterionId = cloneEntity.TrialCriterionId,

                        ObjectRelationParentId = cloneEntity.TrialCriterionId,

                        ObjectRelationParentId2 = cloneEntity.OrganInfoId,

                        ExtraIndentification = extraIdentification

                    }, new
                    {
                        QuestionAnswerList = list.Join(organList, t => t.OrganInfoId, u => u.Id, (t, u) => u).OrderBy(t => t.ShowOrder).ToList(),
                    });

                }
                else
                {
                    //手动操作
                    foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(OrganTrialInfo)))
                    {
                        var type = GetEntityAuditOpt(item);

                        var entity = item.Entity as OrganTrialInfo;

                        await InsertInspection<OrganTrialInfo>(entity, type, x => new InspectionConvertDTO()
                        {
                            IsDistinctionInterface = false,

                            TrialReadingCriterionId = entity.TrialCriterionId,

                            ObjectRelationParentId = entity.TrialCriterionId,

                            ObjectRelationParentId2 = entity.OrganInfoId,

                            ExtraIndentification = extraIdentification

                        });
                    }
                }
            }



            // 项目  系统公用表
            //病灶管理  区分项目 还是系统的
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(CriterionNidusSystem)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as CriterionNidusSystem;


                await InsertInspection<CriterionNidusSystem>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,

                    ObjectRelationParentId = entity.CriterionId,

                });
            }

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(CriterionNidusTrial)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as CriterionNidusTrial;

                var extraIdentification = string.Empty;

                if (_userInfo.RequestUrl != "OrganInfo/addOrUpdateCriterionNidus" && type == AuditOpt.Add)
                {
                    extraIdentification = "/Auto";
                }




                await InsertInspection<CriterionNidusTrial>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,

                    ObjectRelationParentId = entity.CriterionId,

                    TrialReadingCriterionId = entity.CriterionId,

                    ExtraIndentification = extraIdentification


                });
            }


            //疗效评估

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TumorAssessment_RECIST1Point1)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as TumorAssessment_RECIST1Point1;


                await InsertInspection<TumorAssessment_RECIST1Point1>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,

                    //ObjectRelationParentId = entity.CriterionId

                });
            }


            // 项目  系统公用表
            //配置标准 病灶类型  自动计算标识  "LesionType", "QuestionType"
            if (entitys.Any(x => x.Entity.GetType() == typeof(ReadingSystemCriterionDictionary)))
            {

                var type = AuditOpt.Add;

                var allList = entitys.Where(x => x.Entity.GetType() == typeof(ReadingSystemCriterionDictionary)).Select(t => t.Entity as ReadingSystemCriterionDictionary).ToList();

                //查询出字典的Value  ValueCN  Des 保存
                var dicIdList = allList.Select(t => t.DictionaryId).ToList();

                var selectList = await _dbContext.Dictionary.Where(x => dicIdList.Contains(x.Id)).Select(t => new { t.Id, t.Value, t.ValueCN, t.Description, t.ShowOrder }).ToListAsync();


                foreach (var list in allList.GroupBy(t => t.ParentCode))
                {

                    var firstEntity = list.First();
                    var cloneEntity = list.First().Clone();


                    //保证Id 唯一
                    cloneEntity.Id = IdentifierHelper.CreateGuid(firstEntity.CriterionId.ToString(), firstEntity.ParentCode.ToString());


                    var extraIdentification = string.Empty;


                    extraIdentification = $"/{cloneEntity.ParentCode}";



                    await InsertInspection<ReadingSystemCriterionDictionary>(cloneEntity, type, x => new InspectionConvertDTO()
                    {

                        ObjectRelationParentId = x.CriterionId,

                        TrialReadingCriterionId = x.IsSystemCriterion == false ? x.CriterionId : null,

                        //不显示区分接口   通过是否是系统字典  以及字典Code 区分
                        IsDistinctionInterface = false,
                        ExtraIndentification = extraIdentification

                    },
                        new
                        {
                            SelectList = selectList.Join(list, t => t.Id, u => u.DictionaryId, (t, u) =>
                                                        new
                                                        {
                                                            Value = t.Value,
                                                            t.ValueCN,
                                                            t.Description,
                                                            t.ShowOrder,
                                                            u.IsBaseLineUse,
                                                            u.IsFollowVisitUse
                                                        }
                                                        ).OrderBy(t => t.ShowOrder).ToList()
                        });
                }



            }



            if (entitys.Any(x => x.Entity.GetType() == typeof(ReadingTrialCriterionDictionary)))
            {

                var type = AuditOpt.Add;

                var allList = entitys.Where(x => x.Entity.GetType() == typeof(ReadingTrialCriterionDictionary)).Select(t => t.Entity as ReadingTrialCriterionDictionary).ToList();

                //查询出字典的Value  ValueCN  Des 保存
                var dicIdList = allList.Select(t => t.DictionaryId).ToList();

                var selectList = await _dbContext.Dictionary.Where(x => dicIdList.Contains(x.Id)).Select(t => new
                {
                    t.Id,

                    Value = _userInfo.IsEn_Us ? t.Value : t.ValueCN,
                    t.ValueCN,
                    t.Description,
                    t.ShowOrder
                }).ToListAsync();


                foreach (var list in allList.GroupBy(t => t.ParentCode))
                {

                    var firstEntity = list.First();
                    var cloneEntity = list.First().Clone();


                    //保证Id 唯一
                    cloneEntity.Id = IdentifierHelper.CreateGuid(firstEntity.CriterionId.ToString(), firstEntity.ParentCode.ToString());


                    var extraIdentification = string.Empty;


                    extraIdentification = $"/{cloneEntity.ParentCode}/IsTrial";



                    await InsertInspection<ReadingTrialCriterionDictionary>(cloneEntity, type, x => new InspectionConvertDTO()
                    {

                        ObjectRelationParentId = x.CriterionId,

                        TrialReadingCriterionId = x.CriterionId,

                        //不显示区分接口   通过是否是系统字典  以及字典Code 区分
                        IsDistinctionInterface = false,
                        ExtraIndentification = extraIdentification

                    },
                        new
                        {
                            SelectList = selectList.Join(list, t => t.Id, u => u.DictionaryId, (t, u) =>
                                                        new
                                                        {
                                                            Value = _userInfo.IsEn_Us ? t.Value : t.ValueCN,
                                                            t.ValueCN,
                                                            t.Description,
                                                            t.ShowOrder,
                                                            u.IsBaseLineUse,
                                                            u.IsFollowVisitUse
                                                        }
                                                        ).OrderBy(t => t.ShowOrder).ToList()
                        });
                }



            }



            #endregion

            #region 文档相关



            // 系统文件签署  父层级未记录稽查（系统文档初始数据）
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(SystemDocConfirmedIdentityUser)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as SystemDocConfirmedIdentityUser;

                var extraIdentification = string.Empty;


                if (type == AuditOpt.Update)
                {
                    if (entity.IsDeleted == true)
                    {
                        extraIdentification = "/" + 2;
                    }
                    else
                    {
                        extraIdentification = "/" + 1;
                    }
                }


                var systemDocument = await _dbContext.SystemDocument.Where(x => x.Id == entity.SystemDocumentId).FirstOrDefaultAsync();
                await InsertInspection<SystemDocConfirmedIdentityUser>(entity, type, x => new InspectionConvertDTO()
                {
                    GeneralId = x.Id,
                    ExtraIndentification = extraIdentification,
                    ObjectRelationParentId = x.SystemDocumentId

                }, new
                {

                    FileTypeId = systemDocument.FileTypeId,
                    Name = systemDocument.Name,
                    UploadTime = systemDocument.CreateTime,

                    CreateUserName = _userInfo.UserName,
                    UserType = _userInfo.UserTypeShortName,
                    IsSigned = entity.ConfirmTime != null,      // 是否签署  添加了就是签署了
                });
            }

            // 项目文件签署
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TrialDocConfirmedIdentityUser)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as TrialDocConfirmedIdentityUser;

                var extraIdentification = string.Empty;


                if (type == AuditOpt.Update)
                {
                    if (entity.IsDeleted == true)
                    {
                        extraIdentification = "/" + 2;
                    }
                    else
                    {
                        extraIdentification = "/" + 1;
                    }
                }

                var trialDoc = await _dbContext.TrialDocument.Where(x => x.Id == entity.TrialDocumentId).FirstOrDefaultAsync();

                await InsertInspection<TrialDocConfirmedIdentityUser>(entity as TrialDocConfirmedIdentityUser, type, x => new InspectionConvertDTO()
                {
                    TrialId = trialDoc.TrialId,
                    ExtraIndentification = extraIdentification,

                    ObjectRelationParentId = x.TrialDocumentId
                }, new
                {

                    UploadTime = trialDoc.CreateTime,

                    CreateUserName = _userInfo.UserName,

                    UserType = _userInfo.UserTypeShortName,

                    IsSigned = entity.ConfirmTime != null
                });
            }


            //系统文件
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(SystemDocument)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as SystemDocument;

                List<Guid> needConfirmedUserTypeIdList = new List<Guid>();

                if (entity.NeedConfirmedUserTypeList == null)
                {
                    needConfirmedUserTypeIdList = await _dbContext.SystemDocNeedConfirmedUserType.Where(x => x.SystemDocumentId == entity.Id).Select(t => t.NeedConfirmUserTypeId).ToListAsync();
                }
                else
                {
                    needConfirmedUserTypeIdList = entity.NeedConfirmedUserTypeList.Select(t => t.NeedConfirmUserTypeId).ToList();
                }


                var userTypeNameList = await _dbContext.UserType.Where(x => needConfirmedUserTypeIdList.Contains(x.Id)).Select(x => x.UserTypeShortName).ToListAsync();
                var userTypeName = string.Join(",", userTypeNameList);
                await InsertInspection<SystemDocument>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false
                }, new
                {
                    NeedConfirmedUserType = userTypeName,
                });
            }

            // 项目文档
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TrialDocument)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as TrialDocument;

                List<Guid> needConfirmedUserTypeIdList = new List<Guid>();

                if (entity.NeedConfirmedUserTypeList == null)
                {
                    needConfirmedUserTypeIdList = await _dbContext.TrialDocNeedConfirmedUserType.Where(x => x.TrialDocumentId == entity.Id).Select(t => t.NeedConfirmUserTypeId).ToListAsync();
                }
                else
                {
                    needConfirmedUserTypeIdList = entity.NeedConfirmedUserTypeList.Select(t => t.NeedConfirmUserTypeId).ToList();
                }

                var usertypeNames = await _dbContext.UserType.Where(x => needConfirmedUserTypeIdList.Contains(x.Id)).Select(x => x.UserTypeShortName).ToListAsync();
                var usertypeName = string.Join(",", usertypeNames);
                var isDistinctionInterface = false;
                if (_userInfo.RequestUrl == "TrialDocument/publishTrialDocument")
                {
                    isDistinctionInterface = true;
                }
                await InsertInspection<TrialDocument>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = isDistinctionInterface,
                    ObjectRelationParentId = x.TrialId
                },
                new
                {
                    NeedConfirmedUserType = usertypeName,
                });


            }

            //项目标准自动发送邮件配置
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TrialEmailNoticeConfig)))
            {
                var type = GetEntityAuditOpt(item);

                var extraIdentification = string.Empty;

                var entity = item.Entity as TrialEmailNoticeConfig;

                //找到配置的用户
                var configUserTypeList = entitys.Where(x => x.Entity.GetType() == typeof(TrialEmailNoticeUser)).Select(t => t.Entity as TrialEmailNoticeUser)
                    .Where(t => t.TrialEmailNoticeConfigId == entity.Id).Select(t =>
                new { t.TrialEmailNoticeConfigId, t.EmailUserType, t.UserType }).ToList();



                await InsertInspection<TrialEmailNoticeConfig>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,
                    //ObjectRelationParentId = x.TrialReadingCriterionId,
                    ExtraIndentification = extraIdentification
                },
           new
           {
               ToUserTypes = configUserTypeList.Where(t => t.EmailUserType == EmailUserType.To).Select(t => t.UserType).ToList(),
               CopyUserTypes = configUserTypeList.Where(t => t.EmailUserType == EmailUserType.Copy).Select(t => t.UserType).ToList(),
           });


            }

            #endregion


            #region 热键  模板 个性化配置

            if (entitys.Any(x => x.Entity.GetType() == typeof(ShortcutKey)))
            {
                var type = AuditOpt.Add;

                var list = entitys.Where(x => x.Entity.GetType() == typeof(ShortcutKey)).Select(t => t.Entity as ShortcutKey);


                var firstEntity = list.FirstOrDefault();

                var cloneEntity = firstEntity.Clone();

                //保证Id 唯一
                cloneEntity.Id = IdentifierHelper.CreateGuid(firstEntity.UserId.ToString(), firstEntity.CreateUserId.ToString());

                await InsertInspection(cloneEntity, type, x => new InspectionConvertDTO()
                {

                    //byzhouhang
                    ObjectRelationParentId = x.UserId,

                    IsDistinctionInterface = false,
                }, new
                {
                    ShortcutKeyList = list,
                });
            }

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(UserWLTemplate)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as UserWLTemplate;

                var extraIdentification = string.Empty;


                await InsertInspection<UserWLTemplate>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,

                    ObjectRelationParentId = entity.UserId
                });
            }


            #endregion

            #region 附加评估

            // 是否参与附加评估记录表
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(SubjectCriteriaEvaluation)))
            {
                var type = GetEntityAuditOpt(item);

                //var extraIdentification = string.Empty;

                var entity = item.Entity as SubjectCriteriaEvaluation;


                await InsertInspection<SubjectCriteriaEvaluation>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,
                    ObjectRelationParentId = x.SubjectId,
                    ObjectRelationParentId2 = x.TrialReadingCriterionId,

                    TrialReadingCriterionId = x.TrialReadingCriterionId,
                });


            }

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(SubjectCriteriaEvaluationVisitFilter)))
            {
                var type = GetEntityAuditOpt(item);

                var extraIdentification = string.Empty;

                var entity = item.Entity as SubjectCriteriaEvaluationVisitFilter;


                if (type == AuditOpt.Add)
                {
                    if (entity.IsGeneratedTask)
                    {
                        extraIdentification = "/AutoGenerate";
                    }
                    else
                    {
                        extraIdentification = "/Add";
                    }
                }

                if (type == AuditOpt.Update)
                {

                    //手动生成任务

                    if (entity.IsGeneratedTask)
                    {
                        //Update
                        extraIdentification = "/ManualGenerate";
                    }


                    //回退接口
                    else if (_userInfo.RequestUrl == "SubjectCriteriaEvaluation/confirmBackCriteriaVisitTask")
                    {
                        extraIdentification = "/Back";
                    }
                    else
                    {
                        //筛选影像保存接口
                        //if (_userInfo.RequestUrl == "SubjectCriteriaEvaluation/batchAddSubjectCriteriaEvaluationVisitStudyFilter")
                        //{
                        extraIdentification = "/Update";
                        //}

                    }


                }






                await InsertInspection<SubjectCriteriaEvaluationVisitFilter>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,
                    IsSelfDefine = true,
                    ExtraIndentification = extraIdentification,
                    ObjectRelationParentId = x.SubjectVisitId,
                    ObjectRelationParentId2 = x.TrialReadingCriterionId,

                    TrialReadingCriterionId = x.TrialReadingCriterionId,
                });
            }

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(SubjectCriteriaEvaluationVisitStudyFilter)))
            {
                var type = GetEntityAuditOpt(item);

                var extraIdentification = string.Empty;

                var entity = item.Entity as SubjectCriteriaEvaluationVisitStudyFilter;

                if (entity.IsConfirmed == true)
                {
                    extraIdentification = "/Confirm";
                }
                else
                {
                    extraIdentification = "/Save";
                }

                await InsertInspection<SubjectCriteriaEvaluationVisitStudyFilter>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,
                    IsSelfDefine = true,

                    ExtraIndentification = extraIdentification,

                    ObjectRelationParentId = x.StudyId,
                    ObjectRelationParentId2 = x.SeriesId,//序列有的稽查没有记录，所以StudyId放前面

                    ObjectRelationParentId3 = x.TrialReadingCriterionId,

                    TrialReadingCriterionId = x.TrialReadingCriterionId,
                });
            }



            #endregion

            #region 医学审核



            //医学审核 问题答案
            if (entitys.Any(x => x.Entity.GetType() == typeof(ReadingMedicineQuestionAnswer)))
            {

                var type = AuditOpt.Add;

                var list = entitys.Where(x => x.Entity.GetType() == typeof(ReadingMedicineQuestionAnswer)).Select(t => t.Entity as ReadingMedicineQuestionAnswer);

                var questionIdList = list.Select(t => t.ReadingMedicineQuestionId).ToList();

                var questionNameList = await _dbContext.ReadingMedicineTrialQuestion.Where(x => questionIdList.Contains(x.Id)).Select(t => new { t.QuestionName, ReadingMedicineQuestionId = t.Id, t.ShowOrder }).ToListAsync();

                var firstEntity = list.FirstOrDefault();

                var cloneEntity = firstEntity.Clone();

                //保证Id 唯一
                cloneEntity.Id = IdentifierHelper.CreateGuid(firstEntity.VisitTaskId.ToString(), firstEntity.TaskMedicalReviewId.ToString());

                await InsertInspection(cloneEntity, type, x => new InspectionConvertDTO()
                {
                    VisitTaskId = x.VisitTaskId,

                    //byzhouhang
                    ObjectRelationParentId = x.TaskMedicalReviewId,

                    IsDistinctionInterface = false,
                }, new
                {
                    QuestionAnswerList = list.Join(questionNameList, t => t.ReadingMedicineQuestionId, u => u.ReadingMedicineQuestionId, (t, u) => new { t.Answer, u.QuestionName, u.ShowOrder }).OrderBy(t => t.ShowOrder).ToList(),
                });
            }


            //医学审核对话

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingMedicalReviewDialog)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ReadingMedicalReviewDialog;

                bool isHaveQuestion = false;
                if (entitys.Any(x => x.Entity.GetType() == typeof(TaskMedicalReview)))
                {
                    isHaveQuestion = entitys.Where(x => x.Entity.GetType() == typeof(TaskMedicalReview)).Select(x => x.Entity as TaskMedicalReview).Select(x => x.IsHaveQuestion).FirstOrDefault();
                }
                else
                {
                    isHaveQuestion = await _dbContext.TaskMedicalReview.Where(x => x.Id == entity.TaskMedicalReviewId).Select(t => t.IsHaveQuestion).FirstOrDefaultAsync();
                }


                var extraIdentification = string.Empty;

                //失效的时候 不区分标识
                if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.MIM)
                {
                    extraIdentification = $"/MIM";
                }
                else
                {
                    extraIdentification = $"/IR";
                }

                await InsertInspection<ReadingMedicalReviewDialog>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,
                    VisitTaskId = entity.VisitTaskId,

                    ObjectRelationParentId = entity.TaskMedicalReviewId,

                    ExtraIndentification = extraIdentification

                }, new
                {
                    IsHaveQuestion = isHaveQuestion,
                });
            }



            //医学审核
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TaskMedicalReview)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as TaskMedicalReview;

                var extraIdentification = string.Empty;

                //失效的时候 不区分标识
                if (_dbContext.Entry(entity).Property(t => t.IsInvalid).IsModified == true && entity.IsInvalid == true)
                {
                    extraIdentification = $"/Invalid";
                }

                await InsertInspection<TaskMedicalReview>(entity, type, x => new InspectionConvertDTO()
                {
                    VisitTaskId = entity.VisitTaskId,

                    ObjectRelationParentId = entity.VisitTaskId,

                    ObjectRelationParentId2 = entity.MedicalManagerUserId,

                    ExtraIndentification = extraIdentification,

                    IsDistinctionInterface = (type == AuditOpt.Add || extraIdentification != String.Empty) ? false : true
                });
            }

            //系统 医学审核问题
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingMedicineSystemQuestion)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ReadingMedicineSystemQuestion;

                var parentQuestionName = string.Empty;
                if (entity.ParentId != null)
                {
                    parentQuestionName = await _dbContext.ReadingMedicineSystemQuestion.Where(x => x.Id == entity.ParentId).Select(x => x.QuestionName).FirstOrDefaultAsync();
                }

                await InsertInspection<ReadingMedicineSystemQuestion>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,
                }, new { ParentQuestionName = parentQuestionName });
            }

            //项目医学审核问题
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingMedicineTrialQuestion)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ReadingMedicineTrialQuestion;

                var parentQuestionName = string.Empty;
                if (entity.ParentId != null)
                {
                    parentQuestionName = await _dbContext.ReadingMedicineTrialQuestion.Where(x => x.Id == entity.ParentId).Select(x => x.QuestionName).FirstOrDefaultAsync();
                }

                await InsertInspection<ReadingMedicineTrialQuestion>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,

                    ObjectRelationParentId = entity.TrialId,
                    TrialReadingCriterionId = x.TrialReadingCriterionId,


                }, new { ParentQuestionName = parentQuestionName });
            }


            #endregion

            #region QC  质疑 一致性核查



            // Qc 问题答案   
            if (entitys.Any(x => x.Entity.GetType() == typeof(TrialQCQuestionAnswer)))
            {
                var entityEntryList = entitys.Where(x => x.Entity.GetType() == typeof(TrialQCQuestionAnswer));

                var type = entityEntryList.All(t => t.State == EntityState.Added) ? AuditOpt.Add : AuditOpt.Update;


                var list = entityEntryList.Select(t => t.Entity as TrialQCQuestionAnswer);


                var firstEntity = list.FirstOrDefault();

                var trialQuestionIdList = list.Select(t => t.TrialQCQuestionConfigureId);

                var trialQuestionNameList = await _dbContext.TrialQCQuestionConfigure.Where(x => x.TrialId == firstEntity.TrialId).Select(t => new { t.QuestionName, TrialQCQuestionConfigureId = t.Id, t.ShowOrder }).ToListAsync();

                var beforeAnswerList = await _dbContext.TrialQCQuestionAnswer.Where(x => x.SubjectVisitId == firstEntity.SubjectVisitId && x.CurrentQCEnum == firstEntity.CurrentQCEnum && x.QCProcessEnum == firstEntity.QCProcessEnum)
                    .Select(u => new { u.TrialQCQuestionConfigureId, u.Answer }).ToListAsync();

                var answerList = list.Select(u => new { u.TrialQCQuestionConfigureId, u.Answer }).Union(beforeAnswerList).DistinctBy(t => t.TrialQCQuestionConfigureId);

                var cloneEntity = firstEntity.Clone();

                //保证Id 唯一
                cloneEntity.Id = IdentifierHelper.CreateGuid(firstEntity.SubjectVisitId.ToString(), ((int)firstEntity.QCProcessEnum).ToString(), ((int)firstEntity.CurrentQCEnum).ToString());

                await InsertInspection(cloneEntity, type, x => new InspectionConvertDTO()
                {
                    SubjectVisitId = x.SubjectVisitId,

                    //byzhouhang
                    ObjectRelationParentId = x.SubjectVisitId,
                }, new
                {
                    QcQuestionAnswerList = answerList.Join(trialQuestionNameList, t => t.TrialQCQuestionConfigureId, u => u.TrialQCQuestionConfigureId, (t, u) => new
                    {
                        t.Answer,

                        u.QuestionName,
                        u.ShowOrder
                    }).OrderBy(t => t.ShowOrder).ToList(),
                });









            }

            //QC 质疑
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(QCChallenge)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as QCChallenge;

                await InsertInspection<QCChallenge>(entity, type, x => new InspectionConvertDTO()
                {
                    SubjectVisitId = x.SubjectVisitId,

                    ObjectRelationParentId = x.SubjectVisitId
                }, new
                {

                    IsOverTime = entity.IsClosed ? entity.ClosedTime > entity.DeadlineTime : DateTime.Now > entity.DeadlineTime,
                });
            }

            // 质疑 对话
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(QCChallengeDialog)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as QCChallengeDialog;

                var extraIdentification = string.Empty;

                var reason = string.Empty;

                //  对话消息区分用户类型

                extraIdentification = "/(" + _userInfo.UserTypeShortName + ")";


                if (_userInfo.RequestUrl.ToLower() == "qcoperation/closeqcchallenge")
                {
                    reason = entity.TalkContent.Substring(entity.TalkContent.LastIndexOf(':') + 1);
                }

                await InsertInspection<QCChallengeDialog>(entity, type, x => new InspectionConvertDTO()
                {

                    SubjectVisitId = x.SubjectVisitId,


                    //byzhouhang
                    ObjectRelationParentId = entity.QCChallengeId,

                    IsDistinctionInterface = false,
                    ExtraIndentification = extraIdentification,
                });
            }
            //一致性核查 对话
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(CheckChallengeDialog)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as CheckChallengeDialog;

                var extraIdentification = string.Empty;

                var reason = string.Empty;

                extraIdentification = "/(" + _userInfo.UserTypeShortName + ")";

                if (_userInfo.RequestUrl.ToLower() == "qcoperation/closecheckchallenge")
                {
                    reason = entity.TalkContent.Substring(entity.TalkContent.LastIndexOf(':') + 1);
                }


                await InsertInspection<CheckChallengeDialog>(entity, type, x => new InspectionConvertDTO()
                {

                    SubjectVisitId = x.SubjectVisitId,

                    //byzhouhang
                    IsDistinctionInterface = false,

                    Reason = reason,

                    ExtraIndentification = extraIdentification,
                    ObjectRelationParentId = entity.SubjectVisitId,
                }

                );
            }


            // 一致性核查文件  是否需要单独一个表记录？
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(InspectionFile)))
            {
                var type = GetEntityAuditOpt(item);

                await InsertInspection<InspectionFile>(item.Entity as InspectionFile, type, x => new InspectionConvertDTO()
                {
                    ObjectRelationParentId = x.TrialId

                });
            }
            #endregion

            #region 中心调研


            // 中心调研表
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TrialSiteSurvey)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as TrialSiteSurvey;
                if (entity.TrialSite == null)
                {
                    entity.TrialSite = await _dbContext.TrialSite.IgnoreQueryFilters().Where(x => x.Id == entity.TrialSiteId && x.TrialId == entity.TrialId).FirstOrDefaultAsync();
                }

                if (entity.PreliminaryUser == null)
                {
                    entity.PreliminaryUser = await _dbContext.User.Where(x => x.Id == entity.PreliminaryUserId).FirstOrDefaultAsync();
                }

                if (entity.ReviewerUser == null)
                {
                    entity.ReviewerUser = await _dbContext.User.Where(x => x.Id == entity.ReviewerUserId).FirstOrDefaultAsync();
                }

                var trialSiteId = entity.TrialSite?.Id;

                await InsertInspection<TrialSiteSurvey>(item.Entity as TrialSiteSurvey, type, x => new InspectionConvertDTO()
                {
                    ObjectRelationParentId = trialSiteId,
                }, new
                {

                    //TrialSiteCode = entity.TrialSite.TrialSiteCode,
                    //TrialSiteAliasName = entity.TrialSite.TrialSiteAliasName,
                    //Phone = entity.Phone,
                    //Email = entity.Email,


                    PreliminaryUser = entity.PreliminaryUser == null ? "" : entity.PreliminaryUser.FullName,
                    ReviewerUser = entity.ReviewerUser == null ? "" : entity.ReviewerUser.FullName,

                });
            }
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TrialSiteUserSurvey)))
            {
                var type = GetEntityAuditOpt(item);
                var entity = item.Entity as TrialSiteUserSurvey;

                var trialid = await _dbContext.TrialSiteSurvey.Where(x => x.Id == entity.TrialSiteSurveyId).Select(x => x.TrialId).FirstOrDefaultAsync();



                await InsertInspection<TrialSiteUserSurvey>(entity, type, x => new InspectionConvertDTO()
                {
                    TrialId = trialid,

                    IsDistinctionInterface = false

                });
            }
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TrialSiteEquipmentSurvey)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as TrialSiteEquipmentSurvey;
                var trialid = await _dbContext.TrialSiteSurvey.Where(x => x.Id == entity.TrialSiteSurveyId).Select(x => x.TrialId).FirstOrDefaultAsync();

                await InsertInspection<TrialSiteEquipmentSurvey>(entity, type, x => new InspectionConvertDTO()
                {
                    TrialId = trialid,
                    IsDistinctionInterface = false

                });
            }

            #endregion




            //系统  Qc 问题
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(QCQuestion)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as QCQuestion;

                int? parentQuestionOrder = null;
                string parentQuestionName = string.Empty;

                if (entity.ParentId != null)
                {
                    var question = await _dbContext.QCQuestionConfigure.Where(x => x.Id == entity.ParentId).Select(x => new { x.Id, x.ShowOrder, x.QuestionName }).FirstOrDefaultAsync();

                    parentQuestionOrder = question?.ShowOrder;
                    parentQuestionName = question?.QuestionName;

                }


                await InsertInspection<QCQuestion>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false

                }, new
                {
                    ParentQuestionName = parentQuestionName,
                    ParentQuestionOrder = parentQuestionOrder
                });
            }

            // 项目QC问题
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TrialQCQuestion)))
            {

                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as TrialQCQuestion;

                int? parentQuestionOrder = null;
                string parentQuestionName = string.Empty;

                if (entity.ParentId != null)
                {
                    var question = entitys.Where(x => x.Entity.GetType() == typeof(TrialQCQuestion)).Select(t => t.Entity as TrialQCQuestion).Select(x => new { x.Id, x.ShowOrder, x.QuestionName }).FirstOrDefault(t => t.Id == entity.ParentId);

                    question = question ?? await _dbContext.TrialQCQuestionConfigure.Where(x => x.Id == entity.ParentId).Select(x => new { x.Id, x.ShowOrder, x.QuestionName }).FirstOrDefaultAsync();


                    parentQuestionOrder = question?.ShowOrder;
                    parentQuestionName = question?.QuestionName;

                }


                await InsertInspection<TrialQCQuestion>(entity, type, x => new InspectionConvertDTO()
                {
                    ObjectRelationParentId = x.TrialId,
                    IsDistinctionInterface = false
                }, new
                {
                    ParentQuestionName = parentQuestionName,
                    ParentQuestionOrder = parentQuestionOrder
                });
            }



            // 签名模板
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(SystemBasicData)))
            {
                var type = GetEntityAuditOpt(item);

                var extraIdentification = string.Empty;

                var basicData = item.Entity as SystemBasicData;
                extraIdentification = (basicData.ParentId == null ? "/parent" : string.Empty);

                await InsertInspection<SystemBasicData>(item.Entity as SystemBasicData, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,
                    ExtraIndentification = extraIdentification
                });
            }


            #region 项目参与人员  项目site



            // 项目中心  Site未稽查
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TrialSite)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as TrialSite;
                if (entity.Site == null && entity.SiteId != null)
                {
                    entity.Site = await _dbContext.Site.Where(x => x.Id == entity.SiteId).FirstOrDefaultAsync();
                }
                await InsertInspection<TrialSite>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = type == AuditOpt.Update ? true : false,
                    TrialId = x.TrialId,

                    ObjectRelationParentId = x.TrialId
                }, new
                {
                    //兼容之前的配置  冗余该字段
                    SiteCode = entity.TrialSiteCode,

                    //Site  没记录稽查 必须查询存
                    SiteName = entity.TrialSiteName
                });
            }

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(UserRole)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as UserRole;
                //var user = await _dbContext.Users.Include(x => x.UserTypeRole).FirstOrDefaultAsync(x => x.Id == entity.UserId);
                await InsertInspection<UserRole>(entity, type, x => new InspectionConvertDTO
                {
                    IsDistinctionInterface = type == AuditOpt.Update ? true : false,
                });
            }

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(IdentityUser)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as IdentityUser;


                await InsertInspection<IdentityUser>(entity, type, x => new InspectionConvertDTO
                {
                    IsDistinctionInterface = type == AuditOpt.Update ? true : false,
                });
            }

            // 项目参与人员
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TrialIdentityUser)))
            {
                var type = GetEntityAuditOpt(item);
                var entity = item.Entity as TrialIdentityUser;
                string extraIndentification = string.Empty;

                var identityUser = await _dbContext.IdentityUser.AsNoTracking().Where(x => x.Id == entity.IdentityUserId).FirstOrDefaultAsync();

                // 变更维护数据，会维护数据，不能插入稽查
                if (_userInfo.IsNotNeedInspection == false)
                {
                    await InsertInspection<TrialIdentityUser>(entity, type, x => new InspectionConvertDTO
                    {
                        //IsDistinctionInterface =  true ,
                        TrialId = x.TrialId,
                        IsDistinctionInterface = false,
                        ObjectRelationParentId = x.TrialId,
                        ExtraIndentification = extraIndentification,
                        //ObjectRelationParentId2 = x.IdentityUserId,
                    }, new
                    {

                        identityUser.FullName,
                        identityUser.EMail,
                        identityUser.Code,
                        identityUser.UserCode,
                        identityUser.UserName,
                        identityUser.DepartmentName,
                        identityUser.Phone,
                        identityUser.OrganizationName,
                    });
                }
            }

            // 项目人员
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TrialUserRole)))
            {
                var type = GetEntityAuditOpt(item);
                var entity = item.Entity as TrialUserRole;
                string extraIndentification = string.Empty;
                if (type == AuditOpt.Update)
                {
                    extraIndentification = "/" + entity.IsDeleted.ToString();
                }

                var userTypeEnum = await _dbContext.Users.Where(x => x.Id == entity.UserId).Select(x => x.UserTypeEnum).FirstOrDefaultAsync();
                //var user = await _dbContext.Users.Include(x => x.UserTypeRole).FirstOrDefaultAsync(x => x.Id == entity.UserId);
                await InsertInspection<TrialUserRole>(entity, type, x => new InspectionConvertDTO
                {
                    IsDistinctionInterface = false,
                    TrialId = x.TrialId,
                    ObjectRelationParentId = x.TrialId,
                    ExtraIndentification = extraIndentification,
                    ObjectRelationParentId2 = x.UserId,
                }, new
                {
                    UserTypeEnum = userTypeEnum,
                });
            }


            // 项目中心人员
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TrialSiteUserRole)))
            {

                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as TrialSiteUserRole;


                if (entity.TrialSite == null)
                {
                    entity.TrialSite = await _dbContext.TrialSite.Where(x => x.Id == entity.TrialSiteId).IgnoreQueryFilters().FirstOrDefaultAsync();
                }

                await InsertInspection<TrialSiteUserRole>(item.Entity as TrialSiteUserRole, type, x => new InspectionConvertDTO
                {
                    IsDistinctionInterface = type == AuditOpt.Update ? true : false,
                    TrialId = x.TrialId,
                    ObjectRelationParentId = entity.TrialSite.Id,
                    ObjectRelationParentId2 = x.UserId,
                });
            }

            #endregion

            // 受试者
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(Subject)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as Subject;
                var finalSubjectVisitName = await _dbContext.SubjectVisit.AsNoTracking().Where(x => x.Id == entity.FinalSubjectVisitId && entity.FinalSubjectVisitId != null).Select(x => x.VisitName).FirstOrDefaultAsync();


                await InsertInspection<Subject>(entity, type, x => new InspectionConvertDTO()
                {
                    SubjectId = x.Id,
                    Reason = entity.SuspendReason,
                    TrialSiteId = x.TrialSiteId,

                    //项目的信息 找离的最近的项目稽查信息
                    ObjectRelationParentId = entity.TrialSiteId,
                }, new
                {
                    FinalSubjectVisitName = finalSubjectVisitName,

                    //变换名称   兼容之前做的稽查  冗余
                    SubjectCode = entity.Code,
                });
            }

            // 访视计划
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(VisitStage)))
            {

                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as VisitStage;

                await InsertInspection<VisitStage>(item.Entity as VisitStage, type, x => new InspectionConvertDTO()
                {
                    ObjectRelationParentId = x.TrialId

                });

                #region Old
                //var visitPlanStatus = await this._dbContext.Trial.Where(x => x.Id == entity.TrialId).Select(x => x.VisitPlanConfirmed).FirstOrDefaultAsync();
                //if (type == "Add")
                //{
                //    visitPlanStatus = false;
                //}
                //await InsertInspection<VisitStage>(item.Entity as VisitStage, type, x => new InspectionConvertDTO()
                //{
                //    ObjectRelationParentId = x.TrialId

                //}, new
                //{
                //    VisitPlanStatus = visitPlanStatus,
                //});
                #endregion

            }


            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(SubjectVisitImageBackRecord)))
            {

                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as SubjectVisitImageBackRecord;

                var extraIdentification = string.Empty;

                var isDistinctionInterface = true;

                var reason = type == AuditOpt.Add ? entity.ApplyReason : entity.ResultRemark;

                #region 处理标识



                #endregion
                var SubjectId = await _dbContext.SubjectVisit.Where(x => x.Id == entity.SubjectVisitId).Select(x => x.SubjectId).FirstOrDefaultAsync();

                await InsertInspection<SubjectVisitImageBackRecord>(item.Entity as SubjectVisitImageBackRecord, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = isDistinctionInterface,
                    Reason = reason,

                    //Subject的信息 找离的最近的Subject稽查信息
                    ObjectRelationParentId = x.SubjectVisitId,

                    SubjectId = SubjectId,
                    SubjectVisitId = x.Id,


                    ExtraIndentification = extraIdentification,

                }
                );
            }
            // 访视
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(SubjectVisit)))
            {

                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as SubjectVisit;

                var extraIdentification = string.Empty;

                var isDistinctionInterface = true;

                var reason = string.Empty;

                #region 处理标识

                switch (_userInfo.RequestUrl.ToLower())
                {
                    //待处理？
                    case "qcoperation/qcpassedorfailed":

                        if (entity.AuditState == AuditStateEnum.QCPassed && (entity.SecondReviewState == SecondReviewState.AuditPassed || entity.SecondReviewState == SecondReviewState.AuditFailed))
                        {
                            extraIdentification = "/SecondReviewFinished";
                        }
                        else
                        {
                            extraIdentification = "/" + (40 % (int)entity.AuditState).ToString();

                        }

                        break;

                    //设置核查通过
                    case "qcoperation/setcheckpass":

                        reason = entity.ManualPassReason;
                        break;

                    //领取或者取消QC任务
                    case "qcoperation/obtainorcancelqctask":
                        type = type + "/" + entity.IsTake.ToString();
                        break;

                    //确认重阅  区分用户类型
                    case "visittask/confirmrereading":

                        if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.APM)
                        {
                            type = type + "/" + 1;

                        }
                        else
                        {
                            //SPM
                            type = type + "/" + 2;
                        }
                        break;


                }

                if (_userInfo.RequestUrl == "NoneDicomStudy/deleteNoneDicomStudy" || _userInfo.RequestUrl == "NoneDicomStudy/deleteNoneDicomStudyFile")
                {
                    isDistinctionInterface = false;

                    extraIdentification = "/DeleteNoneDicomFileZero";
                }

                if (_userInfo.RequestUrl == "QCOperation/addCheckChallengeReply" || _userInfo.RequestUrl == "QCOperation/UploadVisitCheckExcel")
                {
                    if (entity.CheckChallengeState == CheckChanllengeTypeEnum.CRCWaitPMReply || entity.CheckChallengeState == CheckChanllengeTypeEnum.PMWaitCRCReply)
                    {
                        //发送对话  修改质疑状态  不需要区分接口
                        isDistinctionInterface = false;

                        extraIdentification = "/ModifyCheckChallengeState";
                    }
                }

                if (entity.SubmitState == SubmitStateEnum.ToSubmit)
                {
                    if (_dbContext.SubjectVisit.Where(t => t.Id == entity.Id).Any(t => t.SubmitState == SubmitStateEnum.None))
                    {
                        isDistinctionInterface = false;
                        extraIdentification = "/FirstUploadToSubmit";
                    }
                }
                else if (entity.SubmitState == SubmitStateEnum.None)
                {
                    if (_dbContext.SubjectVisit.Where(t => t.Id == entity.Id).Any(t => t.SubmitState == SubmitStateEnum.ToSubmit))
                    {
                        isDistinctionInterface = false;
                        extraIdentification = "/NoImage";
                    }
                }

                #endregion


                await InsertInspection<SubjectVisit>(item.Entity as SubjectVisit, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = isDistinctionInterface,
                    Reason = reason,

                    //Subject的信息 找离的最近的Subject稽查信息
                    ObjectRelationParentId = x.SubjectId,

                    SubjectId = x.SubjectId,
                    SubjectVisitId = x.Id,

                    TrialSiteId = x.TrialSiteId,

                    ExtraIndentification = extraIdentification,

                },
                //兼容之前的配置名 
                new { SubjectVisitName = entity.VisitName }
                );
            }


            //任务
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(VisitTask)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as VisitTask;
                var userRealName = await _dbContext.User.Where(x => x.Id == entity.DoctorUserId).Select(x => x.FullName).FirstOrDefaultAsync();
                VisitTaskAuditingDto obj = new VisitTaskAuditingDto()
                {
                    UserRealName = userRealName,

                };

                string reason = string.Empty;
                var extraIdentification = string.Empty;
                var isDistinctionInterface = true;
                #region 标识区分

                if (type == AuditOpt.Add)
                {
                    isDistinctionInterface = false;

                    //生成一致性分析任务
                    if (entity.IsSelfAnalysis == true)
                    {
                        extraIdentification = "/SelfAnalysis";
                    }
                    else if (entity.IsSelfAnalysis == false)
                    {
                        extraIdentification = "/GroupAnalysis";
                    }
                    else
                    {
                        extraIdentification = "/NotAnalysis";
                    }

                    //区分任务类型
                    extraIdentification = extraIdentification + "/" + (int)entity.ReadingCategory;


                }
                else
                {


                    switch (_userInfo.RequestUrl)
                    {
                        //申请重阅
                        case "VisitTask/applyReReading":


                            extraIdentification = "/" + (int)entity.ReReadingApplyState;

                            break;


                        //同意重阅
                        case "VisitTask/ConfirmReReading":


                            if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.APM)
                            {
                                extraIdentification = "/" + 1;

                            }
                            else
                            {
                                extraIdentification = "/" + 2;
                            }

                            break;

                        case "VisitTask/PMSetTaskBack":

                            if (entity.PMBackReason.IsNotNullOrEmpty())
                            {
                                extraIdentification = "/" + "Reason";
                                reason = entity.PMBackReason;
                            }

                            break;

                        case "ReadingImageTask/SubmitVisitTaskQuestions":

                            //访视任务-- 非Dicom 阅片
                            if (entity.ReadingTaskState != ReadingTaskState.HaveSigned)
                            {
                                //提交访视任务的时候 会多次更新同一个记录 只记录最后一次
                                return;
                            }

                            break;

                        //Dicom 阅片  签名
                        case "ReadingImageTask/SubmitDicomVisitTask":

                            //跳转阅片结果需要该参数
                            var subjectCode = _dbContext.Subject.Where(t => t.Id == entity.SubjectId).Select(t => t.Code).First();

                            obj.SubjectCode = subjectCode;

                            break;

                        case "ReadingImageTask/resetReadingTask":
                            //跳转阅片结果需要该参数

                            obj.IsReadingReset = true;

                            break;

                    }

                    #region 裁判、肿瘤学、全局 都是通用的

                    //裁判任务  结果的保存 和签名提交
                    if (entity.JudgeResultTaskId != null && (_userInfo.RequestUrl == "ReadingImageTask/SaveJudgeVisitTaskResult" || _userInfo.RequestUrl == "ReadingImageTask/SubmitJudgeVisitTaskResult"))
                    {

                        var visitTaskNum = entity.VisitTaskNum - ReadingCommon.TaskNumDic[ReadingCategory.Judge];
                        var list = await _dbContext.VisitTask.Where(t => t.TaskState == TaskState.Effect && t.SubjectId == entity.SubjectId && t.VisitTaskNum == visitTaskNum && t.JudgeVisitTaskId == entity.Id && t.TrialReadingCriterionId == entity.TrialReadingCriterionId).Select(t => new { t.Id, t.DoctorUser.FullName, t.ArmEnum }).OrderBy(t => t.ArmEnum).ToListAsync();


                        var r1 = list.Where(t => t.ArmEnum == Arm.DoubleReadingArm1).FirstOrDefault();
                        var r2 = list.Where(t => t.ArmEnum == Arm.DoubleReadingArm2).FirstOrDefault();

                        obj.R1 = r1.FullName;
                        obj.R2 = r2.FullName;
                        obj.SelectResult = r1.Id == entity.JudgeResultTaskId ? "R1" : "R2";
                    }

                    #endregion

                    //增加进入阅片中的稽查

                    //重置阅片也会从待阅片 变为阅片中，因为复制病灶依赖这个改变
                    if (obj.IsReadingReset != true)
                    {
                        if (entity.ReadingTaskState == ReadingTaskState.Reading)
                        {
                            if (_dbContext.VisitTask.Where(t => t.Id == entity.Id).Any(t => t.ReadingTaskState == ReadingTaskState.WaitReading))
                            {
                                isDistinctionInterface = false;
                                extraIdentification = "/ChangeToReading";
                            }
                        }
                    }



                    if (entity.IsReadClinicalData == true)
                    {
                        if (_dbContext.VisitTask.Where(t => t.Id == entity.Id).Any(t => t.IsReadClinicalData == false))
                        {
                            isDistinctionInterface = false;
                            extraIdentification = "/ReadClinicalData";
                        }
                    }

                    if (entity.TaskBlindName.Contains("Timepoint Ran"))
                    {
                        if (_dbContext.VisitTask.Where(t => t.Id == entity.Id).Any(t => !t.TaskBlindName.Contains("Timepoint Ran")))
                        {
                            isDistinctionInterface = false;
                            extraIdentification = "/TriggerSystemBlindingName";
                        }
                    }



                }


                #region 通过链接跳转 2022 12-19

                ////肿瘤学任务
                //if (entity.ReadingTaskState == ReadingTaskState.HaveSigned && _userInfo.RequestUrl == "ReadingImageTask/SubmitOncologyReadingInfo")
                //{


                //    var oncologyAnswerList = await _dbContext.ReadingOncologyTaskInfo.Where(t => t.OncologyTaskId == entity.Id).Select(t => new { t.VisitTask.TaskBlindName, t.VisitTask.TaskName, t.EvaluationReason, t.EvaluationResult, t.VisitTask.VisitTaskNum, VisitTaskId = t.VisitTask.Id }).ToListAsync();

                //    var golbalTaskInfo = await _dbContext.VisitTask.Where(t => t.SubjectId == entity.SubjectId && t.ReadingCategory == ReadingCategory.Global && t.TaskState == TaskState.Effect && t.IsAnalysisCreate == entity.IsAnalysisCreate && t.VisitTaskNum == (entity.VisitTaskNum - ReadingCommon.TaskNumDic[ReadingCategory.Oncology] + ReadingCommon.TaskNumDic[ReadingCategory.Global])).Select(t => new { GlobalTaskId = t.Id }).FirstNotNullAsync();


                //    var globalResultList = await _dbContext.ReadingGlobalTaskInfo.Where(t => t.GlobalTaskId == golbalTaskInfo.GlobalTaskId).ToListAsync();

                //    var modifyVisitList = globalResultList
                //           .GroupBy(t => t.TaskId).Select(g => new
                //           {
                //               VisitTaskId = g.Key,
                //               GlobalResult = g.Select(c => new { c.Answer, c.QuestionId })
                //           }).ToList();

                //    var query = from answer in oncologyAnswerList
                //                join modifyVisit in modifyVisitList on answer.VisitTaskId equals modifyVisit.VisitTaskId into cc
                //                from modifyVisit in cc.DefaultIfEmpty()
                //                select new
                //                {
                //                    answer.TaskBlindName,
                //                    answer.TaskName,
                //                    answer.EvaluationReason,
                //                    answer.EvaluationResult,
                //                    IsGlobalModify = modifyVisit != null,
                //                    Reason = modifyVisit != null ? modifyVisit.GlobalResult.Where(t => t.QuestionId == null).FirstOrDefault()?.Answer : String.Empty
                //                };

                //    var result = query.ToList();

                //    obj = new { OncologyAnswerList = result };
                //}

                ////全局任务  
                //if (entity.ReadingTaskState == ReadingTaskState.HaveSigned && _userInfo.RequestUrl == "ReadingImageTask/SubmitGlobalReadingInfo")
                //{

                //    var globalResultList = await _dbContext.ReadingGlobalTaskInfo.Where(t => t.GlobalTaskId == entity.Id).Select(t => new { VisitTaskId = t.TaskId, t.QuestionId, t.Answer, t.VisitTask.TaskBlindName, t.VisitTask.TaskName, t.TrialReadingQuestion.QuestionName }).ToListAsync();

                //    var visitTaskIdList = globalResultList.Select(t => t.VisitTaskId).ToList();

                //    var visitResultList = await _dbContext.ReadingTaskQuestionAnswer.Where(t => visitTaskIdList.Contains(t.VisitTaskId) && t.ReadingQuestionTrial.IsJudgeQuestion).Select(t => new { t.VisitTaskId, t.VisitTask.TaskBlindName, t.VisitTask.TaskName, t.VisitTask.VisitTaskNum, t.ReadingQuestionTrial.QuestionName, t.ReadingQuestionTrial.ShowOrder, t.Answer, t.ReadingQuestionTrialId })
                //        .OrderBy(t => t.VisitTaskNum).ToListAsync();

                //    var query = visitResultList.GroupBy(t => new { t.VisitTaskId, t.VisitTaskNum, t.TaskName, t.TaskBlindName }).Select(g => new
                //    {
                //        VisitTaskId = g.Key.VisitTaskId,
                //        VisitTaskNum = g.Key.VisitTaskNum,
                //        TaskName = g.Key.TaskName,
                //        TaskBlindName = g.Key.TaskBlindName,

                //        VisitQuestionAnswerList = g.OrderBy(t => t.ShowOrder).Select(u => new { u.QuestionName, u.Answer }).ToList(),

                //        GlobalQuestionAnswerList = g.OrderBy(t => t.ShowOrder).Select(u => new { u.QuestionName, Answer = globalResultList.Where(t => t.VisitTaskId == g.Key.VisitTaskId && t.QuestionId == u.ReadingQuestionTrialId).FirstOrDefault()?.Answer ?? String.Empty }).ToList(),

                //        Reason = globalResultList.Where(t => t.VisitTaskId == g.Key.VisitTaskId && t.QuestionId == null).FirstOrDefault()?.Answer ?? String.Empty
                //    });


                //    var result = query.ToList();

                //    obj = new { GlobalAnswerList = result };
                //}

                #endregion

                #endregion

                if (entity.SouceReadModuleId != null)
                {
                    var subjectVisitId = await _dbContext.ReadModule.Where(x => x.Id == entity.SouceReadModuleId).Select(x => x.SubjectVisitId).FirstOrDefaultAsync();

                    obj.CutOffVisitName = await _dbContext.SubjectVisit.Where(x => x.Id == subjectVisitId).Select(x => x.BlindName).FirstOrDefaultAsync();

                }

                await InsertInspection<VisitTask>(entity, type, x => new InspectionConvertDTO()
                {
                    VisitTaskId = x.Id,

                    IsDistinctionInterface = isDistinctionInterface,
                    Reason = reason,
                    ExtraIndentification = extraIdentification,

                    SubjectVisitId = entity.SourceSubjectVisitId,

                    ObjectRelationParentId = entity.SourceSubjectVisitId != null ? entity.SourceSubjectVisitId : entity.SouceReadModuleId,

                    ObjectRelationParentId2 = entity.DoctorUserId,

                    ObjectRelationParentId3 = entity.TrialReadingCriterionId,

                }, obj);
            }

            #region Dicom  非Dicom  既往手术史..临床数据

            // Dicom
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(DicomStudy)))
            {
                var type = GetEntityAuditOpt(item);
                var extraIdentification = string.Empty;

                var entity = item.Entity as DicomStudy;

                var reason = entity.ModifyReason;
                switch (_userInfo.RequestUrl)
                {
                    case "QCOperation/updateModality":
                        if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ClinicalResearchCoordinator)
                        {
                            extraIdentification = "/2";
                        }

                        break;
                    case "Study/amendmentPatientInfo":
                        reason = entity.Reason;

                        break;
                }

                await InsertInspection<DicomStudy>(item.Entity as DicomStudy, type, x => new InspectionConvertDTO()
                {
                    ObjectRelationParentId = x.SubjectVisitId,
                    ExtraIndentification = extraIdentification,
                    Reason = reason
                });
            }

            // 后处理Dicom影像
            // TaskStudy

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TaskStudy)))
            {
                var entity = item.Entity as TaskStudy;
                var type = GetEntityAuditOpt(item);
                var armEnum = await _dbContext.VisitTask.Where(x => x.Id == entity.VisitTaskId).Select(x => x.ArmEnum).FirstOrDefaultAsync();
                await InsertInspection<TaskStudy>(item.Entity as TaskStudy, type, x => new InspectionConvertDTO()
                {
                    ObjectRelationParentId = x.VisitTaskId,
                }, new
                {
                    ArmEnum = armEnum,
                });
            }

            // 序列
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(DicomSeries)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as DicomSeries;

                await InsertInspection<DicomSeries>(item.Entity as DicomSeries, type, x => new InspectionConvertDTO()
                {
                    ObjectRelationParentId = x.StudyId
                }
                );
            }

            //
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(DicomInstance)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as DicomInstance;

                await InsertInspection<DicomInstance>(item.Entity as DicomInstance, type, x => new InspectionConvertDTO()
                {
                    ObjectRelationParentId = x.SeriesId,
                    ObjectRelationParentId2 = x.StudyId,
                }
                );
            }


            // 非Dicom
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(NoneDicomStudy)))
            {

                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as NoneDicomStudy;

                var extraIdentification = string.Empty;

                if (_userInfo.RequestUrl.ToLower() == "nonedicomstudy/addorupdatenonedicomstudy")
                {
                    extraIdentification = "/(" + _userInfo.UserTypeShortName + ")";
                }



                await InsertInspection<NoneDicomStudy>(item.Entity as NoneDicomStudy, type, x => new InspectionConvertDTO()
                {
                    ObjectRelationParentId = x.SubjectVisitId,
                    ExtraIndentification = extraIdentification,
                    Reason = entity.ModifyReason
                });
            }

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(NoneDicomStudyFile)))
            {

                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as NoneDicomStudyFile;

                var extraIdentification = string.Empty;


                Guid? subjectVisitId = null;

                Arm? armEnum = Arm.SingleReadingArm;
                if (entity.VisitTaskId != null)
                {
                    extraIdentification = "/VisitTask";
                    var obj = await _dbContext.VisitTask.FindAsync(entity.VisitTaskId);
                    armEnum = obj?.ArmEnum;
                    subjectVisitId = obj.SourceSubjectVisitId;
                }
                else if (entity.ImageLabelNoneDicomStudyId != null)
                {
                    //默认R0
                    extraIdentification = "/VisitTask";

                    subjectVisitId = await _dbContext.NoneDicomStudy.Where(x => x.Id == entity.ImageLabelNoneDicomStudyId).Select(t => t.SubjectVisitId).FirstOrDefaultAsync();
                }
                else
                {
                    subjectVisitId = (await _dbContext.NoneDicomStudy.FindAsync(entity.NoneDicomStudyId))?.SubjectVisitId;
                }

                await InsertInspection<NoneDicomStudyFile>(item.Entity as NoneDicomStudyFile, type, x => new InspectionConvertDTO()
                {
                    SubjectVisitId = subjectVisitId,
                    //SubjectId = noneDicomStudy.SubjectId,
                    VisitTaskId = x.VisitTaskId,
                    ObjectRelationParentId = subjectVisitId,
                    ObjectRelationParentId2 = x.NoneDicomStudyId,
                    ObjectRelationParentId3 = x.OriginNoneDicomStudyId,
                    ExtraIndentification = extraIdentification
                }, new
                {
                    ArmEnum = armEnum,
                });
            }


            // 既往手术史
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(PreviousSurgery)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as PreviousSurgery;

                await InsertInspection<PreviousSurgery>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,

                    SubjectVisitId = x.SubjectVisitId,

                    ObjectRelationParentId = x.SubjectVisitId,

                    ObjectRelationParentId2 = x.ClinicalDataTrialSetId,

                }, new
                {
                    ClinicalDataLevel = ClinicalLevel.Subject,

                    Type = ClinicalFileType.PreviousSurgery
                });
            }

            // 既往放疗史
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(PreviousHistory)))
            {

                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as PreviousHistory;

                await InsertInspection<PreviousHistory>(entity, type, x => new InspectionConvertDTO()
                {


                    IsDistinctionInterface = false,

                    SubjectVisitId = x.SubjectVisitId,

                    ObjectRelationParentId2 = x.ClinicalDataTrialSetId,

                    ObjectRelationParentId = x.SubjectVisitId,
                }, new
                {
                    ClinicalDataLevel = ClinicalLevel.Subject,
                    Type = ClinicalFileType.PreviousHistory
                });
            }

            // 其他治疗史
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(PreviousOther)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as PreviousOther;

                await InsertInspection<PreviousOther>(entity, type, x => new InspectionConvertDTO()
                {

                    IsDistinctionInterface = false,

                    SubjectVisitId = x.SubjectVisitId,

                    ObjectRelationParentId2 = x.ClinicalDataTrialSetId,

                    ObjectRelationParentId = x.SubjectVisitId,
                }, new
                {
                    ClinicalDataLevel = ClinicalLevel.Subject,
                    Type = ClinicalFileType.PreviousOther
                });
            }

            #endregion

            #region 阅片人入组


            //阅片人入组   父层级未记录稽查（医生）
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(Enroll)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as Enroll;
                var doctor = await _dbContext.Doctor.FirstOrDefaultAsync(x => x.Id == entity.DoctorId);
                var readingCategoryList = await _dbContext.EnrollReadingCategory.Where(x => x.EnrollId == entity.Id).Select(t => t.ReadingCategory).ToListAsync();
                await InsertInspection<Enroll>(item.Entity as Enroll, type, x => new InspectionConvertDTO()
                {
                    ObjectRelationParentId = x.TrialId
                }, new
                {
                    //父层级的数据  暂时没有记录稽查  所以这里必须查
                    Name = doctor.FullName,
                    ChineseName = doctor.ChineseName,
                    Email = doctor.EMail,
                    IsUploadedACKSOW = entity.AttachmentId != Guid.Empty,

                    //子层级的数据 记录到父层级 必须查询  不然找上一条时数据不准
                    ReadingCategoryList = readingCategoryList
                });
            }

            //独立阅片人 设置阅片类型   这里对于操作人 不区分 添加 编辑 删除    只有设置（相当于更新）

            if (entitys.Any(x => x.Entity.GetType() == typeof(EnrollReadingCategory)))
            {
                var type = AuditOpt.Update;

                var addList = entitys.Where(x => x.Entity.GetType() == typeof(EnrollReadingCategory) && x.State == EntityState.Added).Select(t => t.Entity as EnrollReadingCategory).ToList();
                var deleteList = entitys.Where(x => x.Entity.GetType() == typeof(EnrollReadingCategory) && x.State == EntityState.Deleted).Select(t => t.Entity as EnrollReadingCategory).ToList();

                var first = addList.Union(deleteList).FirstOrDefault();

                var enrollId = first.EnrollId;

                var trialReadingCriterionId = first.TrialReadingCriterionId;

                Guid? trialId = Guid.Empty;

                if (first.Enroll != null)
                {
                    trialId = first.Enroll.TrialId;
                }
                else
                {
                    trialId = await _dbContext.Enroll.Where(x => x.Id == enrollId).Select(t => t.TrialId).FirstOrDefaultAsync();
                }


                await InsertInspection<EnrollReadingCategory>(first, type, x => new InspectionConvertDTO()
                {
                    //GeneralId  和ObjectRelationParentId 一样  会成环  所以查询的时候 需要排除自身 
                    GeneralId = IdentifierHelper.CreateGuid(enrollId.ToString(), trialReadingCriterionId.ToString()),

                    TrialId = trialId,

                    ObjectRelationParentId = enrollId,

                    ObjectRelationParentId2 = trialReadingCriterionId,

                    IsDistinctionInterface = false
                }, new
                {
                    ReadingCategoryList = addList.Select(t => t.ReadingCategory).ToList(),
                });
            }

            #endregion


            #region 阅片期临床数据

            // CRC  PM 临床数据
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingClinicalData)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ReadingClinicalData;
                var trialReadingCriterionId = await _dbContext.ReadModule.Where(t => t.Id == entity.ReadingId).Select(t => t.TrialReadingCriterionId).FirstOrDefaultAsync();
                var config = await _dbContext.ClinicalDataTrialSet.FindAsync(entity.ClinicalDataTrialSetId);

                string extraIndentification = string.Empty;

                if (type != AuditOpt.Update)
                {
                    switch (config.ClinicalDataLevel)
                    {
                        case ClinicalLevel.Subject:
                        case ClinicalLevel.SubjectVisit:
                            extraIndentification = "SubjectVisit";
                            break;
                        case ClinicalLevel.Study:
                            extraIndentification = "Study";
                            break;
                        case ClinicalLevel.ImageRead:
                        case ClinicalLevel.OncologyRead:
                            extraIndentification = "ImageRead";
                            break;
                    }
                }

                List<string> urlList = new List<string>()
                {
                    "ReadingClinicalData/addOrUpdateReadingClinicalData",
                    "ReadingClinicalData/deleteReadingClinicalDataPDF",
                };

                if (type == AuditOpt.Update && urlList.Contains(_userInfo.RequestUrl))
                {
                    switch (config.ClinicalDataLevel)
                    {
                        case ClinicalLevel.ImageRead:
                        case ClinicalLevel.OncologyRead:
                            extraIndentification = "ImageRead";
                            break;
                        default:
                            extraIndentification = "SubjectVisit";
                            break;
                    }
                }

                await InsertInspection<ReadingClinicalData>(item.Entity as ReadingClinicalData, type, x => new InspectionConvertDTO()
                {
                    TrialReadingCriterionId = trialReadingCriterionId,
                    IsDistinctionInterface = type == AuditOpt.Update ? true : false,

                    SubjectVisitId = x.IsVisit ? x.ReadingId : null,

                    ObjectRelationParentId = entity.ClinicalDataTrialSetId,
                    AuditIdentification = extraIndentification,

                    //ObjectRelationParentId2 = x.IsVisit == false?x.ReadingId:null
                },
                new { FileCountViewStr = config?.ClinicalDataLevel == ClinicalLevel.Subject && config?.ClinicalUploadType == ClinicalUploadType.Table ? "NA" : entity.FileCount.ToString() }
                );
            }


            //临床数据上传PDF

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingClinicalDataPDF)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ReadingClinicalDataPDF;

                string extraIndentification = string.Empty;
                if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager)
                {
                    extraIndentification = "/PM";
                }


                var clinicalData = await _dbContext.ReadingClinicalData.Where(t => t.Id == entity.ReadingClinicalDataId).FirstOrDefaultAsync();

                if (clinicalData == null)
                {

                    clinicalData = entitys.Where(x => x.Entity.GetType() == typeof(ReadingClinicalData)).Select(x => x.Entity as ReadingClinicalData).FirstOrDefault();
                }
                if (clinicalData != null)
                {
                    var clinicalDataTrialSet = await _dbContext.ClinicalDataTrialSet.Where(t => t.Id == clinicalData.ClinicalDataTrialSetId).FirstOrDefaultAsync();

                    SubjectVisit? visit = await _dbContext.SubjectVisit.Where(x => x.Id == clinicalData.ReadingId).FirstOrDefaultAsync();
                    TrialSite? siteInfo = null;
                    Subject? subject = null;

                    //阅片标准
                    var trialReadingCriterionIdList = await _dbContext.TrialClinicalDataSetCriterion.Where(t => t.TrialClinicalDataSetId == clinicalDataTrialSet.Id).Select(t => t.TrialReadingCriterionId).ToListAsync();


                    var trialReadingCriterionId = await _dbContext.ReadModule.Where(t => t.Id == clinicalData.ReadingId).Select(t => t.TrialReadingCriterionId).FirstOrDefaultAsync();


                    //阅片标准
                    var criterionNameList = await _dbContext.ReadingQuestionCriterionTrial.Where(t => trialReadingCriterionIdList.Contains(t.Id)).OrderBy(t => t.ShowOrder).Select(t => t.CriterionName).ToListAsync();



                    if (visit != null)
                    {
                        siteInfo = await _dbContext.TrialSite.Where(x => x.Id == visit.TrialSiteId).FirstOrDefaultAsync();
                        subject = await _dbContext.Subject.Where(x => x.Id == clinicalData.SubjectId).FirstOrDefaultAsync();
                    }

                    Guid? subjectVisitId = visit == null ? null : visit.Id;
                    await InsertInspection<ReadingClinicalDataPDF>(entity, type, x => new InspectionConvertDTO()
                    {
                        TrialReadingCriterionId = trialReadingCriterionId,
                        TrialId = clinicalData.TrialId,
                        SubjectId = clinicalData.SubjectId,
                        ExtraIndentification = extraIndentification,
                        SubjectVisitId = subjectVisitId,
                    }, new
                    {
                        SiteCode = siteInfo == null ? "" : siteInfo.TrialSiteCode,
                        SubjectCode = subject == null ? "" : subject.Code,
                        VisitName = visit == null ? "" : visit.VisitName,
                        clinicalDataTrialSet.ClinicalDataSetName,
                        clinicalDataTrialSet.ClinicalDataLevel,
                        clinicalDataTrialSet.ClinicalUploadType,
                        CriterionNames = string.Join(",", criterionNameList.Distinct()),
                        FileCount = 1,

                    });
                }
            }


            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ClinicalForm)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ClinicalForm;

                var clinicalDataTrialSet = await _dbContext.ClinicalDataTrialSet.Where(t => t.Id == entity.ClinicalDataTrialSetId).FirstOrDefaultAsync();

                SubjectVisit? visit = await _dbContext.SubjectVisit.Where(x => x.Id == entity.ReadingId).FirstOrDefaultAsync();
                TrialSite? siteInfo = null;
                Subject? subject = null;

                //阅片标准
                var trialReadingCriterionIdList = await _dbContext.TrialClinicalDataSetCriterion.Where(t => t.TrialClinicalDataSetId == clinicalDataTrialSet.Id).Select(t => t.TrialReadingCriterionId).ToListAsync();



                //阅片标准
                var criterionNameList = await _dbContext.ReadingQuestionCriterionTrial.Where(t => trialReadingCriterionIdList.Contains(t.Id)).OrderBy(t => t.ShowOrder).Select(t => t.CriterionName).ToListAsync();



                if (visit != null)
                {
                    siteInfo = await _dbContext.TrialSite.Where(x => x.Id == visit.TrialSiteId).FirstOrDefaultAsync();
                    subject = await _dbContext.Subject.Where(x => x.Id == entity.SubjectId).FirstOrDefaultAsync();
                }

                Guid? subjectVisitId = visit == null ? null : visit.Id;
                await InsertInspection<ClinicalForm>(entity, type, x => new InspectionConvertDTO()
                {
                    TrialId = entity.TrialId,
                    SubjectId = entity.SubjectId,
                    SubjectVisitId = subjectVisitId,
                }, new
                {
                    SiteCode = siteInfo == null ? "" : siteInfo.TrialSiteCode,
                    SubjectCode = subject == null ? "" : subject.Code,
                    VisitName = visit == null ? "" : visit.VisitName,
                    clinicalDataTrialSet.ClinicalDataSetName,
                    clinicalDataTrialSet.ClinicalDataLevel,
                    clinicalDataTrialSet.ClinicalUploadType,
                    CriterionNames = string.Join(",", criterionNameList.Distinct()),


                });
            }





            //系统临床数据配置

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ClinicalDataSystemSet)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ClinicalDataSystemSet;

                await InsertInspection<ClinicalDataSystemSet>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,
                });
            }



            //项目临床数据配置
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ClinicalDataTrialSet)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ClinicalDataTrialSet;

                var extraIdentification = string.Empty;
                if (_userInfo.RequestUrl == "configTrialBasicInfo/ConfigTrialProcessInfoConfirm")
                {
                    extraIdentification = "/ConfirmSelect";
                }
                else if (_userInfo.RequestUrl == "ClinicalDataSet/applyTrialClinical")
                {
                    extraIdentification = "/applyTrialClinical";
                }

                //获取配置的标准名称

                //List<string> trialDics = new List<string>();
                //var dictionaryIds = new List<Guid>();
                //if (entity.TrialDicList == null || entity.TrialDicList.Count == 0)
                //{
                //    dictionaryIds = await this._dbContext.TrialDictionary.Where(x => x.TrialId == entity.Id && x.KeyName == "Criterion").Select(x => x.DictionaryId).ToListAsync();
                //}
                //else
                //{
                //    dictionaryIds = entity.TrialDicList.Select(x => x.DictionaryId).ToList();
                //}
                //trialDics = await this._dbContext.Dictionary.Where(x => dictionaryIds.Contains(x.Id)).Select(x => x.ValueCN).ToListAsync();

                var trialReadingCritiralIdList = new List<Guid>();

                var criterionNameList = new List<string>();

                if (entity.TrialClinicalDataSetCriteriaList == null || entity.TrialClinicalDataSetCriteriaList.Count() == 0)
                {
                    criterionNameList = await _dbContext.TrialClinicalDataSetCriterion.Where(t => t.TrialClinicalDataSetId == entity.Id).Select(t => t.TrialReadingCriterion.CriterionName).ToListAsync();
                }
                else
                {
                    var ids = entity.TrialClinicalDataSetCriteriaList.Select(t => t.TrialReadingCriterionId).ToList();
                    criterionNameList = await _dbContext.ReadingQuestionCriterionTrial.Where(t => ids.Contains(t.Id)).Select(t => t.CriterionName).ToListAsync();
                }

                await InsertInspection<ClinicalDataTrialSet>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,
                    ObjectRelationParentId = entity.TrialId,
                    ExtraIndentification = extraIdentification,
                }, new
                {
                    CriterionNames = criterionNameList?.Count() > 0 ? string.Join(",", criterionNameList) : string.Empty
                });
            }



            //临床数据问题

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TrialClinicalQuestion)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as TrialClinicalQuestion;

                var trialId = await _dbContext.ClinicalDataTrialSet.Where(t => t.Id == entity.TrialClinicalId).Select(t => t.TrialId).FirstOrDefaultAsync();
                var GroupName = entity.GroupId == null ? entity.QuestionName : _dbContext.TrialClinicalQuestion.Where(t => t.Id == entity.GroupId).Select(t => t.QuestionName).FirstOrDefault();
                var GroupEnName = entity.GroupId == null ? entity.QuestionEnName : _dbContext.TrialClinicalQuestion.Where(t => t.Id == entity.GroupId).Select(t => t.QuestionEnName).FirstOrDefault();
                await InsertInspection<TrialClinicalQuestion>(entity, type, x => new InspectionConvertDTO()
                {
                    TrialId = trialId,
                },
                  new
                  {
                      GroupName = GroupName,
                      GroupEnName = GroupEnName,
                  }
                );
            }


            //临床数据表格问题
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TrialClinicalTableQuestion)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as TrialClinicalTableQuestion;

                var trialId = await _dbContext.ClinicalDataTrialSet.Where(t => t.Id == entity.TrialClinicalId).Select(t => t.TrialId).FirstOrDefaultAsync();
                await InsertInspection<TrialClinicalTableQuestion>(entity, type, x => new InspectionConvertDTO()
                {
                    TrialId = trialId,
                }

                );
            }



            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingConsistentClinicalData)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ReadingConsistentClinicalData;

                var config = await _dbContext.ClinicalDataTrialSet.FindAsync(entity.ClinicalDataTrialSetId);

                await InsertInspection<ReadingConsistentClinicalData>(item.Entity as ReadingConsistentClinicalData, type, x => new InspectionConvertDTO()
                {

                    IsDistinctionInterface = type == AuditOpt.Update ? true : false,

                    SubjectVisitId = x.IsVisit ? x.ReadingId : null,

                    ObjectRelationParentId = entity.ClinicalDataTrialSetId,

                    //ObjectRelationParentId2 = x.IsVisit == false?x.ReadingId:null
                }, new { FileCountViewStr = config?.ClinicalDataLevel == ClinicalLevel.Subject && config?.ClinicalUploadType == ClinicalUploadType.Table ? "NA" : entity.FileCount.ToString() });
            }

            //阅片期计划
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingPeriodSet)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ReadingPeriodSet;

                var siteCodes = string.Empty;
                if (entity.ReadingScope == ReadingScopeEnum.Site)
                {
                    var siteIds = entity.ReadingPeriodSites.Select(t => t.TrialSiteId).ToList();
                    if (siteIds == null || siteIds.Count == 0)
                    {
                        siteIds = await _dbContext.ReadingPeriodSite.Where(c => c.ReadingPeriodSetId == entity.Id).Select(t => t.TrialSiteId).ToListAsync();
                    }
                    var nameList = _dbContext.TrialSite.Where(c => c.TrialId == entity.TrialId && siteIds.Contains(c.Id)).Select(t => t.TrialSiteCode).ToList();

                    siteCodes = String.Join(',', nameList);
                }

                await InsertInspection<ReadingPeriodSet>(item.Entity as ReadingPeriodSet, type, x => new InspectionConvertDTO()
                {
                    ObjectRelationParentId = x.VisitStageId,
                    ObjectRelationParentId2 = entity.TrialReadingCriterionId,


                }, new
                {
                    SiteCodes = siteCodes
                });
            }

            #region 阅片期临时数据不记录
            //foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingPeriodPlan)))
            //{
            //    var entity = item.Entity as ReadingPeriodPlan;

            //    if (entity.ReadingPeriodSet == null)
            //    {
            //        entity.ReadingPeriodSet = _dbContext.ReadingPeriodSet.Find(entity.ReadingPeriodSetId);
            //    }

            //    await InsertInspection<ReadingPeriodPlan>(item.Entity as ReadingPeriodPlan, type, x => new InspectionConvertDTO()
            //    {
            //        GeneralId = x.Id,
            //        SubjectVisitId = x.SubjectVisitId,
            //    }, new
            //    {
            //        entity.ReadingPeriodSet.ReadingPeriodName,
            //        entity.ReadingPeriodSet.EffectOfTime,
            //        entity.ReadingPeriodSet.ExpirationDate
            //    });
            //}

            #endregion


            //阅片期
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadModule)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ReadModule;

                string extraIndentification = string.Empty;
                object objData = new { };


                //临床数据表单确认
                if (_userInfo.RequestUrl == "ClinicalAnswer/cRCConfirmClinical")
                {
                    extraIndentification = "/" + _userInfo.RequestUrl;
                    var readModuleCriterionFromList = entitys.Where(x => x.Entity.GetType() == typeof(ReadModuleCriterionFrom)).ToList();
                    if (readModuleCriterionFromList.Count() > 0)
                    {
                        var readModuleCriterionFrom = readModuleCriterionFromList.FirstOrDefault().Entity as ReadModuleCriterionFrom;


                        var clinicalFormIds = new List<Guid>();
                        var criterionIds = new List<Guid>();
                        readModuleCriterionFromList.ForEach(x =>
                        {
                            var form = x.Entity as ReadModuleCriterionFrom;
                            clinicalFormIds.Add(form.ClinicalFormId);
                        });

                        var clinicalFormList = await _dbContext.ClinicalForm.Where(t => clinicalFormIds.Contains(t.Id)).ToListAsync();

                        var clinicalDataTrialSetIds = clinicalFormList.Select(x => x.ClinicalDataTrialSetId).ToList().Distinct();


                        var readModule = await _dbContext.ReadModule.Where(t => t.Id == readModuleCriterionFrom.ReadModuleId).Include(x => x.SubjectVisit).FirstOrDefaultAsync();
                        var latestScanDate = readModule.SubjectVisit.LatestScanDate;

                        var clinicalDataTrialSetList = await _dbContext.ClinicalDataTrialSet.Where(t => clinicalDataTrialSetIds.Contains(t.Id)).ToListAsync();


                        var clinicalSetIds = clinicalDataTrialSetList.Select(x => x.Id).ToList();

                        // 项目临床数据和标准的关联
                        var trialReadingCriterionIdList = await _dbContext.TrialClinicalDataSetCriterion.Where(x => clinicalSetIds.Contains(x.TrialClinicalDataSetId)).Select(x => x.TrialReadingCriterionId).Distinct().ToListAsync();

                        // 标准
                        var criterionNameList = await _dbContext.ReadingQuestionCriterionTrial.Where(t => trialReadingCriterionIdList.Contains(t.Id)).OrderBy(t => t.ShowOrder).Select(t => t.CriterionName).ToListAsync();



                        Subject subject = await _dbContext.Subject.Where(x => x.Id == readModule.SubjectId).FirstOrDefaultAsync();
                        TrialSite siteInfo = await _dbContext.TrialSite.Where(x => x.Id == subject.TrialSiteId).FirstOrDefaultAsync();

                        var clinicalDataSetNameList = clinicalDataTrialSetList.Select(x => x.ClinicalDataSetName).ToList();
                        objData = new
                        {
                            SiteCode = siteInfo == null ? "" : siteInfo.TrialSiteCode,
                            SubjectCode = subject == null ? "" : subject.Code,
                            LatestScanDate = latestScanDate,
                            ClinicalDataSetName = string.Join(",", clinicalDataSetNameList),
                            ClinicalDataLevel = clinicalDataTrialSetList.Select(x => x.ClinicalDataLevel).FirstOrDefault(),
                            ClinicalUploadType = clinicalDataTrialSetList.Select(x => x.ClinicalUploadType).FirstOrDefault(),
                            CriterionNames = string.Join(",", criterionNameList.Distinct()),
                            RecordNumber = readModuleCriterionFromList.Count(),

                        };
                    }
                }


                List<string> urlList = new List<string>() {
                "ClinicalAnswer/cRCCancelConfirmClinical",
                "ClinicalAnswer/PMConfirmClinical"
                };



                if (urlList.Contains(_userInfo.RequestUrl))
                {
                    extraIndentification = "/" + _userInfo.RequestUrl;
                    string status = string.Empty;
                    if (!entity.IsCRCConfirm && _userInfo.RequestUrl == "ClinicalAnswer/PMConfirmClinical")
                    {
                        status = "已撤回";
                        extraIndentification += "/revocation";
                    }
                    else if (entity.IsPMConfirm && _userInfo.RequestUrl == "ClinicalAnswer/PMConfirmClinical")
                    {
                        status = "已核对";
                        extraIndentification += "/Confirm";
                    }


                    var readModuleCriterionFrom = await _dbContext.ReadModuleCriterionFrom.Where(t => t.ReadModuleId == entity.Id).FirstOrDefaultAsync();
                    var latestScanDate = await _dbContext.ReadModule.Where(t => t.Id == entity.Id).Select(x => x.SubjectVisit.LatestScanDate).FirstOrDefaultAsync();
                    TrialSite? siteInfo = null;
                    Subject? subject = null;
                    //阅片标准


                    var clinicalFormIds = await _dbContext.ReadModuleCriterionFrom.Where(x => x.ReadModuleId == entity.Id).Select(x => x.ClinicalFormId).ToListAsync();
                    var clinicalDataTrialSetIds = await _dbContext.ClinicalForm.Where(x => clinicalFormIds.Contains(x.Id)).Select(x => x.ClinicalDataTrialSetId).Distinct().ToListAsync();

                    // 临床数据
                    var clinicalDataTrialSetList = await _dbContext.ClinicalDataTrialSet.Where(x => clinicalDataTrialSetIds.Contains(x.Id)).ToListAsync();

                    var clinicalSetIds = clinicalDataTrialSetList.Select(x => x.Id).ToList();

                    // 项目临床数据和标准的关联
                    var trialReadingCriterionIdList = await _dbContext.TrialClinicalDataSetCriterion.Where(x => clinicalSetIds.Contains(x.TrialClinicalDataSetId)).Select(x => x.TrialReadingCriterionId).Distinct().ToListAsync();

                    // 标准
                    var criterionNameList = await _dbContext.ReadingQuestionCriterionTrial.Where(t => trialReadingCriterionIdList.Contains(t.Id)).OrderBy(t => t.ShowOrder).Select(t => t.CriterionName).ToListAsync();



                    subject = await _dbContext.Subject.Where(x => x.Id == entity.SubjectId).FirstOrDefaultAsync();
                    siteInfo = await _dbContext.TrialSite.Where(x => x.Id == subject.TrialSiteId).FirstOrDefaultAsync();

                    var clinicalDataSetNameList = clinicalDataTrialSetList.Select(x => x.ClinicalDataSetName).ToList().Distinct();





                    objData = new
                    {
                        SiteCode = siteInfo == null ? "" : siteInfo.TrialSiteCode,
                        SubjectCode = subject == null ? "" : subject.Code,
                        LatestScanDate = latestScanDate,
                        ClinicalDataSetName = string.Join(",", clinicalDataSetNameList),
                        ClinicalDataLevel = clinicalDataTrialSetList.Select(x => x.ClinicalDataLevel).FirstOrDefault(),
                        ClinicalUploadType = clinicalDataTrialSetList.Select(x => x.ClinicalUploadType).FirstOrDefault(),
                        CriterionNames = string.Join(",", criterionNameList.Distinct()),
                        RecordNumber = clinicalFormIds.Count(),
                        Status = status,

                    };
                }



                await InsertInspection<ReadModule>(item.Entity as ReadModule, type, x => new InspectionConvertDTO()
                {
                    ObjectRelationParentId = entity.SubjectVisitId,

                    ObjectRelationParentId2 = entity.TrialReadingCriterionId,
                    ExtraIndentification = extraIndentification,
                    //SubjectVisitId = x.SubjectVisitId,
                    IsDistinctionInterface = false,
                }, objData);
            }


            #endregion


            #region 阅片

            //用户添加
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(UserRole)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as UserRole;

                var extraIdentification = string.Empty;

                //保存其他个性化配置
                if (_userInfo.RequestUrl == "UserWLTemplate/setAutoCutNextTask")
                {
                    extraIdentification = "/Personalization";
                }

                await InsertInspection<UserRole>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,
                    ExtraIndentification = extraIdentification
                }, new
                {
                    UserRealName = entity.FullName,
                }
                );
            }
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(IdentityUser)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as IdentityUser;

                var extraIdentification = string.Empty;

                //保存其他个性化配置
                if (_userInfo.RequestUrl == "UserWLTemplate/setAutoCutNextTask")
                {
                    extraIdentification = "/Personalization";
                }

                await InsertInspection<IdentityUser>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,
                    ExtraIndentification = extraIdentification
                }, new
                {
                    UserRealName = entity.FullName,
                }
                );
            }


            //分配规则
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TaskAllocationRule)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as TaskAllocationRule;

                var userRealName = await _dbContext.User.Where(x => x.Id == entity.DoctorUserId).Select(x => x.FullName).FirstOrDefaultAsync();

                await InsertInspection<TaskAllocationRule>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,

                    ObjectRelationParentId = entity.EnrollId,

                    ObjectRelationParentId2 = entity.DoctorUserId

                }, new
                {
                    UserRealName = userRealName
                });
            }

            //  suject  医生绑定关系
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(SubjectUser)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as SubjectUser;

                await InsertInspection<SubjectUser>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,

                    ObjectRelationParentId = entity.SubjectId,

                    ObjectRelationParentId2 = entity.DoctorUserId,

                    ObjectRelationParentId3 = entity.TrialReadingCriterionId,

                }, new { ArmToTask = entity.ArmEnum });
            }


            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(SubjectCanceDoctor)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as SubjectCanceDoctor;

                await InsertInspection<SubjectCanceDoctor>(entity, type, x => new InspectionConvertDTO()
                {

                    ObjectRelationParentId = entity.SubjectId,


                    ObjectRelationParentId3 = entity.TrialReadingCriterionId,

                }, new { });
            }



            //申请重阅记录表
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(VisitTaskReReading)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as VisitTaskReReading;

                var extraIdentification = string.Empty;

                var reason = entity.RequestReReadingReason;
                switch (_userInfo.RequestUrl)
                {
                    case "VisitTask/applyReReading":

                        extraIdentification = "/" + (int)entity.RequestReReadingType;
                        break;

                    case "VisitTask/ConfirmReReading":

                        if (_userInfo.UserTypeEnumInt == (int)UserTypeEnum.ProjectManager || _userInfo.UserTypeEnumInt == (int)UserTypeEnum.APM)
                        {
                            extraIdentification = "/" + 1;
                        }
                        else
                        {
                            extraIdentification = "/" + 2;
                        }
                        reason = entity.RequestReReadingRejectReason;

                        if (entity.RequestReReadingResultEnum == RequestReReadingResult.Agree)
                        {
                            extraIdentification = extraIdentification + "/" + 1;

                        }
                        else if (entity.RequestReReadingResultEnum == RequestReReadingResult.Reject)
                        {
                            extraIdentification = extraIdentification + "/" + 2;
                        }
                        break;
                }


                await InsertInspection<VisitTaskReReading>(entity, type, x => new InspectionConvertDTO()
                {
                    VisitTaskId = entity.OriginalReReadingTaskId,

                    Reason = reason,

                    ObjectRelationParentId = entity.OriginalReReadingTaskId,


                    ExtraIndentification = extraIdentification,

                });
            }


            //一致性分析规则

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TaskConsistentRule)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as TaskConsistentRule;


                var extraIdentification = string.Empty;

                //自身一致性分析
                if (entity.IsSelfAnalysis == true)
                {
                    extraIdentification = "/" + 1;

                }
                //组件一致性分析
                else
                {
                    extraIdentification = "/" + 2;
                }

                await InsertInspection<TaskConsistentRule>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = true,

                    ObjectRelationParentId = entity.TrialId,

                    ObjectRelationParentId2 = entity.TrialReadingCriterionId,

                    ExtraIndentification = extraIdentification,
                });
            }



            #endregion



            #region 阅片结果


            #region  暂时不区分标准

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingTaskQuestionMark)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ReadingTaskQuestionMark;

                var tableQuestionAnswer = entitys.Where(x => x.Entity.GetType() == typeof(ReadingTableQuestionAnswer)).Select(x => x.Entity as ReadingTableQuestionAnswer)
                    .Where(x => x.RowId == entity.RowId && x.TableQuestionId == entity.TableQuestionId).FirstOrDefault();
                var answer = string.Empty;




                if (tableQuestionAnswer != null)
                {


                    var tableQuesionList = await _dbContext.ReadingTableQuestionTrial.Where(t => t.Id == tableQuestionAnswer.TableQuestionId).Select(t =>
                    new
                    {
                        TrialReadingCriterionId = t.ReadingQuestionTrial.ReadingQuestionCriterionTrialId, //标准Id
                        Type = t.ReadingQuestionTrial.QuestionName, //病灶类型
                        t.Unit,
                        t.CustomUnit,
                        t.DictionaryCode,
                        t.QuestionName,
                        t.QuestionEnName,
                        QuestionId = t.Id,
                        t.ShowOrder,
                        AnswerType = t.Type,
                    })
                     .OrderBy(t => t.ShowOrder).FirstOrDefaultAsync();

                    List<UnitData> unitDataList = (await _dbContext.Dictionary.Where(x => x.Parent.Code == "ValueUnit").Where(x => x.Code != "0").ToListAsync()).Select(x => new UnitData()
                    {

                        Unit = (ValueUnit)int.Parse(x.Code),
                        UnitName = x.Value.ToString(),
                    }).ToList();

                    answer = Translationunit(tableQuesionList.AnswerType, tableQuesionList.Unit, tableQuesionList.CustomUnit, unitDataList, tableQuestionAnswer.Answer);
                }

                var rowMark = await _dbContext.ReadingTableAnswerRowInfo.Where(x => x.Id == entity.RowId).Select(x => x.RowMark).FirstOrDefaultAsync();

                var tableQuestionName = await _dbContext.ReadingTableQuestionTrial.Where(x => x.Id == entity.TableQuestionId).Select(x => _userInfo.IsEn_Us ? x.QuestionEnName : x.QuestionName).FirstOrDefaultAsync();
                var questionName = await _dbContext.ReadingQuestionTrial.Where(x => x.Id == entity.QuestionId).Select(x => _userInfo.IsEn_Us ? x.QuestionEnName : x.QuestionName).FirstOrDefaultAsync();
                var liverSegmentation = await _dbContext.ReadingTableQuestionAnswer.Where(x => x.RowId == entity.RowId && x.ReadingTableQuestionTrial.QuestionMark == QuestionMark.liverSegmentation).Select(x => x.Answer).FirstOrDefaultAsync();

                var generalId = new Guid();
                if (entity.MarkId != null)
                {
                    generalId = entity.MarkId.Value;
                }
                else if (entity.TableQuestionId == null && entity.QuestionId == null)
                {
                    generalId = entity.Id;
                }

                else
                {
                    generalId = IdentifierHelper.CreateGuid(entity.VisitTaskId.ToString(), entity.QuestionId.ToString(), entity.RowId.ToString(), entity.TableQuestionId.ToString(), "ReadingTaskQuestionMark");
                }


                bool isDistinctionInterface = true;
                var customPrefix = string.Empty;

                // 对于一个标记绑定两个问题的不计稽查
                var existsMark = await _dbContext.ReadingTaskQuestionMark.AnyAsync(t => t.MarkId == entity.MarkId);

                // 自定义表格 和问题添加标记的时候 要记录为 添加标记
                if ((_userInfo.RequestUrl == "SaveTaskQuestion/-10"
                    || _userInfo.RequestUrl == "saveTableQuestionMark/-10") && type == "Add" && !existsMark)
                {
                    isDistinctionInterface = false;
                    customPrefix = "ReadingImageTask/submitCustomTag";
                }

                await InsertInspection<ReadingTaskQuestionMark>(entity, type, x => new InspectionConvertDTO()
                {
                    VisitTaskId = entity.VisitTaskId,
                    GeneralId = generalId,
                    ObjectRelationParentId = entity.VisitTaskId,
                    IsDistinctionInterface = isDistinctionInterface,
                    CustomPrefix = customPrefix

                }, new
                {
                    QuestionName = questionName,
                    RowMark = rowMark,
                    TableQuestionName = tableQuestionName,
                    Answer = answer,
                    LiverSegmentation = liverSegmentation,
                });
            }


            //Segmentation

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(Segmentation)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as Segmentation;


                var visitTask = await _dbContext.VisitTask.Where(x => x.Id == entity.VisitTaskId).FirstOrDefaultAsync();

                await InsertInspection<Segmentation>(entity, type, x => new InspectionConvertDTO()
                {
                    TrialReadingCriterionId = visitTask != null ? visitTask.TrialReadingCriterionId : null,
                });
            }


            //Segment

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(Segment)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as Segment;

                var visitTask = await _dbContext.VisitTask.Where(x => x.Id == entity.VisitTaskId).FirstOrDefaultAsync();


                var segmentation = await _dbContext.Segmentation.Where(x => x.Id == entity.SegmentationId).FirstOrDefaultAsync();

                await InsertInspection<Segment>(entity, type, x => new InspectionConvertDTO()
                {
                    SubjectId = segmentation != null ? segmentation.SubjectId : null,
                    SubjectVisitId = segmentation != null ? segmentation.SubjectVisitId : null,
                    TrialReadingCriterionId = visitTask != null ? visitTask.TrialReadingCriterionId : null,
                });
            }

            //SegmentBinding

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(SegmentBinding)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as SegmentBinding;


                var tableQuestionAnswer = entitys.Where(x => x.Entity.GetType() == typeof(ReadingTableQuestionAnswer)).Select(x => x.Entity as ReadingTableQuestionAnswer)
                  .Where(x => x.RowId == entity.RowId && x.TableQuestionId == entity.TableQuestionId).FirstOrDefault();
                var answer = string.Empty;

                List<UnitData> unitDataList = (await _dbContext.Dictionary.Where(x => x.Parent.Code == "ValueUnit").Where(x => x.Code != "0").ToListAsync()).Select(x => new UnitData()
                {

                    Unit = (ValueUnit)int.Parse(x.Code),
                    UnitName = x.Value.ToString(),
                }).ToList();
                if (tableQuestionAnswer != null)
                {


                    var tableQuesionList = await _dbContext.ReadingTableQuestionTrial.Where(t => t.Id == tableQuestionAnswer.TableQuestionId).Select(t =>
                    new
                    {
                        TrialReadingCriterionId = t.ReadingQuestionTrial.ReadingQuestionCriterionTrialId, //标准Id
                        Type = t.ReadingQuestionTrial.QuestionName, //病灶类型
                        t.Unit,
                        t.CustomUnit,
                        t.DictionaryCode,
                        t.QuestionName,
                        t.QuestionEnName,
                        QuestionId = t.Id,
                        t.ShowOrder,
                        AnswerType = t.Type,
                    })
                     .OrderBy(t => t.ShowOrder).FirstOrDefaultAsync();


                    answer = Translationunit(tableQuesionList.AnswerType, tableQuesionList.Unit, tableQuesionList.CustomUnit, unitDataList, tableQuestionAnswer.Answer);
                }
                else
                {
                    var questionAnswer = entitys.Where(x => x.Entity.GetType() == typeof(ReadingTaskQuestionAnswer)).Select(x => x.Entity as ReadingTaskQuestionAnswer)
                    .Where(x => x.VisitTaskId == entity.VisitTaskId && x.ReadingQuestionTrialId == entity.QuestionId).FirstOrDefault();

                    if (questionAnswer != null)
                    {
                        var quesionInfo = await _dbContext.ReadingQuestionTrial.Where(t => t.Id == questionAnswer.ReadingQuestionTrialId).Select(t =>
                       new
                       {

                           t.Unit,
                           t.CustomUnit,
                           t.DictionaryCode,
                           t.QuestionName,
                           t.QuestionEnName,
                           QuestionId = t.Id,
                           t.ShowOrder,
                           AnswerType = t.Type,
                       })
                        .OrderBy(t => t.ShowOrder).FirstOrDefaultAsync();

                        answer = Translationunit(quesionInfo.AnswerType, quesionInfo.Unit, quesionInfo.CustomUnit, unitDataList, questionAnswer.Answer);
                    }
                }

                var rowMark = await _dbContext.ReadingTableAnswerRowInfo.Where(x => x.Id == entity.RowId).Select(x => x.RowMark).FirstOrDefaultAsync();




                var segmentation = await _dbContext.Segmentation.Where(x => x.Id == entity.SegmentationId).Include(x => x.VisitTask).FirstOrDefaultAsync() ?? new Segmentation() { };

                var segment = await _dbContext.Segment.Where(x => x.Id == entity.SegmentId).FirstOrDefaultAsync() ?? new Segment() { };

                var tableQuestionName = await _dbContext.ReadingTableQuestionTrial.Where(x => x.Id == entity.TableQuestionId).Select(x => _userInfo.IsEn_Us ? x.QuestionEnName : x.QuestionName).FirstOrDefaultAsync();
                var questionName = await _dbContext.ReadingQuestionTrial.Where(x => x.Id == entity.QuestionId).Select(x => _userInfo.IsEn_Us ? x.QuestionEnName : x.QuestionName).FirstOrDefaultAsync();


                Guid? trialReadingCriterionId = null;
                if (segmentation.VisitTask != null)
                {
                    trialReadingCriterionId = segmentation.VisitTask.TrialReadingCriterionId;
                }



                await InsertInspection<SegmentBinding>(entity, type, x => new InspectionConvertDTO()
                {
                    TrialReadingCriterionId = trialReadingCriterionId,
                }, new
                {
                    segmentation.SegmentationName,
                    segmentation.SEGUrl,
                    segment.SegmentName,
                    segment.SegmentNumber,
                    segment.ColorRgb,

                    QuestionName = questionName,
                    RowMark = rowMark,
                    TableQuestionName = tableQuestionName,
                    Answer = answer,
                });
            }


            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingNoneDicomMark)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ReadingNoneDicomMark;

                var selfDefineIdentification = "ReadingImageTask/submitCustomTag/ReadingTaskQuestionMark/";
                if (type == "Deleted")
                {
                    selfDefineIdentification = "ReadingImageTask/deleteCustomTag/ReadingTaskQuestionMark/";
                }

                await InsertInspection<ReadingNoneDicomMark>(entity, type, x => new InspectionConvertDTO()
                {
                    SelfDefineIdentification = selfDefineIdentification + type

                }, new
                {

                });
            }

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingNoneDicomMarkBinding)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ReadingNoneDicomMarkBinding;
                var selfDefineIdentification = string.Empty;

                var answer = string.Empty;
                Guid? questionId = Guid.Empty;
                string tableQuestionName = string.Empty;
                var rowMark = string.Empty;
                if (entity.TableQuestionId == null)
                {
                    switch (type)
                    {
                        case "Add":
                            selfDefineIdentification = "SaveTaskQuestion/-10/ReadingTaskQuestionAnswer/Add/AddMark";
                            break;
                        case "Update":
                            selfDefineIdentification = "SaveTaskQuestion/-10/ReadingTaskQuestionAnswer/Add/UpdateMark";
                            break;
                        case "Deleted":
                            selfDefineIdentification = "SaveTaskQuestion/-10/ReadingTaskQuestionAnswer/Add/DeleteMark";
                            break;
                    }

                    questionId = entity.QuestionId;
                    answer = entitys.Where(x => x.Entity.GetType() == typeof(ReadingTaskQuestionAnswer)).Select(x => x.Entity as ReadingTaskQuestionAnswer).Select(x => x.Answer).FirstOrDefault();
                }
                else
                {
                    switch (type)
                    {
                        case "Add":
                            selfDefineIdentification = "saveTableQuestionMark/-10/ReadingTableQuestionAnswer/Add/AddMark";
                            break;
                        case "Update":
                            selfDefineIdentification = "saveTableQuestionMark/-10/ReadingTableQuestionAnswer/Add/UpdateMark";
                            break;
                        case "Deleted":
                            selfDefineIdentification = "saveTableQuestionMark/-10/ReadingTableQuestionAnswer/Add/DeleteMark";
                            break;
                    }
                    questionId = entity.QuestionId;
                    tableQuestionName = _dbContext.ReadingTableQuestionTrial.Where(x => x.Id == entity.TableQuestionId).Select(x => _userInfo.IsEn_Us ? x.QuestionEnName : x.QuestionName).FirstOrDefault();
                    answer = entitys.Where(x => x.Entity.GetType() == typeof(ReadingTableQuestionAnswer)).Select(x => x.Entity as ReadingTableQuestionAnswer).Select(x => x.Answer).FirstOrDefault();
                    rowMark = _dbContext.ReadingTableAnswerRowInfo.Where(x => x.Id == entity.RowId).Select(x => x.RowMark).FirstOrDefault();
                }




                var mark = entitys.Where(x => x.Entity.GetType() == typeof(ReadingNoneDicomMark)).Select(x => x.Entity as ReadingNoneDicomMark).FirstOrDefault();
                if (mark == null)
                {
                    mark = await _dbContext.ReadingNoneDicomMark.Where(x => x.Id == entity.NoneDicomMarkId).FirstOrDefaultAsync();

                }
                var QuestionName = string.Empty;
                if (answer != null)
                {
                    QuestionName = _dbContext.ReadingQuestionTrial.Where(x => x.Id == questionId).Select(x => _userInfo.IsEn_Us ? x.QuestionEnName : x.QuestionName).FirstOrDefault();
                }

                await InsertInspection<ReadingNoneDicomMarkBinding>(entity, type, x => new InspectionConvertDTO()
                {
                    SelfDefineIdentification = selfDefineIdentification,

                }, new
                {
                    RowMark = rowMark,
                    TableQuestionName = tableQuestionName,
                    MarkName = mark == null || type == "Deleted" ? string.Empty : mark.OrderMarkName,
                    PicturePath = mark == null ? string.Empty : mark.PicturePath,
                    QuestionName = QuestionName,
                    QuestinonAnswer = answer
                });
            }

            //保存影像质量   多条记录，只记录一条稽查   
            if (entitys.Any(x => x.Entity.GetType() == typeof(ReadingTaskQuestionAnswer)))
            {
                //判断是否不需要记录稽查
                if (_userInfo.IsNotNeedInspection)
                {
                    _userInfo.IsNotNeedInspection = false;

                }
                else
                {
                    // 保存影像质量 、  修改整体肿瘤评估结果 、  非dicom 保存访视阅片结果 、附加评估
                    if (_userInfo.RequestUrl == "ReadingImageTask/changeDicomReadingQuestionAnswer"
                        || _userInfo.RequestUrl == "ReadingImageTask/saveImageQuality"
                         || _userInfo.RequestUrl.Contains("SaveTaskQuestion")
                        || _userInfo.RequestUrl == "ReadingImageTask/saveVisitTaskQuestions"
                        || _userInfo.RequestUrl == "ReadingImageTask/changeCalculationAnswer"
                        || _userInfo.RequestUrl == "ReadingImageTask/submitTaskAdditionalQuestion")
                    {
                        var type = AuditOpt.Add;

                        List<UnitData> unitDataList = (await _dbContext.Dictionary.Where(x => x.Parent.Code == "ValueUnit").Where(x => x.Code != "0").ToListAsync()).Select(x => new UnitData()
                        {

                            Unit = (ValueUnit)int.Parse(x.Code),
                            UnitName = x.Value.ToString(),
                        }).ToList();
                        var extraIdentification = string.Empty;

                        //具体的答案
                        var taskQuestionAnswerList = entitys.Where(x => x.Entity.GetType() == typeof(ReadingTaskQuestionAnswer)).Select(t => t.Entity as ReadingTaskQuestionAnswer).ToList();

                        //获取问题名称 组合成数组
                        var quesionList = await _dbContext.ReadingQuestionTrial.Where(t => taskQuestionAnswerList.Select(k => k.ReadingQuestionTrialId).Contains(t.Id)).IgnoreQueryFilters().Select(t => new
                        {
                            QuestionName = t.QuestionName,
                            t.QuestionEnName,
                            QuestionId = t.Id,
                            t.DictionaryCode,
                            t.Unit,
                            t.CustomUnit,
                            t.ShowOrder,
                            AnswerType = t.Type,
                        }).OrderBy(t => t.ShowOrder).ToListAsync();


                        var firstEntity = taskQuestionAnswerList.First();

                        var cloneEntity = firstEntity.Clone();



                        //保证Id 唯一
                        cloneEntity.Id = IdentifierHelper.CreateGuid(firstEntity.ReadingQuestionCriterionTrialId.ToString(), firstEntity.ReadingQuestionTrialId.ToString(), firstEntity.VisitTaskId.ToString());


                        dynamic tableQuesionAndAnswerList = null;
                        //自定义特有标识
                        if (await _dbContext.ReadingQuestionCriterionTrial.AnyAsync(t => t.Id == firstEntity.ReadingQuestionCriterionTrialId && t.CriterionType == CriterionType.SelfDefine))
                        {
                            //extraIdentification = "/Self";

                            //还会把病灶问题答案更新

                            var tableQuestionAnswerList = entitys.Where(x => x.Entity.GetType() == typeof(ReadingTableQuestionAnswer)).Select(t => t.Entity as ReadingTableQuestionAnswer).ToList();


                            //获取表格问题名称 组合成数组
                            var tableQuesionList = await _dbContext.ReadingTableQuestionTrial.Where(t => tableQuestionAnswerList.Select(k => k.TableQuestionId).Contains(t.Id)).Select(t =>
                            new
                            {
                                TrialReadingCriterionId = t.ReadingQuestionTrial.ReadingQuestionCriterionTrialId, //标准Id
                                Type = t.ReadingQuestionTrial.QuestionName, //病灶类型
                                t.Unit,
                                t.CustomUnit,
                                t.DictionaryCode,
                                t.QuestionName,
                                t.QuestionEnName,
                                QuestionId = t.Id,
                                t.ShowOrder,
                                AnswerType = t.Type,
                            })
                                .OrderBy(t => t.ShowOrder).ToListAsync();

                            tableQuesionAndAnswerList = tableQuestionAnswerList.Join(tableQuesionList, t => t.TableQuestionId, u => u.QuestionId, (t, u) =>
                                   new
                                   {
                                       //如果问题类型是附件 特殊处理 方便前端解析
                                       Answer = Translationunit(u.AnswerType, u.Unit, u.CustomUnit, unitDataList, t.Answer),

                                       u.QuestionName,
                                       u.QuestionEnName,
                                       u.DictionaryCode,
                                       u.ShowOrder,
                                       t.RowId
                                   }
                                   ).OrderBy(t => t.RowId).ThenBy(t => t.ShowOrder).ToList();



                        }

                        var markList = entitys.Where(x => x.Entity.GetType() == typeof(ReadingTaskQuestionMark)).Select(x => x.Entity as ReadingTaskQuestionMark).ToList();

                        var questionids = taskQuestionAnswerList.Select(x => x.ReadingQuestionTrialId as Guid?).ToList();
                        var mark = markList.Where(x => questionids.Contains(x.QuestionId)).FirstOrDefault();
                        var markName = string.Empty;
                        if (mark != null)
                        {
                            markName = mark.OrderMarkName;
                        }

                        string picturePath = mark != null ? mark.PicturePath : string.Empty;

                        string otherPicturePath = mark != null ? mark.OtherPicturePath : string.Empty;

                        if (_userInfo.AuditIdentification == "DeleteMark")
                        {
                            markName = string.Empty;
                            picturePath = string.Empty;
                            otherPicturePath = string.Empty;
                        }

                        // 这里本来就批量展示问题的 现在又需要单个展示
                        var thisQuestinonAnswer = entitys.Where(x => x.Entity.GetType() == typeof(ReadingTaskQuestionAnswer)).Select(x => x.Entity as ReadingTaskQuestionAnswer).FirstOrDefault();

                        var question = await _dbContext.ReadingQuestionTrial.Where(x => x.Id == thisQuestinonAnswer.ReadingQuestionTrialId).FirstOrDefaultAsync();

                        string questionName = string.Empty;
                        string questionAnswer = string.Empty;
                        if (thisQuestinonAnswer != null && question != null)
                        {
                            questionName = _userInfo.IsEn_Us ? question.QuestionEnName : question.QuestionName;
                            questionAnswer = Translationunit(question.Type, question.Unit, question.CustomUnit, unitDataList, thisQuestinonAnswer.Answer);
                        }

                        await InsertInspection<ReadingTaskQuestionAnswer>(cloneEntity, type, x => new InspectionConvertDTO()
                        {
                            VisitTaskId = x.VisitTaskId,

                            GeneralId = IdentifierHelper.CreateGuid(cloneEntity.VisitTaskId.ToString(), cloneEntity.ReadingQuestionTrialId.ToString(), "ReadingTaskQuestionAnswer"),

                            ObjectRelationParentId = x.VisitTaskId,

                            TrialReadingCriterionId = x.ReadingQuestionCriterionTrialId,

                            ExtraIndentification = extraIdentification,
                            AuditIdentification = _userInfo.AuditIdentification

                        }, new
                        {

                            MarkName = markName,
                            PicturePath = picturePath,
                            OtherPicturePath = otherPicturePath,
                            QuestinonAnswer = questionAnswer,
                            QuestionName = questionName,
                            QuestionAnswerList = taskQuestionAnswerList.Join(quesionList,
                            t => t.ReadingQuestionTrialId,
                            u => u.QuestionId,
                            (t, u) =>
                            new
                            {
                                Answer = Translationunit(u.AnswerType, u.Unit, u.CustomUnit, unitDataList, t.Answer),
                                PCWGInterimAnswer = Translationunit(u.AnswerType, u.Unit, u.CustomUnit, unitDataList, t.PCWGInterimAnswer),
                                u.DictionaryCode,
                                u.QuestionName,
                                u.QuestionEnName,
                                u.ShowOrder
                            }).OrderBy(t => t.ShowOrder).ToList()
                         ,
                            TableQuestionAndAnswerList = tableQuesionAndAnswerList
                        });


                    }
                }



            }

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingTableQuestionAnswer)))
            {
                if (_userInfo.RequestUrl == "saveTableQuestionMark/-10")
                {
                    var type = GetEntityAuditOpt(item);

                    var entity = item.Entity as ReadingTableQuestionAnswer;

                    var tableQuestion = await _dbContext.ReadingTableQuestionTrial.Where(x => x.Id == entity.TableQuestionId).FirstOrDefaultAsync();
                    var questionName = await _dbContext.ReadingQuestionTrial.Where(x => x.Id == entity.QuestionId).Select(x => _userInfo.IsEn_Us ? x.QuestionEnName : x.QuestionName).FirstOrDefaultAsync();
                    var generalId = IdentifierHelper.CreateGuid(entity.VisitTaskId.ToString(), entity.QuestionId.ToString(), entity.RowId.ToString(), entity.TableQuestionId.ToString(), "ReadingTableQuestionAnswer");
                    var rowMark = await _dbContext.ReadingTableAnswerRowInfo.Where(x => x.Id == entity.RowId).Select(x => x.RowMark).FirstOrDefaultAsync();


                    var markList = entitys.Where(x => x.Entity.GetType() == typeof(ReadingTaskQuestionMark)).Select(x => x.Entity as ReadingTaskQuestionMark).ToList();


                    var mark = markList.Where(x => x.RowId == entity.RowId && x.TableQuestionId == entity.TableQuestionId).FirstOrDefault();
                    var markName = string.Empty;
                    if (mark != null)
                    {
                        markName = mark.OrderMarkName;
                    }
                    List<UnitData> unitDataList = (await _dbContext.Dictionary.Where(x => x.Parent.Code == "ValueUnit").Where(x => x.Code != "0").ToListAsync()).Select(x => new UnitData()
                    {

                        Unit = (ValueUnit)int.Parse(x.Code),
                        UnitName = x.Value.ToString(),
                    }).ToList();

                    await InsertInspection<ReadingTableQuestionAnswer>(entity, type, x => new InspectionConvertDTO()
                    {
                        VisitTaskId = entity.VisitTaskId,
                        GeneralId = generalId,
                        ObjectRelationParentId = entity.VisitTaskId,
                        AuditIdentification = _userInfo.AuditIdentification

                    }, new
                    {
                        Answer = Translationunit(tableQuestion.Type, tableQuestion.Unit, tableQuestion.CustomUnit, unitDataList, entity.Answer),
                        MarkName = markName,
                        PicturePath = mark != null ? mark.PicturePath : string.Empty,
                        QuestionName = questionName,
                        RowMark = rowMark,
                        TableQuestionName = _userInfo.IsEn_Us ? tableQuestion.QuestionEnName : tableQuestion.QuestionName,
                    });
                }

            }





            //病灶这里操作  ReadingTableAnswerRowInfo  ReadingTableQuestionAnswer

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingTableAnswerRowInfo)))
            {

                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as ReadingTableAnswerRowInfo;

                var tableQuestionAnswerList = entitys.Where(x => x.Entity.GetType() == typeof(ReadingTableQuestionAnswer)).Select(t => t.Entity as ReadingTableQuestionAnswer).Where(t => t.RowId == entity.Id).ToList();


                List<UnitData> unitDataList = (await _dbContext.Dictionary.Where(x => x.Parent.Code == "ValueUnit").Where(x => x.Code != "0").ToListAsync()).Select(x => new UnitData()
                {

                    Unit = (ValueUnit)int.Parse(x.Code),
                    UnitName = x.Value.ToString(),
                }).ToList();

                //获取表格问题名称 组合成数组
                var tableQuesionList = await _dbContext.ReadingTableQuestionTrial.Where(t => tableQuestionAnswerList.Select(k => k.TableQuestionId).Contains(t.Id)).Select(t =>
                new
                {
                    TrialReadingCriterionId = t.ReadingQuestionTrial.ReadingQuestionCriterionTrialId, //标准Id
                    Type = t.ReadingQuestionTrial.QuestionName, //病灶类型
                    t.Unit,
                    t.CustomUnit,
                    t.DictionaryCode,
                    t.QuestionName,
                    t.QuestionEnName,
                    QuestionId = t.Id,
                    t.ShowOrder,
                    AnswerType = t.Type,

                })
                    .OrderBy(t => t.ShowOrder).ToListAsync();

                var trialReadingCriterionId = tableQuesionList.FirstOrDefault()?.TrialReadingCriterionId;

                //获取表名称   类型名称(病灶类型)  不用查 从项目问题的稽查记录里面去取
                //var tableName = await _dbContext.ReadingQuestionTrial.Where(t => t.Id == entity.QuestionId).Select(t => t.QuestionName).FirstOrDefaultAsync();

                //分裂病灶 需要原病灶的标识

                //if (_userInfo.RequestUrl == " ReadingImageTask/splitLesion")
                var originalRowMark = string.Empty;
                var mergeRowMark = string.Empty;
                if (entity.SplitRowId != null)
                {

                    originalRowMark = await _dbContext.ReadingTableAnswerRowInfo.Where(t => t.Id == entity.SplitRowId).Select(t => t.RowMark).FirstOrDefaultAsync();
                }

                if (entity.MergeRowId != null)
                {

                    mergeRowMark = await _dbContext.ReadingTableAnswerRowInfo.Where(t => t.Id == entity.MergeRowId).Select(t => t.RowMark).FirstOrDefaultAsync();
                }

                //处理标识   因为触发器在稽查后才进行操作

                entity.OrderMark = await _dbContext.ReadingQuestionTrial.Where(x => x.Id == entity.QuestionId).Select(x => x.OrderMark).FirstOrDefaultAsync();

                entity.RowMark = entity.OrderMark + entity.RowIndex.GetLesionMark();




                string extraIdentification = string.Empty;

                var readingQuestion = await _dbContext.ReadingQuestionTrial.Where(t => t.Id == entity.QuestionId).Include(x => x.ReadingQuestionCriterionTrial).FirstNotNullAsync();
                if (readingQuestion.ReadingQuestionCriterionTrial.CriterionGroup == CriterionGroup.Nontumorous)
                {
                    extraIdentification = "/Nontumorous";
                }

                if (readingQuestion.ReadingQuestionCriterionTrial.CriterionType == CriterionType.SelfDefine)
                {
                    extraIdentification = "/SelfDefine";
                }


                await InsertInspection<ReadingTableAnswerRowInfo>(entity, type, x => new InspectionConvertDTO()
                {
                    ExtraIndentification = extraIdentification,
                    VisitTaskId = x.VisitTaskId,

                    ObjectRelationParentId = x.VisitTaskId,

                    TrialReadingCriterionId = trialReadingCriterionId,

                    ObjectRelationParentId2 = x.QuestionId,
                    AuditIdentification = _userInfo.AuditIdentification

                }, new
                {
                    OriginalRowMark = originalRowMark,
                    MergeRowMark = mergeRowMark,
                    //TableName = tableName,
                    QuestionAnswerList =

                //需要手动添加病灶类型
                tableQuestionAnswerList.Join(tableQuesionList, t => t.TableQuestionId, u => u.QuestionId, (t, u) =>
                new
                {
                    //如果问题类型是附件 特殊处理 方便前端解析
                    Answer = Translationunit(u.AnswerType, u.Unit, u.CustomUnit, unitDataList, t.Answer),
                    //t.Answer        /*u.Unit==ValueUnit.Custom? t.Answer+u.CustomUnit:(u.Unit != ValueUnit.None|| u.Unit != null)*/,
                    u.QuestionName,
                    u.QuestionEnName,
                    u.DictionaryCode,
                    u.ShowOrder
                }
                ).OrderBy(t => t.ShowOrder).ToList()
                });


                ////添加/修改病灶接口  只会对单个病灶进行操作
                //if (_userInfo.RequestUrl == "ReadingImageTask/submitTableQuestion")
                //{             
                //}

                ////删除病灶接口  里面也有更新
                //if (_userInfo.RequestUrl == "ReadingImageTask/deleteReadingRowAnswer")
                //{
                //    //有删除  有修改 多条稽查记录  

                //    var deleteList = entitys.Where(x => x.Entity.GetType() == typeof(ReadingTableQuestionAnswer) && GetEntityAuditOpt(x) == AuditOpt.Deleted).Select(t => t.Entity as ReadingTableQuestionAnswer).ToList();

                //    var updateList = entitys.Where(x => x.Entity.GetType() == typeof(ReadingTableQuestionAnswer) && GetEntityAuditOpt(x) == AuditOpt.Update).Select(t => t.Entity as ReadingTableQuestionAnswer).ToList();
                //}

            }


            #endregion



            #region 肿瘤学阅片结果 记录表格  废弃

            //if (entitys.Any(x => x.entity.gettype() == typeof(readingoncologytaskinfo)))
            //{
            //        var type = auditopt.add;

            //        var oncologyanswerlist = entitys.where(x => x.entity.gettype() == typeof(readingoncologytaskinfo)).select(t => t.entity as readingoncologytaskinfo);

            //        var visittaskidlist = oncologyanswerlist.select(t => t.visittaskid).tolist();

            //        var visittasklist = await _dbcontext.visittask.where(t => visittaskidlist.contains(t.id)).select(t => new { visittaskid = t.id, t.taskname, t.taskblindname, t.visittasknum, t.subjectid }).tolistasync();



            //        var modifyvisitlist = await _dbcontext.readingglobaltaskinfo.where(t => visittaskidlist.contains(t.taskid) && t.visittask.taskstate == taskstate.effect).groupby(t => t.taskid).select(g => new
            //        {
            //            visittaskid = g.key,
            //            globalresult = g.select(c => new { c.answer, c.questionid })
            //        }).tolistasync();


            //        //var oncologyanswervisitlist = visittasklist.join(oncologyanswerlist, t => t.visittaskid, u => u.visittaskid, (t, u) => new { t.visittaskid, t.taskblindname, t.taskname, u.evaluationreason, u.evaluationresult }).tolist();

            //        var query = from answer in oncologyanswerlist
            //                    join visittask in visittasklist on answer.visittaskid equals visittask.visittaskid
            //                    join modifyvisit in modifyvisitlist on answer.visittaskid equals modifyvisit.visittaskid into cc
            //                    from modifyvisit in cc.defaultifempty()
            //                    select new
            //                    {
            //                        visittask.taskblindname,
            //                        visittask.taskname,
            //                        answer.evaluationreason,
            //                        answer.evaluationresult,
            //                        isglobalmodify = modifyvisit != null,
            //                        reason = modifyvisit != null ? modifyvisit.globalresult.where(t => t.questionid == null).firstordefault()?.answer : string.empty
            //                    };
            //    var result = query.tolist();


            //    var oncologyanswer = oncologyanswerlist.first();

            //    var cloneentity = oncologyanswer.clone();

            //    cloneentity.id = newid.nextguid();

            //    await insertinspection<readingoncologytaskinfo>(oncologyanswer, type, x => new inspectionconvertdto()
            //    {
            //        visittaskid = oncologyanswer.visittaskid,

            //        objectrelationparentid = oncologyanswer.visittaskid,

            //    }, new { oncologyanswerlist = result });
            //}

            #endregion




            // 全局 阅片结果
            if (entitys.Any(x => x.Entity.GetType() == typeof(ReadingGlobalTaskInfo)))
            {
                var type = AuditOpt.Add;

                var list = entitys.Where(x => x.Entity.GetType() == typeof(ReadingGlobalTaskInfo)).Select(t => t.Entity as ReadingGlobalTaskInfo);

                //不是固定问题的问题
                var firstEntity = list.First();

                var cloneEntity = firstEntity.Clone();

                var criterion = await _dbContext.VisitTask.Where(t => t.Id == cloneEntity.GlobalTaskId).Select(t => new { t.TrialReadingCriterionId, t.TrialReadingCriterion.CriterionType }).FirstOrDefaultAsync();

                //保证Id 唯一
                cloneEntity.Id = IdentifierHelper.CreateGuid(firstEntity.GlobalTaskId.ToString(), criterion.TrialReadingCriterionId.ToString());

                var extraIdentification = string.Empty;


                var objList = new List<object>();

                foreach (var group in list.GroupBy(t => t.TaskId))
                {
                    var questionAnswerList = group.Where(t => t.QuestionId != null).ToList();


                    var questionIdList = questionAnswerList.Select(t => t.QuestionId).ToList();

                    var quesionList = await _dbContext.ReadingQuestionTrial.Where(t => questionIdList.Contains(t.Id)).Select(t => new
                    {
                        QuestionName = t.QuestionName,
                        t.QuestionEnName,
                        QuestionId = t.Id,
                        t.DictionaryCode,
                        t.ShowOrder
                    }).OrderBy(t => t.ShowOrder).ToListAsync();


                    //pcwg3 的问题没有提交过来，是通过固定的方式去查询出来 
                    if (criterion.CriterionType == CriterionType.PCWG3)
                    {

                        extraIdentification = "/PCWG3";
                        //获取访视的评估结果 也要记录稽查
                        var visitAnswerList = await _dbContext.ReadingTaskQuestionAnswer.Where(t => t.VisitTaskId == group.Key && t.ReadingQuestionTrial.GlobalReadingShowType != GlobalReadingShowType.NotShow).Select(u => new
                        {
                            TaskBlindName = u.VisitTask.TaskBlindName,
                            QuestionId = u.ReadingQuestionTrialId,
                            QuestionName = u.ReadingQuestionTrial.QuestionName,
                            u.ReadingQuestionTrial.QuestionEnName,
                            u.ReadingQuestionTrial.DictionaryCode,
                            u.ReadingQuestionTrial.ShowOrder,
                            u.Answer
                        }).OrderBy(t => t.ShowOrder).ToListAsync();


                        var obj = new
                        {
                            TaskBlindName = visitAnswerList.Select(t => t.TaskBlindName).FirstOrDefault(),
                            VisitQuestionAnswerList = visitAnswerList,


                            Reason = group.Where(t => t.QuestionId == null && t.GlobalAnswerType == GlobalAnswerType.Reason).FirstOrDefault()?.Answer,

                            QuestionAnswerList = questionAnswerList.Join(quesionList, t => t.QuestionId, u => u.QuestionId, (t, u) => new { t.Answer, u.QuestionName, u.QuestionEnName, u.DictionaryCode, u.ShowOrder }).OrderBy(t => t.ShowOrder).ToList()
                        };

                        objList.Add(obj);



                    }
                    else
                    {
                        //获取访视的评估结果 也要记录稽查
                        var visitAnswerList = await _dbContext.ReadingTaskQuestionAnswer.Where(t => t.VisitTaskId == group.Key && questionIdList.Contains(t.ReadingQuestionTrialId)).Select(u => new
                        {
                            TaskBlindName = u.VisitTask.TaskBlindName,
                            QuestionId = u.ReadingQuestionTrialId,
                            u.Answer
                        }).ToListAsync();


                        var obj = new
                        {
                            TaskBlindName = visitAnswerList.Select(t => t.TaskBlindName).FirstOrDefault(),
                            VisitQuestionAnswerList = visitAnswerList.Join(quesionList, t => t.QuestionId, u => u.QuestionId, (t, u) => new { t.Answer, u.QuestionName, u.DictionaryCode, u.ShowOrder }).OrderBy(t => t.ShowOrder).ToList(),
                            Reason = group.Where(t => t.QuestionId == null && t.GlobalAnswerType == GlobalAnswerType.Reason).FirstOrDefault()?.Answer,
                            AgreeOrNot = group.Where(t => t.QuestionId == null && t.GlobalAnswerType == GlobalAnswerType.AgreeOrNot).FirstOrDefault()?.Answer,
                            UpdateType = group.Where(t => t.QuestionId == null && t.GlobalAnswerType == GlobalAnswerType.UpdateType).FirstOrDefault()?.Answer,
                            QuestionAnswerList = questionAnswerList.Join(quesionList, t => t.QuestionId, u => u.QuestionId, (t, u) => new { t.Answer, u.QuestionName, u.QuestionEnName, u.DictionaryCode, u.ShowOrder }).OrderBy(t => t.ShowOrder).ToList()
                        };

                        objList.Add(obj);

                    }

                }


                await InsertInspection<ReadingGlobalTaskInfo>(cloneEntity, type, x => new InspectionConvertDTO()
                {
                    VisitTaskId = x.GlobalTaskId,
                    TrialReadingCriterionId = criterion.TrialReadingCriterionId,
                    ObjectRelationParentId = x.TaskId,
                    ExtraIndentification = extraIdentification
                }, new { GlobalAnswerList = objList });

            }


            //肿瘤学阅片结果

            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(ReadingOncologyTaskInfo)))
            {
                var type = AuditOpt.Add;

                var entity = item.Entity as ReadingOncologyTaskInfo;

                await InsertInspection<ReadingOncologyTaskInfo>(entity, type, x => new InspectionConvertDTO()
                {
                    VisitTaskId = entity.VisitTaskId,

                    ObjectRelationParentId = entity.VisitTaskId,

                });
            }


            #endregion






            #endregion


        }

        /// <summary>
        /// 插入稽查实体
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="data">数据</param>
        /// <param name="type">类型</param>
        /// <param name="expression">表达式</param>
        /// <param name="otherItem">其他对象</param>
        /// <param name="auditIdentification">额外标识</param>
        /// <param name="customPrefix">自定义前缀</param>
        /// <returns></returns>
        public async Task InsertInspection<T>(T entityObj, string type, Expression<Func<T, InspectionConvertDTO>> expression = null, object otherItem = null) where T : Entity
        {

            InspectionConvertDTO inspection = new InspectionConvertDTO();
            if (expression != null)
            {
                var f = expression.Compile();

                inspection = f(entityObj);
            }
            var reason = inspection.Reason;

            //避免重复赋值  有些特殊的GeneralId  
            var generalId = (inspection.GeneralId != null && inspection.GeneralId != Guid.Empty) ? inspection.GeneralId : entityObj.Id;
            inspection.GeneralId = generalId;

            inspection.Identification = GetInspectionRecordIdentification(entityObj, type, inspection) + inspection.ExtraIndentification;

            //将实体对象属性 映射到稽查实体
            MapEntityPropertyToAuditEntity(entityObj, inspection);

            //var generalData = await GetInspectionGeneralDataAsync(inspection);

            var generalData = await GetInspectionGeneralGuidAsync(inspection);


            //不可少  因为稽查实体可能某些Id没有 
            MapEntityPropertyToAuditEntity(generalData, inspection);

            #region 处理标识

            //批量记录instance 这种稽查的时候，减少数据库查询交互 --稽查缓存
            var from = await _fusionCache.GetOrSetAsync(InspectionCacheKeys.FrontAuditConfig(inspection.Identification), async _ =>
                        {
                            return await _dbContext.FrontAuditConfig
                                .FirstOrDefaultAsync(x => x.Identification == inspection.Identification);
                        },
                        TimeSpan.FromMinutes(10) // 缓存 10 分钟
                    );

            //var from = await _dbContext.FrontAuditConfig.FirstOrDefaultAsync(x => x.Identification == inspection.Identification);

            inspection.ObjectTypeId = from?.ObjectTypeId;
            inspection.OptTypeId = from?.OptTypeId;
            //inspection.ChildrenTypeId = from?.ChildrenTypeId;
            inspection.ModuleTypeId = from?.ModuleTypeId;

            #endregion



            inspection.CreateUserName = _userInfo.UserName;
            inspection.CreateUserRealName = _userInfo.FullName;
            inspection.RoleName = _userInfo.UserTypeShortName;
            inspection.CreateUserId = _userInfo.UserRoleId;
            inspection.IP = _userInfo.IP;
            inspection.CreateTime = inspection.CreateTime == default(DateTime) ? DateTime.Now : inspection.CreateTime;

            if (_userInfo.SignId != null)
            {
                inspection.SignId = _userInfo.SignId;
                inspection.IsSign = true;
            }

            var entityName = entityObj.GetType().Name;

            inspection.JsonDetail = new InspectionJsonDetail
            {
                //稽查实体，加上扩充的信息               
                //Data = AddJsonItem(entityObj, otherItem),

                //通用信息 每条稽查必须记录的
                //CommonData = generalData

                EntityName = entityName,

                //Data 仅仅记录稽查实体的信息  CommonData  存放关联数据的信息(特殊情况下会单独赋值)
                //后期通过关联   就不需要把 OtherItem  并入到Data中
                Data = AddJsonItem(entityObj, otherItem),

                //准确来讲  此处称之为 RelationData 更贴合  为了兼容之前的数据
                CommonData = new { SiteCode = generalData.SiteCode, SubjectCode = generalData.SubjectCode },

            }.ToJsonStr();
            inspection.BatchId = _userInfo.BatchId.Value;

            inspection.EntityName = entityName;
            inspection.RealUrlAndEntity = _userInfo.RequestUrl + "/" + entityName + "/" + type;

            inspection.Reason = inspection.Reason == string.Empty && reason != string.Empty ? reason : inspection.Reason;
            await _dbContext.DataInspection.AddAsync(inspection);


            //await AddInspectionRecordAsync( entityObj, inspection, otherItem);
        }


        /// <summary>
        /// 将数据库实体属性，映射到稽查实体属性 避免重复赋值
        /// </summary>
        /// <param name="date"></param>
        /// <param name="auditEntity"></param>
        public void MapEntityPropertyToAuditEntity(object data, DataInspection auditEntity)
        {
            foreach (var auditEntityPropertyInfo in auditEntity.GetType().GetProperties())
            {
                var excepetNameList = typeof(Entity).GetProperties().Select(t => t.Name)
                    .Concat(typeof(ISoftDelete).GetProperties().Select(t => t.Name))
                    .Concat(typeof(IAuditAdd<>).GetProperties().Select(t => t.Name))
                    .Concat(typeof(IAuditUpdate<>).GetProperties().Select(t => t.Name));

                var filterProperties = data.GetType().GetProperties().Where(t => !excepetNameList.Any(u => u == t.Name));

                if (filterProperties.Any(t => t.Name == auditEntityPropertyInfo.Name))
                {
                    var value = data.GetType().GetProperty(auditEntityPropertyInfo.Name).GetValue(data);

                    auditEntity.GetType().GetProperty(auditEntityPropertyInfo.Name).SetValue(auditEntity, value);
                }
            }
        }


        /// <summary>
        /// 获取稽查通用Guid数据 (每条稽查记录必须查询的)
        /// </summary>
        /// <param name="inspection"></param>
        /// <returns></returns>
        public async Task<InspectionGeneralData> GetInspectionGeneralGuidAsync(InspectionConvertDTO inspection)
        {

            InspectionGeneralData generalData = new InspectionGeneralData()
            {
                TrialSiteId = inspection.TrialSiteId,
                SubjectId = inspection.SubjectId,
                SubjectVisitId = inspection.SubjectVisitId,
                TrialId = inspection.TrialId,
                TrialReadingCriterionId = inspection.TrialReadingCriterionId
            };


            if (inspection.VisitTaskId != null)
            {

                if (generalData.TrialId == null || generalData.TrialSiteId == null || generalData.SubjectId == null || generalData.TrialReadingCriterionId == null)
                {
                    //var info = await _dbContext.VisitTask.Where(x => x.Id == inspection.VisitTaskId).Select(x => new { SubjectCode = x.Subject.Code, TrialSiteCode = x.Subject.TrialSite.TrialSiteCode, SubjectId = x.SubjectId, x.Subject.TrialSiteId, x.TrialId, x.SourceSubjectVisitId, ReadModuleSubjectVisitId = (Guid?)x.ReadModule.SubjectVisitId, x.TrialReadingCriterionId }).FirstOrDefaultAsync();

                    var info = await _fusionCache.GetOrSetAsync(InspectionCacheKeys.VisitTask(inspection.VisitTaskId), async _ =>
                    {
                        return await _dbContext.VisitTask.Where(x => x.Id == inspection.VisitTaskId).Select(x => new { SubjectCode = x.Subject.Code, TrialSiteCode = x.Subject.TrialSite.TrialSiteCode, SubjectId = x.SubjectId, x.Subject.TrialSiteId, x.TrialId, x.SourceSubjectVisitId, ReadModuleSubjectVisitId = (Guid?)x.ReadModule.SubjectVisitId, x.TrialReadingCriterionId }).FirstOrDefaultAsync();

                    },
                         TimeSpan.FromDays(1) // 缓存 1天
                   );

                    generalData.TrialReadingCriterionId = info?.TrialReadingCriterionId ?? generalData.TrialReadingCriterionId;
                    generalData.TrialId = info?.TrialId ?? generalData.TrialId;
                    generalData.SubjectId = info?.SubjectId ?? generalData.SubjectId;
                    generalData.TrialSiteId = info?.TrialSiteId ?? generalData.TrialSiteId;
                    generalData.SubjectVisitId = info?.SourceSubjectVisitId != null ? info?.SourceSubjectVisitId : (info?.ReadModuleSubjectVisitId != null ? info?.ReadModuleSubjectVisitId : null);

                    //以后移除
                    generalData.SiteCode = info?.TrialSiteCode ?? generalData.SiteCode;
                    generalData.SubjectCode = info?.SubjectCode ?? generalData.SubjectCode;
                }

            }

            if (inspection.TrialReadingCriterionId != null)
            {
                if (generalData.TrialId == null)
                {
                    var info = await _fusionCache.GetOrSetAsync(InspectionCacheKeys.ReadingQuestionCriterionTrial(inspection.TrialReadingCriterionId), async _ =>
                        {
                            return await _dbContext.ReadingQuestionCriterionTrial.Where(x => x.Id == inspection.TrialReadingCriterionId).Select(x => new { x.TrialId }).FirstOrDefaultAsync();
                        },
                          TimeSpan.FromDays(1) // 缓存 1天
                    );

                    //var info = await _dbContext.ReadingQuestionCriterionTrial.Where(x => x.Id == inspection.TrialReadingCriterionId).Select(x => new { x.TrialId }).FirstOrDefaultAsync();

                    generalData.TrialId = info?.TrialId ?? generalData.TrialId;
                }
            }

            // Suject  visit  都进行了设置   不用处理

            if (inspection.SubjectVisitId != null)
            {
                if (generalData.TrialId == null || generalData.TrialSiteId == null || generalData.SubjectId == null)
                {

                    var info = await _fusionCache.GetOrSetAsync(InspectionCacheKeys.SubjectVisit(inspection.SubjectVisitId), async _ =>
                    {
                        return await _dbContext.SubjectVisit.Where(x => x.Id == generalData.SubjectVisitId).Select(x =>
                      new { x.SubjectId, x.TrialSiteId, x.TrialId, SubjectCode = x.Subject.Code, TrialSiteCode = x.Subject.TrialSite.TrialSiteCode }).FirstOrDefaultAsync();
                    },
                          TimeSpan.FromDays(1) // 缓存 1天
                    );

                    //  var info = await _dbContext.SubjectVisit.Where(x => x.Id == generalData.SubjectVisitId).Select(x =>
                    //new { x.SubjectId, x.TrialSiteId, x.TrialId, SubjectCode = x.Subject.Code, TrialSiteCode = x.Subject.TrialSite.TrialSiteCode }).FirstOrDefaultAsync();


                    generalData.TrialId = info?.TrialId ?? generalData.TrialId;
                    generalData.TrialSiteId = info?.TrialSiteId ?? generalData.TrialSiteId;
                    generalData.SubjectId = info?.SubjectId ?? generalData.SubjectId;

                    //以后移除
                    generalData.SiteCode = info?.TrialSiteCode ?? generalData.SiteCode;
                    generalData.SubjectCode = info?.SubjectCode ?? generalData.SubjectCode;
                }


            }


            if (generalData.SubjectId != null)
            {
                if (generalData.TrialId == null || generalData.TrialSiteId == null)
                {
                    //var info = await _dbContext.Subject.Where(x => x.Id == generalData.SubjectId).Select(x => new { SubjectId = x.Id, x.TrialSiteId, x.TrialId, SubjectCode = x.Code, TrialSiteCode = x.TrialSite.TrialSiteCode }).FirstOrDefaultAsync();

                    var info = await _fusionCache.GetOrSetAsync(InspectionCacheKeys.SubjecSiteInfo(inspection.SubjectId), async _ =>
                    {
                        return await _dbContext.Subject.Where(x => x.Id == generalData.SubjectId).Select(x => new { SubjectId = x.Id, x.TrialSiteId, x.TrialId, SubjectCode = x.Code, TrialSiteCode = x.TrialSite.TrialSiteCode }).FirstOrDefaultAsync();
                    },
                       TimeSpan.FromDays(1) // 缓存 1天
                    );


                    if (info == null)
                    {
                        var subject = _dbContext.Subject.Find(generalData.SubjectId);

                        generalData.TrialId = subject?.TrialId;
                        generalData.TrialSiteId = subject?.TrialSiteId;
                    }
                    else
                    {
                        generalData.TrialId = info?.TrialId ?? generalData.TrialId;

                        generalData.TrialSiteId = info?.TrialSiteId ?? generalData.TrialSiteId;
                    }

                    //以后移除
                    generalData.SiteCode = info?.TrialSiteCode ?? generalData.SiteCode;
                    generalData.SubjectCode = info?.SubjectCode ?? generalData.SubjectCode;
                }


            }

            return generalData;
        }



        /// <summary>
        /// 获取稽查记录的标识符   部分业务会进行特殊处理
        /// </summary>
        /// <returns></returns>
        /// <typeparam name="T"></typeparam>
        /// <param name="entityObj"></param>
        /// <param name="type"></param>
        /// <param name="IsDistinctionInterface"></param>
        /// <param name="isSelfDefine"></param>
        /// <param name="auditIdentification"></param>
        /// <param name="customPrefix">自定义前缀  某些接口需要用同一个稽查</param>
        /// <returns></returns>
        public string GetInspectionRecordIdentification<T>(T entityObj, string type, InspectionConvertDTO inspection)
        {
            //var entityType = _dbContext.Model.FindEntityType(entityObj.GetType());
            //var tableName = entityType.GetTableName();

            var entityTypeName = entityObj.GetType().Name;

            //文档签署这块，不区分系统和项目的 需要处理为同一个标识
            //if (typeof(T) == typeof(TrialDocConfirmedUser) || typeof(T) == typeof(SystemDocConfirmedUser))
            //{
            //    entityTypeName = "New/" + "UserSigned";
            //}
            string result = string.Empty;
            //默认规则
            if (inspection.IsDistinctionInterface)
            {
                //自定义 标识后面 补充由代码上层的 extraIdentification 附加
                if (inspection.IsSelfDefine)
                {
                    result = $"{_userInfo.RequestUrl}/{entityTypeName}";
                }
                else
                {
                    result = $"{_userInfo.RequestUrl}/{entityTypeName}/{type}";
                }


            }
            else
            {
                //自定义 标识后面 补充由代码上层的 extraIdentification 附加
                if (inspection.IsSelfDefine)
                {
                    result = $"{entityTypeName}";
                }
                else
                {
                    result = $"{entityTypeName}/{type}";
                }

            }

            if (inspection.AuditIdentification.IsNotNullOrEmpty())
            {
                result = result + "/" + inspection.AuditIdentification;
            }

            if (inspection.CustomPrefix.IsNotNullOrEmpty())
            {
                result = inspection.CustomPrefix + "/" + result;
            }


            if (inspection.SelfDefineIdentification.IsNotNullOrEmpty())
            {
                result = inspection.SelfDefineIdentification;
            }
            return result;

        }


        /// 往json里面添加属性
        /// </summary>
        /// <param name="jsonObj">json</param>
        /// <param name="otherItem">添加对象</param>
        /// <returns></returns>
        public IDictionary<string, object> AddJsonItem(object jsonObj, object otherItem = null)
        {


            var JsonData = JsonConvert.DeserializeObject<IDictionary<string, object>>((jsonObj).ToJsonStr());

            if (otherItem == null)
            {
                return JsonData;
            }
            var other = JsonConvert.DeserializeObject<IDictionary<string, object>>(otherItem.ToJsonStr());

            foreach (var item in other)
            {
                if (JsonData.ContainsKey(item.Key))
                {
                    JsonData[item.Key] = item.Value;
                }
                else
                {
                    JsonData.Add(item.Key, item.Value);
                }

            }
            return JsonData;

        }



    }
}
