using IRaCIS.Core.Domain.Models;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infra.EFCore.Common.Dto;
using IRaCIS.Core.Infrastructure;
using IRaCIS.Core.Infrastructure.Extention;
using MassTransit;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Newtonsoft.Json;
using SharpCompress.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;


namespace IRaCIS.Core.Infra.EFCore.Common
{
    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; }

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



        /// <summary>
        /// 特殊删除
        /// </summary>
        private List<Type> NodeleteTableTypes
        {
            get
            {
                return new List<Type>()
                {
                   typeof(TrialUser),
                   typeof(TrialSiteSurvey),
                   typeof(TrialSiteUser),
                   typeof(VisitStage),
                   typeof(TrialSite)
                };
            }
        }


        public string GetEntityAuditOpt(EntityEntry entityEntry)
        {
            if (entityEntry.State == EntityState.Added)
            {
                return AuditOpt.Add;
            }

            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)
        {

            #region 区分

            // 项目
            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 clinicalDataSetNameList = await _dbContext.ClinicalDataTrialSet.Where(t => t.TrialId == entity.Id && t.IsConfirm).Select(t => t.ClinicalDataSetName).ToListAsync();



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



                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
                }).FirstOrDefaultAsync();
                switch (_userInfo.RequestUrl)
                {
                    case "configTrialBasicInfo/ConfigTrialBasicInfoConfirm":
                        extraIdentification = $"/{oldentity.IsTrialBasicLogicConfirmed.ToString()}";
                        break;

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

                    case "TrialEmailNoticeConfig/setTrialEmail":

                        extraIdentification = oldentity.IsConfigureEmail ? "/EmailUpdate" : "/EmailSave";
                        break;
                }


                await InsertInspection<Trial>(item.Entity as Trial, type, x => new InspectionConvertDTO()
                {
                    TrialId = x.Id,
                    ExtraIndentification = extraIdentification,
                }, new
                {
                    //TrialDicList = string.Join(",", trialDics)

                    CriterionNames = criterionNameList.Count() > 0 ? string.Join(",", criterionNameList) : string.Empty,

                    ClinicalDataSetNames = clinicalDataSetNameList.Count() > 0 ? string.Join(",", clinicalDataSetNameList) : String.Empty,


                }); ;
            }





            #endregion


            #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 == "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(ReadingCriterionDictionary)).Select(t => t.Entity as ReadingCriterionDictionary).Where(t => t.CriterionId == entity.Id).Select(t => t.DictionaryId).ToList();

                var dicValueList = new List<string>();
                if (dicIdList.Count() == 0)
                {
                    dicValueList = await _dbContext.ReadingCriterionDictionary.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();
                }


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

                    TrialReadingCriterionId = entity.Id,

                    ObjectRelationParentId = x.TrialId,

                    ExtraIndentification = extraIdentification

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

            //系统标准问题
            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, 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,

                    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(CriterionNidus)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as CriterionNidus;


                var extraIdentification = string.Empty;
                if (entity.IsSystemCriterion == false)
                {
                    extraIdentification = "/IsTrial";

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



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

                    ObjectRelationParentId = entity.CriterionId,

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

                    ExtraIndentification = extraIdentification


                });
            }

            //疗效评估

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

                var entity = item.Entity as TumorAssessment;


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

                    ObjectRelationParentId = entity.CriterionId

                });
            }


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



                var type = AuditOpt.Add;

                var allList = entitys.Where(x => x.Entity.GetType() == typeof(ReadingCriterionDictionary)).Select(t => t.Entity as ReadingCriterionDictionary).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;

                    //系统标准
                    if (cloneEntity.IsSystemCriterion)
                    {
                        extraIdentification = $"/{cloneEntity.ParentCode}";
                    }
                    else
                    {
                        extraIdentification = $"/{cloneEntity.ParentCode}/IsTrial";
                    }


                    await InsertInspection<ReadingCriterionDictionary>(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
                                                        {
                                                            t.Value,
                                                            t.ValueCN,
                                                            t.Description,
                                                            t.ShowOrder,
                                                            u.IsBaseLineUse,
                                                            u.IsFollowVisitUse
                                                        }
                                                        ).OrderBy(t => t.ShowOrder).ToList()
                        });
                }







            }



            #endregion


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

                var entity = item.Entity as SystemDocConfirmedUser;
                var systemDocument = await _dbContext.SystemDocument.Where(x => x.Id == entity.SystemDocumentId).FirstOrDefaultAsync();
                await InsertInspection<SystemDocConfirmedUser>(entity, type, x => new InspectionConvertDTO()
                {
                    GeneralId = x.Id,

                    ObjectRelationParentId = x.SystemDocumentId

                }, new
                {

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

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

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

                var entity = item.Entity as TrialDocConfirmedUser;

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

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


                    ObjectRelationParentId = x.TrialDocumentId
                }, new
                {

                    UploadTime = trialDoc.CreateTime,

                    CreateUserName = _userInfo.UserName,
                    UserType = _userInfo.UserTypeShortName,
                    IsSigned = true
                });
            }


            //医学审核 问题答案
            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;

                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

                });
            }



            //医学审核
            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
                });
            }



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




                #region OLd
                //var entitylist = entitys.Where(x => x.Entity.GetType() == typeof(TrialQCQuestionAnswer)).Select(x => x.Entity as TrialQCQuestionAnswer).ToList();
                //var firstEntity = entitylist.FirstOrDefault();
                //var subjectVisit = await _dbContext.SubjectVisit.Where(x => x.Id == firstEntity.SubjectVisitId).FirstOrDefaultAsync();
                //subjectVisit = subjectVisit ?? new SubjectVisit();
                //if (type == "Add")
                //{


                //    await InsertInspection(firstEntity, type, answer => new InspectionConvertDTO()
                //    {
                //        SiteId = subjectVisit.SiteId,
                //        SubjectId = subjectVisit.SubjectId,
                //        SubjectVisitName = subjectVisit.VisitName,
                //        TrialId = subjectVisit.TrialId,
                //        SubjectVisitId = subjectVisit.Id,

                //        //GeneralId = subjectVisit.Id,
                //        //byzhouhang
                //        ObjectRelationParentId = subjectVisit.Id,
                //    }, new
                //    {
                //        QcQuestionAnswerCommands = await Getdata(entitylist),
                //    });
                //}
                //else if (type == "Update")
                //{

                //    var questionIds = entitylist.Where(x => x.SubjectVisitId == subjectVisit.Id).Select(x => x.Id).ToList();
                //    var createUserId = entitylist.Select(x => x.CreateUserId).FirstOrDefault();
                //    var noUpdateData = _dbContext.TrialQCQuestionAnswer.Where(x => x.CreateUserId == createUserId && x.SubjectVisitId == subjectVisit.Id && !questionIds.Contains(x.Id)).ToList();
                //    entitylist.AddRange(noUpdateData);

                //    await InsertInspection(firstEntity, type, answer => new InspectionConvertDTO()
                //    {
                //        SiteId = subjectVisit.SiteId,
                //        SubjectId = subjectVisit.SubjectId,
                //        SubjectVisitName = subjectVisit.VisitName,
                //        TrialId = subjectVisit.TrialId,
                //        SubjectVisitId = subjectVisit.Id,

                //        //GeneralId = subjectVisit.Id,
                //        //byzhouhang
                //        ObjectRelationParentId = subjectVisit.Id,
                //    }, new
                //    {
                //        QcQuestionAnswerCommands = await Getdata(entitylist),
                //    });


                //}

                //async Task<List<AnswerDto>> Getdata(List<TrialQCQuestionAnswer> questionAnswers)
                //{
                //    var ids = questionAnswers.Select(x => x.TrialQCQuestionConfigureId).ToList();
                //    var trialQCQuestionConfigureDatas = await _dbContext.TrialQCQuestionConfigure.Where(x => ids.Contains(x.Id)).ToListAsync();
                //    var collect = questionAnswers.GroupJoin(trialQCQuestionConfigureDatas, one => one.TrialQCQuestionConfigureId, two => two.Id, (x, y) => new { one = x, two = y })
                //      .SelectMany(a => a.two.DefaultIfEmpty(), (c, d) => new { c = c.one, d })
                //      .OrderBy(x => x.d.ShowOrder)
                //      .Select(o => new AnswerDto()
                //      {
                //          QuestionName = o.d.QuestionName,
                //          Answer = o.c.Answer,
                //      }).ToList();
                //    return collect;
                //}
                #endregion





            }

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

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

                    SubjectVisitId = x.SubjectVisitId,


                    //byzhouhang
                    ObjectRelationParentId = entity.QCChallengeId,

                    IsDistinctionInterface = false

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

                var entity = item.Entity as CheckChallengeDialog;

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

                    SubjectVisitId = x.SubjectVisitId,

                    //byzhouhang
                    IsDistinctionInterface = false,

                    ObjectRelationParentId = entity.SubjectVisitId,
                }

                );
            }


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

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

                });
            }
            #endregion

            // 中心调研表
            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.Where(x => x.SiteId == entity.SiteId && 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();
                }

                await InsertInspection<TrialSiteSurvey>(item.Entity as TrialSiteSurvey, type, x => new InspectionConvertDTO()
                {
                    ObjectRelationParentId = entity.TrialSite.Id,
                }, 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(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
                {
                    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
                {
                    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
                {
                    Type = ClinicalFileType.PreviousOther
                });
            }





            //系统文件
            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);
                await InsertInspection<TrialDocument>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false,
                    ObjectRelationParentId = x.TrialId
                },
                new
                {
                    NeedConfirmedUserType = usertypeName,
                });


            }

            //系统  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(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 = x.TrialId

                }, new { ParentQuestionName = parentQuestionName });
            }


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

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



            // 项目中心  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.Site = await _dbContext.Site.Where(x => x.Id == entity.SiteId).FirstOrDefaultAsync();
                }
                await InsertInspection<TrialSite>(entity, type, x => new InspectionConvertDTO()
                {
                    TrialId = x.TrialId,

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

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



            // 项目人员
            foreach (var item in entitys.Where(x => x.Entity.GetType() == typeof(TrialUser)))
            {
                var type = GetEntityAuditOpt(item);

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


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

                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as TrialSiteUser;


                if (entity.TrialSite == null)
                {
                    entity.TrialSite = await _dbContext.TrialSite.Where(x => x.TrialId == entity.TrialId && x.SiteId == entity.SiteId).IgnoreQueryFilters().FirstOrDefaultAsync();
                }

                await InsertInspection<TrialSiteUser>(item.Entity as TrialSiteUser, type, x => new InspectionConvertDTO
                {
                    TrialId = x.TrialId,
                    ObjectRelationParentId = entity.TrialSite.Id,
                    ObjectRelationParentId2 = x.UserId,
                });
            }


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

                //var trialSiteCode = await _dbContext.TrialSite.Where(t => t.TrialId == entity.TrialId && t.SiteId == entity.SiteId).Select(t => t.TrialSiteCode).FirstOrDefaultAsync();

                var trialSiteId = await _dbContext.TrialSite.Where(t => t.TrialId == entity.TrialId && t.SiteId == entity.SiteId).Select(t => t.Id).FirstOrDefaultAsync();

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

                    //项目的信息 找离的最近的项目稽查信息
                    ObjectRelationParentId = 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(SubjectVisit)))
            {

                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as SubjectVisit;

                await InsertInspection<SubjectVisit>(item.Entity as SubjectVisit, type, x => new InspectionConvertDTO()
                {
                    //Subject的信息 找离的最近的Subject稽查信息
                    ObjectRelationParentId = x.SubjectId,

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

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

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

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

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


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

                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as NoneDicomStudy;

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

                });
            }


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

                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 = enrollId,

                    TrialId = trialId,

                    ObjectRelationParentId = enrollId,

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

            #endregion


            #region 阅片期临床数据



            //系统临床数据配置

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

                //获取配置的标准名称

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

            // 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 config= await _dbContext.ClinicalDataTrialSet.FindAsync(entity.ClinicalDataTrialSetId);

                await InsertInspection<ReadingClinicalData>(item.Entity as ReadingClinicalData, 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.SiteId).ToList();
                    var nameList = _dbContext.TrialSite.Where(c => c.TrialId == entity.TrialId && siteIds.Contains(c.SiteId)).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;

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

                    ObjectRelationParentId2 = entity.TrialReadingCriterionId,

                    //SubjectVisitId = x.SubjectVisitId,
                    IsDistinctionInterface = false,
                });
            }


            #endregion


            #region 阅片

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

                var entity = item.Entity as User;

                await InsertInspection<User>(entity, type, x => new InspectionConvertDTO()
                {
                    IsDistinctionInterface = false
                }, 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;

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

                    ObjectRelationParentId = entity.EnrollId,

                    ObjectRelationParentId2 = entity.DoctorUserId

                });
            }

            //  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(VisitTaskReReading)))
            {
                var type = GetEntityAuditOpt(item);

                var entity = item.Entity as VisitTaskReReading;

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

                    Reason = entity.RequestReReadingReason,

                    ObjectRelationParentId = entity.OriginalReReadingTaskId,

                });
            }


            //一致性分析规则

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

                var entity = item.Entity as TaskConsistentRule;

                await InsertInspection<TaskConsistentRule>(entity, type, x => new InspectionConvertDTO()
                {
                    ObjectRelationParentId = entity.TrialId,

                    ObjectRelationParentId2 = entity.TrialReadingCriterionId
                });
            }



            #endregion



            #region 阅片结果


            #region  暂时不区分标准

            //保存影像质量   多条记录，只记录一条稽查   
            if (entitys.Any(x => x.Entity.GetType() == typeof(ReadingTaskQuestionAnswer)))
            {
                // 保存影像质量 、  修改整体肿瘤评估结果 、  非dicom 保存检查批次阅片结果
                if (_userInfo.RequestUrl == "ReadingImageTask/changeDicomReadingQuestionAnswer"
                    || _userInfo.RequestUrl == "ReadingImageTask/saveImageQuality"
                    || _userInfo.RequestUrl == "ReadingImageTask/saveVisitTaskQuestions"
                    || _userInfo.RequestUrl == "ReadingImageTask/changeCalculationAnswer")
                {
                    var type = AuditOpt.Add;

                    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)).Select(t => new
                    {
                        t.QuestionName,
                        QuestionId = t.Id,
                        t.DictionaryCode,
                        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.ReadingQuestionTrial.Unit,
                            t.ReadingQuestionTrial.CustomUnit,
                            t.DictionaryCode,
                            t.QuestionName,
                            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= u.AnswerType== "upload"? "❄❅❆❇❈❉❊" +t.Answer:t.Answer,
                                   u.QuestionName,
                                   u.DictionaryCode,
                                   u.ShowOrder,
                                   t.RowId
                               }
                               ).OrderBy(t => t.RowId).ThenBy(t=>t.ShowOrder).ToList();



                    }

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

                        ObjectRelationParentId = x.VisitTaskId,

                        TrialReadingCriterionId = x.ReadingQuestionCriterionTrialId,

                        ExtraIndentification = extraIdentification,

                    }, new { QuestionAnswerList = taskQuestionAnswerList.Join(quesionList, t => t.ReadingQuestionTrialId, u => u.QuestionId, (t, u) => 
                    new { Answer = u.AnswerType == "upload" ? "❄❅❆❇❈❉❊" + t.Answer : t.Answer, u.DictionaryCode, u.QuestionName, u.ShowOrder }).OrderBy(t => t.ShowOrder).ToList()
                     ,
                        TableQuestionAndAnswerList = tableQuesionAndAnswerList
                    }
                         );

                    
                }


            }

            //病灶这里操作  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();


                //获取表格问题名称 组合成数组
                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.ReadingQuestionTrial.Unit,
                    t.ReadingQuestionTrial.CustomUnit,
                    t.DictionaryCode,
                    t.QuestionName,
                    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;
                if (entity.SplitRowId != null)
                {

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

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

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



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

                    ObjectRelationParentId = x.VisitTaskId,

                    TrialReadingCriterionId = trialReadingCriterionId,

                    ObjectRelationParentId2 = x.QuestionId

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

                //需要手动添加病灶类型
                tableQuestionAnswerList.Join(tableQuesionList, t => t.TableQuestionId, u => u.QuestionId, (t, u) =>
                new
                {
                    //如果问题类型是附件 特殊处理 方便前端解析
                    Answer = u.AnswerType == "upload" ? "❄❅❆❇❈❉❊" + t.Answer : t.Answer,
                    //t.Answer        /*u.Unit==ValueUnit.Custom? t.Answer+u.CustomUnit:(u.Unit != ValueUnit.None|| u.Unit != null)*/,
                    u.QuestionName,
                    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.Where(t => t.QuestionId != null).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
                    {
                        t.QuestionName,
                        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,
                            u.ReadingQuestionTrial.QuestionName,
                            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.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.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


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

                var entity = item.Entity as VisitTask;

                var obj = new object() { };

                //检查批次任务-- 非Dicom 阅片
                if (_userInfo.RequestUrl == "ReadingImageTask/SubmitVisitTaskQuestions" && entity.ReadingTaskState != ReadingTaskState.HaveSigned && type == AuditOpt.Update)
                {
                    //提交检查批次任务的时候 会多次更新同一个记录 只记录最后一次
                    return;
                }



                //Dicom 阅片  签名
                if (_userInfo.RequestUrl == "ReadingImageTask/SubmitDicomVisitTask")
                {
                    //跳转阅片结果需要该参数
                    var subjectCode = _dbContext.Subject.Where(t => t.Id == entity.SubjectId).Select(t => t.Code).First();
                    obj = new { SubjectCode = subjectCode };
                }

                #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 = new { R1 = r1.FullName, R2 = r2.FullName, SelectResult = r1.Id == entity.JudgeResultTaskId ? "R1" : "R2" };
                }

                #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


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

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

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

                    ObjectRelationParentId2 = entity.DoctorUserId,

                    ObjectRelationParentId3 = entity.TrialReadingCriterionId,

                }, obj);
            }



            #endregion


        }

        /// <summary>
        /// 插入稽查实体
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="data">数据</param>
        /// <param name="type">类型</param>
        /// <param name="expression">表达式</param>
        /// <param name="otherItem">其他对象</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);
            }

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

            inspection.Identification = await GetInspectionRecordIdentificationAsync(inspection, entityObj, type, inspection.IsDistinctionInterface) + inspection.ExtraIndentification;

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

            //var generalData = await GetInspectionGeneralDataAsync(inspection);

            var generalData = await GetInspectionGeneralGuidAsync(inspection);

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

            #region 处理标识

            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.RealName;
            inspection.RoleName = _userInfo.UserTypeShortName;
            inspection.CreateUserId = _userInfo.Id;
            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;

            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()
            {
                SiteId = inspection.SiteId,
                SubjectId = inspection.SubjectId,
                SubjectVisitId = inspection.SubjectVisitId,
                TrialId = inspection.TrialId,
                TrialReadingCriterionId = inspection.TrialReadingCriterionId
            };




            if (inspection.VisitTaskId != null)
            {

                if (generalData.TrialId == null || generalData.SiteId == 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.SiteId, x.TrialId, x.SourceSubjectVisitId, ReadModuleSubjectVisitId = (Guid?)x.ReadModule.SubjectVisitId, x.TrialReadingCriterionId }).FirstOrDefaultAsync();

                    generalData.TrialReadingCriterionId = info?.TrialReadingCriterionId ?? generalData.TrialReadingCriterionId;
                    generalData.TrialId = info?.TrialId ?? generalData.TrialId;
                    generalData.SubjectId = info?.SubjectId ?? generalData.SubjectId;
                    generalData.SiteId = info?.SiteId ?? generalData.SiteId;
                    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 _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.SiteId == null || generalData.SubjectId == null)
                {
                    var info = await _dbContext.SubjectVisit.Where(x => x.Id == generalData.SubjectVisitId).Select(x =>
                  new { x.SubjectId, x.SiteId, x.TrialId, SubjectCode = x.Subject.Code, TrialSiteCode = x.Subject.TrialSite.TrialSiteCode }).FirstOrDefaultAsync();


                    generalData.TrialId = info?.TrialId ?? generalData.TrialId;
                    generalData.SiteId = info?.SiteId ?? generalData.SiteId;
                    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.SiteId == null)
                {
                    var info = await _dbContext.Subject.Where(x => x.Id == generalData.SubjectId).Select(x => new { SubjectId = x.Id, x.SiteId, x.TrialId, SubjectCode = x.Code, TrialSiteCode = x.TrialSite.TrialSiteCode }).FirstOrDefaultAsync();

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

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

                  


                    

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


            }

            return generalData;
        }



        /// <summary>
        /// 获取稽查记录的标识符   部分业务会进行特殊处理
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetInspectionRecordIdentificationAsync<T>(InspectionConvertDTO inspection, T entityObj, string type, bool IsDistinctionInterface = true)
        {
            var entityTypeName = entityObj.GetType().Name;

            #region 标识符特殊处理

            //文档签署这块，不区分系统和项目的 需要处理为同一个标识
            if (typeof(T) == typeof(TrialDocConfirmedUser) || typeof(T) == typeof(SystemDocConfirmedUser))
            {
                entityTypeName = "New/" + "UserSigned";
            }

            switch (entityObj.GetType().Name)
            {
                case nameof(TrialDocConfirmedUser):
                case nameof(SystemDocConfirmedUser):

                    var softDelete = entityObj as ISoftDelete;

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

                    break;

                case nameof(SystemBasicData):
                    var basicData = entityObj as SystemBasicData;
                    type = type + (basicData.ParentId == null ? "/parent" : string.Empty);
                    break;

                //case nameof(Trial):
                //    var trial = entityObj as Trial;
                //    Guid id = trial.Id;
                //    var oldentity = await _dbContext.Trial.Where(x => x.Id == id).Select(t => new { t.IsTrialBasicLogicConfirmed, t.IsTrialProcessConfirmed, t.IsTrialUrgentConfirmed }).FirstOrDefaultAsync();
                //    switch (_userInfo.RequestUrl.ToLower())
                //    {
                //        case "configtrialbasicinfo/configtrialbasicinfoconfirm":
                //            type = type + "/" + oldentity.IsTrialBasicLogicConfirmed.ToString();
                //            break;
                //        //case "configtrialbasicinfo/configtrialprocessinfoconfirm":
                //        //    type = type + "/" + oldentity.IsTrialProcessConfirmed.ToString();
                //        //    break;
                //        case "configtrialbasicinfo/configtrialurgentinfoconfirm":
                //            type = type + "/" + oldentity.IsTrialUrgentConfirmed.ToString();
                //            break;
                //    }
                //    break;

                //case nameof(ReadingQuestionTrial):

                //    var trialReadingQuestion = entityObj as ReadingQuestionTrial;

                //    switch (_userInfo.RequestUrl)
                //    {
                //        case "ReadingImageTask/setTrialCriterionJudgeQuestionAnswerGroup":

                //            if (trialReadingQuestion.JudgeType == JudgeTypeEnum.None)
                //            {
                //                type = type + "/" + "Reset";
                //            }

                //            break;
                //    }
                //    break;




                #region 检查批次相关

                //  对话消息区分用户类型
                case nameof(CheckChallengeDialog):
                    type = type + "/(" + _userInfo.UserTypeShortName + ")";

                    var checkDialog = entityObj as CheckChallengeDialog;

                    switch (_userInfo.RequestUrl.ToLower())
                    {
                        case "qcoperation/closecheckchallenge":

                            inspection.Reason = checkDialog.TalkContent.Substring(checkDialog.TalkContent.LastIndexOf(':') + 1);
                            break;
                    }

                    break;

                //  对话消息区分用户类型
                case nameof(QCChallengeDialog):
                    type = type + "/(" + _userInfo.UserTypeShortName + ")";

                    var dialog = entityObj as QCChallengeDialog;
                    switch (_userInfo.RequestUrl.ToLower())
                    {
                        case "qcoperation/closeqcchallenge":

                            inspection.Reason = dialog.TalkContent.Substring(dialog.TalkContent.LastIndexOf(':') + 1);
                            break;
                    }

                    break;


                case nameof(SubjectVisit):
                    var sv = entityObj as SubjectVisit;
                    switch (_userInfo.RequestUrl.ToLower())
                    {
                        //待处理？
                        case "qcoperation/qcpassedorfailed":

                            type = type + "/" + (40 % (int)sv.AuditState).ToString();

                            break;

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

                            inspection.Reason = sv.ManualPassReason;
                            break;

                        //领取或者取消QC任务
                        case "qcoperation/obtainorcancelqctask":
                            type = type + "/" + sv.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 (sv.CheckChallengeState == CheckChanllengeTypeEnum.CRCWaitPMReply || sv.CheckChallengeState == CheckChanllengeTypeEnum.PMWaitCRCReply)
                    {
                        //发送对话  修改质疑状态  不需要区分接口
                        IsDistinctionInterface = false;

                        type = type + "/ModifyCheckChallengeState";
                    }
                    break;

                case nameof(NoneDicomStudy):
                    switch (_userInfo.RequestUrl.ToLower())
                    {
                        case "nonedicomstudy/addorupdatenonedicomstudy":
                            type = type + "/(" + _userInfo.UserTypeShortName + ")";
                            break;
                    }
                    break;
                #endregion


                #region 阅片任务相关

                //任务表
                case nameof(VisitTask):

                    var visitTask = entityObj as VisitTask;


                    if (type == AuditOpt.Add)
                    {
                        //生成一致性分析任务
                        if (visitTask.IsSelfAnalysis == true)
                        {
                            type = type + "/" + "SelfAnalysis";
                        }
                        else if (visitTask.IsSelfAnalysis == false)
                        {
                            type = type + "/" + "GroupAnalysis";
                        }
                        else
                        {
                            type = type + "/" + "NotAnalysis";
                        }

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


                    }
                    else
                    {
                        switch (_userInfo.RequestUrl)
                        {
                            //申请重阅
                            case "VisitTask/applyReReading":
                                type = type + "/" + (int)visitTask.ReReadingApplyState;
                                break;


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

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

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

                                break;
                        }

                    }



                    break;

                //重阅记录表
                case nameof(VisitTaskReReading):

                    var visitTaskReReading = entityObj as VisitTaskReReading;

                    switch (_userInfo.RequestUrl)
                    {
                        case "VisitTask/applyReReading":
                            type = type + "/" + (int)visitTaskReReading.RequestReReadingType;
                            break;

                        case "VisitTask/ConfirmReReading":

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

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

                            if (visitTaskReReading.RequestReReadingResultEnum == RequestReReadingResult.Agree)
                            {
                                type = type + "/" + 1;

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

                    break;

                //一致性分析规则
                case nameof(TaskConsistentRule):

                    var taskConsistentRule = entityObj as TaskConsistentRule;

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

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

                    break;
                    #endregion


                    ////标准 器官病灶表
                    //case nameof(CriterionNidus):

                    //    var criterionNidus = entityObj as CriterionNidus;

                    //    if (criterionNidus.IsSystemCriterion == false)
                    //    {
                    //        type = type + "/IsTrial";
                    //    }

                    //    break;

                    ////系统 项目公用  
                    //case nameof(ReadingCriterionDictionary):

                    //    var readingCriterionDictionary = entityObj as ReadingCriterionDictionary;

                    //    if (readingCriterionDictionary.IsSystemCriterion)
                    //    {
                    //        type = $"{type}/{readingCriterionDictionary.ParentCode}";
                    //    }

                    //    break;


            }

            #endregion

            if (IsDistinctionInterface)
            {
                return $"{_userInfo.RequestUrl}/{entityTypeName}/{type}";

            }
            else
            {
                return $"{entityTypeName}/{type}";
            }
        }


        /// 往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;

        }



    }
}
