﻿﻿using IRaCIS.Core.Domain.BaseModel;
using IRaCIS.Core.Domain.Models;
using IRaCIS.Core.Infra.EFCore.Common;
using IRaCIS.Core.Infrastructure.Encryption;
using IRaCIS.Core.Infrastructure.Extention;
using Microsoft.EntityFrameworkCore.Metadata.Conventions;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Microsoft.VisualBasic;
using Newtonsoft.Json;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;

namespace IRaCIS.Core.Infra.EFCore;

#region 连接池废弃 
/// <summary>
/// 报错，添加subject 报错,重复添加访视
/// </summary>
//public class IRaCISDBScopedFactory : IDbContextFactory<IRaCISDBContext>
//{

//    private readonly IDbContextFactory<IRaCISDBContext> _pooledFactory;
//    private readonly IUserInfo _userInfo;

//    public IRaCISDBScopedFactory(IDbContextFactory<IRaCISDBContext> pooledFactory,IUserInfo userInfo)
//    {
//        _pooledFactory = pooledFactory;
//        _userInfo = userInfo;
//    }

//    public IRaCISDBContext CreateDbContext()
//    {
//        var context = _pooledFactory.CreateDbContext();
//        context._userInfo = _userInfo;
//        return context;
//    }
//}
#endregion


public class IRaCISDBContext : DbContext
{


    public IRaCISDBContext(DbContextOptions<IRaCISDBContext> options) : base(options)
    {
    }
    /// <summary>
    /// efcore codefirst 防止数据注解过多配置，全局统一配置
    /// </summary>
    /// <param name="configurationBuilder"></param>
    protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
    {
        //decimal 不配置，默认精度是18,2
        //configurationBuilder.Conventions.Add(_ => new DecimalPrecisionConvention(18,2));
        //针对字符串使用默认的长度配置为200，如果标注了StringLength 其他长度，就是标注的长度，如果标注了MaxLength 那么就是nvarcharMax
        configurationBuilder.Conventions.Add(_ => new DefaultStringLengthConvention(400));

        //configurationBuilder.Conventions.Add(_ => new RemoveForeignKeyConvention());

        //控制外键索引生成与否 
        //https://learn.microsoft.com/zh-cn/ef/core/modeling/relationships/conventions?utm_source=chatgpt.com
        configurationBuilder.Conventions.Remove(typeof(ForeignKeyIndexConvention));



    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        modelBuilder.Entity<TestLength>(entity =>
        {
            // 使用部分加密值转换器，前 2 个字符不加密，方便模糊搜索
            entity.Property(e => e.Name).HasConversion(new PartialEncryptionConverter(2));

            //entity.OwnsMany(x => x.TestJsonObjectLsit, ownedNavigationBuilder =>
            //{
            //    ownedNavigationBuilder.ToJson();
            //});

            entity.Property(e => e.TestJsonObjectLsit).HasConversion(v => v == null ? "[]" : JsonConvert.SerializeObject(v),
                v => string.IsNullOrEmpty(v) ? null : JsonConvert.DeserializeObject<List<TestJsonObject>>(v));
        });

        modelBuilder.Entity<Trial>(entity =>
        {
            //项目术语配置
            entity.OwnsMany(x => x.TrialObjectNameList, ownedNavigationBuilder =>
            {
                ownedNavigationBuilder.ToJson();
            });

            entity.OwnsMany(x => x.StudyNameList, ownedNavigationBuilder =>
            {
                ownedNavigationBuilder.ToJson();
            });
        });

        modelBuilder.Entity<ReadingQuestionCriterionTrial>(entity =>
        {
            //默认SegmentName
            entity.Property(e => e.DefaultSegmentName).HasConversion(
                v => v == null ? null : JsonConvert.SerializeObject(v),
                v => string.IsNullOrEmpty(v) ? new DefaultSegmentNameDto() { SegmentNameList = new List<string> { "Segment" } } : JsonConvert.DeserializeObject<DefaultSegmentNameDto>(v)
            );
        });

        modelBuilder.Entity<SegmentationVersion>(entity =>
        {
            entity.Property(e => e.SegmentList).HasConversion(
                v => v == null ? null : JsonConvert.SerializeObject(v),
                v => string.IsNullOrEmpty(v) ? new List<SegmentVersionData>() {} : JsonConvert.DeserializeObject<List<SegmentVersionData>>(v)
            );
        });

        modelBuilder.Entity<ReadingQuestionVisitJudgeRule>(entity =>
        {
            entity.Property(e => e.AnswerCombination).HasConversion(
                v => v == null ? null : JsonConvert.SerializeObject(v),
                v => string.IsNullOrEmpty(v) ? new List<AnswerCombinationDto>() { } : JsonConvert.DeserializeObject<List<AnswerCombinationDto>>(v)
            );
        });

        #region pgsql codefirst 配置 暂时屏蔽
        //if (base.Database.IsNpgsql())
        //{
        //    modelBuilder.HasPostgresExtension("uuid-ossp");

        //    //保证pgsql 生成的时间默认为timestamp 而不是  timestamp with time zone
        //    foreach (var entityType in modelBuilder.Model.GetEntityTypes())
        //    {
        //        foreach (var property in entityType.GetProperties())
        //        {
        //            if (property.ClrType == typeof(DateTime) || property.ClrType == typeof(DateTime?))
        //            {
        //                property.SetColumnType("timestamp without time zone");
        //            }
        //        }
        //    }
        //}
        #endregion


        #region decimal 自定义精度，适配多种数据库

        foreach (var entityType in modelBuilder.Model.GetEntityTypes())
        {
            foreach (var property in entityType.GetProperties())
            {
                // 如果属性类型是 decimal 或 nullable decimal
                if (property.ClrType == typeof(decimal) || property.ClrType == typeof(decimal?))
                {
                    // 获取自定义的 DecimalPrecisionAttribute
                    var precisionAttr = property.PropertyInfo?.GetCustomAttributes(typeof(DecimalPrecisionAttribute), false)
                        .FirstOrDefault() as DecimalPrecisionAttribute;

                    if (precisionAttr != null)
                    {
                        property.SetPrecision(precisionAttr.Precision);
                        property.SetScale(precisionAttr.Scale);
                    }
                    else
                    {
                        // 默认的精度设置
                        property.SetPrecision(18);
                        property.SetScale(2);
                    }
                }
            }
        }

        //用户名区分大小写
        modelBuilder.Entity<IdentityUser>(entity =>
        {
            entity.Property(e => e.UserName)
              .UseCollation("Chinese_PRC_CS_AS");
        });
        #endregion

        //遍历实体模型手动配置
        var typesToRegister = Assembly.GetExecutingAssembly().GetTypes().Where(q => q.GetInterface(typeof(IEntityTypeConfiguration<>).FullName) != null);
        foreach (var type in typesToRegister)
        {
            dynamic configurationInstance = Activator.CreateInstance(type);
            modelBuilder.ApplyConfiguration(configurationInstance);
        }

        base.OnModelCreating(modelBuilder);

        //软删除筛选器通常依赖于实体模型的完整定义（例如属性映射、继承关系等）



        foreach (var entityType in modelBuilder.Model.GetEntityTypes())
        {
            #region 修改Id 聚集索引-> Id非聚集，CreateTime聚集索引，方便分区

            // 1️ 所有 Entity：Id 为主键（非聚集）
            if (typeof(Entity).IsAssignableFrom(entityType.ClrType))
            {
                modelBuilder.Entity(entityType.ClrType)
                    .HasKey(nameof(Entity.Id))
                    .IsClustered(false); 
            }

            // 2️ 所有 IAuditAdd：CreateTime 为聚集索引
            if (typeof(IAuditAdd).IsAssignableFrom(entityType.ClrType))
            {
                modelBuilder.Entity(entityType.ClrType)
                    .HasIndex(nameof(IAuditAdd.CreateTime))
                    .IsClustered(); 
            }

            #endregion

            // 软删除配置
            if (typeof(ISoftDelete).IsAssignableFrom(entityType.ClrType))
            {
                //entityType.AddSoftDeleteQueryFilter();

                // 动态创建表达式：e => e.IsDeleted==false
                var parameter = Expression.Parameter(entityType.ClrType, "e");
                var property = Expression.Property(parameter, nameof(ISoftDelete.IsDeleted));
                var filter = Expression.Lambda(
                    Expression.Equal(property, Expression.Constant(false)),
                    parameter);

                // 应用全局查询筛选器
                modelBuilder.Entity(entityType.ClrType).HasQueryFilter(filter);

                //Console.WriteLine($"实体应用软删除：{entityType.ClrType.Name}");

            }
            foreach (var navigation in entityType.GetNavigations())
            {

                if (navigation.IsCollection) continue;

                #region 有问题 
                // 比如 e.SourceSubjectVisit.IsDeleted == False  还会导致 dicom 查询增加额外很多的连表  因为访视  项目  项目中心，dicom 都是软删除
                //
                //// 配置基于导航属性的软删除查询筛选器
                //if (typeof(ISoftDelete).IsAssignableFrom(navigation.TargetEntityType.ClrType))
                //{
                //    var clrType = entityType.ClrType;
                //    var targetType = navigation.TargetEntityType.ClrType;

                //    //e => e.Subject.IsDeleted==false
                //    var parameterNav = Expression.Parameter(clrType, "e");
                //    var navigationProperty = Expression.Property(parameterNav, navigation.Name);
                //    var navigationFilter = Expression.Equal(
                //        Expression.Property(navigationProperty, nameof(ISoftDelete.IsDeleted)),
                //        Expression.Constant(false));

                //    var filterNav = Expression.Lambda(navigationFilter, parameterNav);

                //    modelBuilder.Entity(clrType).HasQueryFilter(filterNav);

                //    Console.WriteLine($"实体应用软删除：{entityType.ClrType.Name}   导航属性{filterNav}");
                //}

                #endregion


            }

            if (typeof(Entity).IsAssignableFrom(entityType.ClrType))
            {
                modelBuilder.Entity(entityType.ClrType).Property<Guid>(nameof(Entity.Id)).HasValueGenerator<MySequentialGuidValueGenerator>();
            }
            if (typeof(IEntitySeqId).IsAssignableFrom(entityType.ClrType))
            {
                modelBuilder.Entity(entityType.ClrType).Property<Guid>(nameof(IEntitySeqId.SeqId)).HasValueGenerator<MySequentialGuidValueGenerator>();
            }
        }

    }

    #region  获取表名 和字段名 优化

    /// <summary>
    /// 直接获取代码定义的模型，以及表上定义的Description 获取表信息 以及备注
    /// </summary>
    /// <returns></returns>
    public List<TableList> GetContextTablesList()
    {
        var tableList = new List<TableList>();

        foreach (var entityType in this.Model.GetEntityTypes())
        {
            var clrType = entityType.ClrType;
            var tableName = entityType.GetTableName();

            var tableDescription = clrType.GetCustomAttribute<DescriptionAttribute>()?.Description ?? string.Empty;

            tableList.Add(new TableList
            {
                Name = tableName,
                Remake = tableDescription,
            });
        }

        return tableList;
    }

    /// <summary>
    /// 直接获取代码定义的某个表的属性，以及属性上定义的Description 获取备注
    /// </summary>
    /// <returns></returns>
    public List<TableList> GetContextTableColumnList(string tableName)
    {
        var tableColumList = new List<TableList>();

        var entityType = this.Model.GetEntityTypes().FirstOrDefault(t => t.GetTableName().ToLower() == tableName.ToLower());

        if (entityType == null)
        {
            throw new ArgumentException($"Table '{tableName}' not found.");
        }

        var clrType = entityType.ClrType;

        foreach (var property in entityType.GetProperties())
        {
            var columnName = property.GetColumnName();
            var columnDescription = clrType.GetProperty(property.Name)?.GetCustomAttribute<DescriptionAttribute>()?.Description ?? string.Empty;

            tableColumList.Add(new TableList
            {
                Name = columnName,
                Remake = columnDescription,
            });
        }

        return tableColumList.OrderBy(t => t.Name).ToList();
    }
    #endregion


    #region Doctor
    public virtual DbSet<Dictionary> Dictionary { get; set; }
    public virtual DbSet<Doctor> Doctor { get; set; }

    public virtual DbSet<DoctorSummarize> DoctorSummarize { get; set; }

    public virtual DbSet<DoctorCriterionFile> DoctorCriterionFile { get; set; }
    public virtual DbSet<DoctorDictionary> DoctorDictionary { get; set; }
    public virtual DbSet<Postgraduate> Postgraduate { get; set; }
    public virtual DbSet<Education> Education { get; set; }
    public virtual DbSet<ResearchPublication> ResearchPublications { get; set; }
    public virtual DbSet<TrialExperience> TrialExperience { get; set; }

    public virtual DbSet<Vacation> Vacation { get; set; }

    public virtual DbSet<Attachment> Attachment { get; set; }
    public virtual DbSet<TrialExperienceCriteria> TrialExperienceCriteria { get; set; }




    #endregion

    #region Enroll

    public virtual DbSet<Workload> DoctorWorkload { get; set; }
    public virtual DbSet<Enroll> Enroll { get; set; }

    public virtual DbSet<EnrollReadingCategory> EnrollReadingCategory { get; set; }


    public virtual DbSet<EnrollDetail> EnrollDetails { get; set; }




    #endregion


    #region Reading

    public virtual DbSet<ReadingUserConfig> ReadingUserConfig { get; set; }
    public virtual DbSet<Segmentation> Segmentation { get; set; }

    public virtual DbSet<SegmentationVersion> SegmentationVersion { get; set; }

    public virtual DbSet<Segment> Segment { get; set; }

    public virtual DbSet<SegmentBinding> SegmentBinding { get; set; }


    public virtual DbSet<TrialCriterionKeyFile> TrialCriterionKeyFile { get; set; }

    public virtual DbSet<SystemCriterionKeyFile> SystemCriterionKeyFile { get; set; }

    public virtual DbSet<CriterionKeyFileRead> CriterionKeyFileRead { get; set; }
    public virtual DbSet<TrialCriterionDictionaryCode> TrialCriterionDictionaryCode { get; set; }

    public virtual DbSet<ReadingImportFile> ReadingImportFile { get; set; }

    public virtual DbSet<ReadingCustomTag> ReadingCustomTag { get; set; }
    public virtual DbSet<SystemCriterionDictionaryCode> SystemCriterionDictionaryCode { get; set; }
    public virtual DbSet<ReadingTaskRelation> ReadingTaskRelation { get; set; }
    public virtual DbSet<OrganInfo> OrganInfo { get; set; }

    public virtual DbSet<ReadingSystemCriterionDictionary> ReadingSystemCriterionDictionary { get; set; }
    public virtual DbSet<ReadingTableAnswerRowInfo> ReadingTableAnswerRowInfo { get; set; }
    public virtual DbSet<OrganTrialInfo> OrganTrialInfo { get; set; }
    public virtual DbSet<ReadingTableQuestionSystem> ReadingTableQuestionSystem { get; set; }
    public virtual DbSet<ReadingPeriodSet> ReadingPeriodSet { get; set; }

    public virtual DbSet<ReadingTaskQuestionAnswer> ReadingTaskQuestionAnswer { get; set; }
    public virtual DbSet<ReadingPeriodPlan> ReadingPeriodPlan { get; set; }

    public virtual DbSet<ReadingClinicalData> ReadingClinicalData { get; set; }

    public virtual DbSet<ReadingOncologyTaskInfo> ReadingOncologyTaskInfo { get; set; }
    public virtual DbSet<ReadingGlobalTaskInfo> ReadingGlobalTaskInfo { get; set; }
    public virtual DbSet<ReadingQuestionCriterionSystem> ReadingQuestionCriterionSystem { get; set; }

    public virtual DbSet<ReadingQuestionCriterionTrial> ReadingQuestionCriterionTrial { get; set; }

    public virtual DbSet<ReadingQuestionSystem> ReadingQuestionSystem { get; set; }

    public virtual DbSet<ReadingQuestionTrial> ReadingQuestionTrial { get; set; }

    public virtual DbSet<ReadingQuestionVisitJudgeRule> ReadingQuestionVisitJudgeRule { get; set; }


    public virtual DbSet<ReadingClinicalDataPDF> ReadingClinicalDataPDF { get; set; }
    public virtual DbSet<ReadingConsistentClinicalData> ReadingConsistentClinicalData { get; set; }
    public virtual DbSet<ReadingConsistentClinicalDataPDF> ReadingConsistentClinicalDataPDF { get; set; }

    public virtual DbSet<ReadingJudgeInfo> ReadingJudgeInfo { get; set; }

    public virtual DbSet<ReadingNoneDicomMark> ReadingNoneDicomMark { get; set; }

    public virtual DbSet<ReadingNoneDicomMarkBinding> ReadingNoneDicomMarkBinding { get; set; }

    public virtual DbSet<ReadModule> ReadModule { get; set; }


    public virtual DbSet<ClinicalDataTrialSet> ClinicalDataTrialSet { get; set; }

    public virtual DbSet<ClinicalDataSystemSet> ClinicalDataSystemSet { get; set; }

    public virtual DbSet<ReadingMedicineSystemQuestion> ReadingMedicineSystemQuestion { get; set; }

    public virtual DbSet<ReadingMedicineTrialQuestion> ReadingMedicineTrialQuestion { get; set; }

    public virtual DbSet<ReadingMedicineQuestionAnswer> ReadingMedicineQuestionAnswer { get; set; }

    public virtual DbSet<ReadingMedicalReviewDialog> ReadingMedicalReviewDialog { get; set; }

    public virtual DbSet<CriterionNidusSystem> CriterionNidusSystem { get; set; }

    public virtual DbSet<CriterionNidusTrial> CriterionNidusTrial { get; set; }

    public virtual DbSet<ReadingTrialCriterionDictionary> ReadingTrialCriterionDictionary { get; set; }

    public virtual DbSet<ReadingTableQuestionTrial> ReadingTableQuestionTrial { get; set; }


    public virtual DbSet<TumorAssessment_RECIST1Point1BM> TumorAssessment_RECIST1Point1BM { get; set; }
    public virtual DbSet<TumorAssessment_RECIST1Point1> TumorAssessment_RECIST1Point1 { get; set; }

    public virtual DbSet<TumorAssessment_IRECIST1Point1> TumorAssessment_IRECIST1Point1 { get; set; }

    public virtual DbSet<TrialClinicalDataSetCriterion> TrialClinicalDataSetCriterion { get; set; }

    public virtual DbSet<TrialCriterionAdditionalAssessmentType> TrialCriterionAdditionalAssessmentType { get; set; }

    public virtual DbSet<SubjectCriteriaEvaluation> SubjectCriteriaEvaluation { get; set; }
    public virtual DbSet<SubjectAdditionalEvaluationResult> SubjectAdditionalEvaluationResult { get; set; }
    public virtual DbSet<SubjectCriteriaEvaluationVisitFilter> SubjectCriteriaEvaluationVisitFilter { get; set; }
    public virtual DbSet<SubjectCriteriaEvaluationVisitStudyFilter> SubjectCriteriaEvaluationVisitStudyFilter { get; set; }

    public virtual DbSet<ReadingTaskQuestionMark> ReadingTaskQuestionMark { get; set; }


    //public virtual DbSet<TrialClinicalDataCriterion> TrialClinicalDataCriterion { get; set; }
    //public virtual DbSet<SystemClinicalDataCriterion> SystemClinicalDataCriterion { get; set; }

    #endregion

    #region Subject and Visit and study
    public virtual DbSet<StudyMonitor> StudyMonitor { get; set; }

    public virtual DbSet<Subject> Subject { get; set; }
    public virtual DbSet<VisitStage> VisitPlans { get; set; }
    public virtual DbSet<VisitPlanInfluenceStudy> VisitPlanInfluenceStudy { get; set; }

    public virtual DbSet<VisitPlanInfluenceStat> VisitPlanInfluenceStat { get; set; }

    public virtual DbSet<NoneDicomStudyFile> NoneDicomStudyFile { get; set; }
    public virtual DbSet<NoneDicomStudy> NoneDicomStudy { get; set; }
    public virtual DbSet<PreviousPDF> PreviousPDF { get; set; }
    public virtual DbSet<PreviousSurgery> PreviousSurgery { get; set; }
    public virtual DbSet<PreviousOther> PreviousOther { get; set; }
    public virtual DbSet<PreviousHistory> PreviousHistory { get; set; }

    public virtual DbSet<DicomStudy> DicomStudys { get; set; }
    public virtual DbSet<DicomSeries> DicomSeries { get; set; }
    public virtual DbSet<DicomInstance> DicomInstances { get; set; }
    public virtual DbSet<ImageShare> ImageShare { get; set; }


    #endregion

    #region Management
    public virtual DbSet<VerificationCode> VerificationCodes { get; set; }
    public virtual DbSet<Menu> MenuFunctions { get; set; }
    public virtual DbSet<UserTypeMenu> UserTypeMenuFunction { get; set; }
    public virtual DbSet<UserRole> Users { get; set; }
    public virtual DbSet<UserType> UserType { get; set; }




    #endregion

    #region Institution


    public virtual DbSet<Hospital> Hospitals { get; set; }
    public virtual DbSet<CRO> CROCompany { get; set; }
    public virtual DbSet<Sponsor> Sponsor { get; set; }

    #endregion

    #region Trial
    public virtual DbSet<Trial> Trial { get; set; }


    public virtual DbSet<TrialDictionary> TrialDictionary { get; set; }
    public virtual DbSet<TrialStatusDetail> TrialDetail { get; set; }
    public virtual DbSet<TrialUserRole> UserTrial { get; set; }

    public virtual DbSet<TrialDictionary> ProjectDictionary { get; set; }

    public virtual DbSet<TrialSiteUserRole> UserTrialSite { get; set; }
    public virtual DbSet<TrialSite> TrialSite { get; set; }

    public virtual DbSet<ReadingPeriodSite> ReadingPeriodSite { get; set; }

    public virtual DbSet<Site> Site { get; set; }

    public virtual DbSet<UserRole> User { get; set; }

    public virtual DbSet<UserPassWordLog> UserPassWordLog { get; set; }

    public virtual DbSet<TrialSiteUserSurvey> TrialSiteUserSurvey { get; set; }
    public virtual DbSet<TrialSiteEquipmentSurvey> TrialSiteEquipmentSurvey { get; set; }
    public virtual DbSet<TrialSiteSurvey> TrialSiteSurvey { get; set; }




    #endregion

    #region Financial
    public virtual DbSet<ReviewerPayInformation> ReviewerPayInformation { get; set; }
    public virtual DbSet<RankPrice> RankPrice { get; set; }
    public virtual DbSet<TrialPaymentPrice> TrialPaymentPrice { get; set; }
    public virtual DbSet<VolumeReward> AwardPrice { get; set; }
    public virtual DbSet<Payment> Payment { get; set; }
    public virtual DbSet<PaymentDetail> PaymentDetail { get; set; }
    public virtual DbSet<ExchangeRate> ExchangeRate { get; set; }
    public virtual DbSet<TrialRevenuesPrice> TrialRevenuesPrice { get; set; }
    public virtual DbSet<PaymentAdjustment> PaymentAdjustment { get; set; }
    public virtual DbSet<TrialRevenuesPriceVerification> TrialRevenuesPriceVerification { get; set; }


    #endregion

    #region QC

    public virtual DbSet<TrialQCQuestion> TrialQCQuestionConfigure { get; set; }
    public virtual DbSet<QCQuestion> QCQuestionConfigure { get; set; }
    public virtual DbSet<TrialQCQuestionAnswer> TrialQCQuestionAnswer { get; set; }
    public virtual DbSet<CheckChallengeDialog> CheckChallengeDialog { get; set; }
    #endregion


    #region QA

    public virtual DbSet<QCChallengeDialog> QCChallengeDialog { get; set; }
    //public virtual DbSet<QANotice> QATemplateDictionary { get; set; }
    public virtual DbSet<QCChallenge> QCChallenge { get; set; }
    public virtual DbSet<SubjectVisit> SubjectVisit { get; set; }
    #endregion

    #region ClinicalQuestion
    public virtual DbSet<TrialClinicalQuestion> TrialClinicalQuestion { get; set; }

    public virtual DbSet<SystemClinicalQuestion> SystemClinicalQuestion { get; set; }

    public virtual DbSet<SystemClinicalTableQuestion> SystemClinicalTableQuestion { get; set; }

    public virtual DbSet<TrialClinicalTableQuestion> TrialClinicalTableQuestion { get; set; }

    public virtual DbSet<ClinicalQuestionAnswer> ClinicalQuestionAnswer { get; set; }

    public virtual DbSet<ClinicalAnswerRowInfo> ClinicalAnswerRowInfo { get; set; }

    public virtual DbSet<ClinicalTableAnswer> ClinicalTableAnswer { get; set; }

    public virtual DbSet<ReadModuleCriterionFrom> ReadModuleCriterionFrom { get; set; }
    public virtual DbSet<ClinicalForm> ClinicalForm { get; set; }
    #endregion


    #region Document
    public virtual DbSet<SystemDocument> SystemDocument { get; set; }
    public virtual DbSet<SystemDocumentAttachment> SystemDocumentAttachment { get; set; }
    public virtual DbSet<TrialDocument> TrialDocument { get; set; }

    public virtual DbSet<TrialDocumentAttachment> TrialDocumentAttachment { get; set; }
    public virtual DbSet<TrialDocNeedConfirmedUserType> TrialDocUserTypeConfirm { get; set; }
    public virtual DbSet<SystemDocNeedConfirmedUserType> SystemDocNeedConfirmedUserType { get; set; }

    public virtual DbSet<TrialDocNeedConfirmedUserType> TrialDocNeedConfirmedUserType { get; set; }



    #endregion

    #region 未分类

    public virtual DbSet<EmailLog> EmailLog { get; set; }
    public virtual DbSet<EmailReSendLog> EmailReSendLog { get; set; }
    public virtual DbSet<EmailRecipientLog> EmailRecipientLog { get; set; }

    public virtual DbSet<ShortcutKey> ShortcutKey { get; set; }

    public virtual DbSet<UserWLTemplate> UserWLTemplate { get; set; }
    public virtual DbSet<EmailNoticeConfig> EmailNoticeConfig { get; set; }
    public virtual DbSet<SystemBasicData> SystemBasicData { get; set; }

    public virtual DbSet<TrialSign> TrialSign { get; set; }

    public virtual DbSet<TrialStateChange> TrialStateChange { get; set; }

    public virtual DbSet<SystemAnonymization> SystemAnonymization { get; set; }

    public virtual DbSet<TrialExternalUser> TrialExternalUser { get; set; }

    public virtual DbSet<UserTypeGroup> UserTypeGroup { get; set; }

    public virtual DbSet<DataInspection> DataInspection { get; set; }


    public virtual DbSet<FrontAuditConfig> FrontAuditConfig { get; set; }
    public virtual DbSet<TrialAuditShow> TrialAuditShow { get; set; }

    public virtual DbSet<InspectionFile> InspectionFile { get; set; }

    public virtual DbSet<CommonDocument> CommonDocument { get; set; }

    public virtual DbSet<SystemNotice> SystemNotice { get; set; }

    public virtual DbSet<SystemNoticeUserRead> SystemNoticeUserRead { get; set; }

    public virtual DbSet<SystemNoticeUserType> SystemNoticeUserType { get; set; }

    public virtual DbSet<ReadingTableQuestionAnswer> ReadingTableQuestionAnswer { get; set; }

    public virtual DbSet<PublishLog> PublishLog { get; set; }
    public virtual DbSet<UserLog> UserLog { get; set; }

    public virtual DbSet<UserAgreement> UserAgreement { get; set; }

    public virtual DbSet<EmailNoticeUserType> EmailNoticeUserType { get; set; }
    public virtual DbSet<TrialEmailBlackUser> TrialEmailBlackUser { get; set; }

    public virtual DbSet<TrialBodyPart> TrialBodyPart { get; set; }

    public virtual DbSet<ExploreRecommend> ExploreRecommend { get; set; }

    public virtual DbSet<SCPPatient> SCPPatient { get; set; }
    public virtual DbSet<SCPStudy> SCPStudy { get; set; }
    public virtual DbSet<SCPSeries> SCPSeries { get; set; }
    public virtual DbSet<SCPInstance> SCPInstance { get; set; }
    public virtual DbSet<TrialDicomAE> TrialDicomAE { get; set; }


    public virtual DbSet<TrialSiteDicomAE> TrialSiteDicomAE { get; set; }


    public virtual DbSet<SCPImageUpload> SCPImageUpload { get; set; }

    public virtual DbSet<UserFeedBack> UserFeedBack { get; set; }

    public virtual DbSet<TaskAllocationRule> TaskAllocationRule { get; set; }

    public virtual DbSet<VisitTask> VisitTask { get; set; }

    public virtual DbSet<SubjectUser> SubjectUser { get; set; }

    public virtual DbSet<VisitTaskReReading> VisitTaskReReading { get; set; }

    public virtual DbSet<TaskMedicalReview> TaskMedicalReview { get; set; }

    public virtual DbSet<TaskMedicalReviewRule> TaskMedicalReviewRule { get; set; }

    public virtual DbSet<TaskConsistentRule> TaskConsistentRule { get; set; }


    public virtual DbSet<TaskInfluence> TaskInfluence { get; set; }

    public virtual DbSet<SubjectCanceDoctor> SubjectCanceDoctor { get; set; }

    public virtual DbSet<TrialEmailNoticeConfig> TrialEmailNoticeConfig { get; set; }

    public virtual DbSet<TrialEmailNoticeUser> TrialEmailNoticeUser { get; set; }


    public virtual DbSet<Internationalization> Internationalization { get; set; }

    public virtual DbSet<TrialVirtualSiteCodeUpdate> TrialVirtualSiteCodeUpdate { get; set; }
    public virtual DbSet<EnrollReadingCriterion> EnrollReadingCriterion { get; set; }
    #endregion

    public virtual DbSet<TrialImageDownload> TrialImageDownload { get; set; }

    public virtual DbSet<TestLength> TestLength { get; set; }

    public virtual DbSet<EventStoreRecord> EventStoreRecord { get; set; }

    public virtual DbSet<IdentityUser> IdentityUser { get; set; }


    public virtual DbSet<TrialIdentityUser> TrialIdentityUser { get; set; }

    public virtual DbSet<SystemDocConfirmedIdentityUser> SystemDocConfirmedIdentityUser { get; set; }

    public virtual DbSet<TrialDocConfirmedIdentityUser> TrialDocConfirmedIdentityUser { get; set; }

    #region 报告、 文档、记录

    public virtual DbSet<AuditDocument> AuditDocument { get; set; }

    public virtual DbSet<SysFileType> SysFileType { get; set; }
    public virtual DbSet<TrialFileType> TrialFileType { get; set; }
    public virtual DbSet<TrialFinalRecord> TrialFinalRecord { get; set; }
    public virtual DbSet<TrialNormalRecord> TrialNormalRecord { get; set; }
    public virtual DbSet<TrialTrianingRecord> TrialTrianingRecord { get; set; }
    public virtual DbSet<TrialFile> TrialFile { get; set; }

    public virtual DbSet<TrialHistoryRecordFile> TrialHistoryRecordFile { get; set; }
    #endregion


    public virtual DbSet<SubjectVisitImageBackRecord> SubjectVisitImageBackRecord { get; set; }


    public virtual DbSet<AuditRecord> AuditRecord { get; set; }
    public virtual DbSet<AuditRecordIdentityUser> AuditRecordIdentityUser { get; set; }
    public virtual DbSet<AuditRecordPermission> AuditRecordPermission { get; set; }

    public virtual DbSet<AuditDocumentClosure> AuditDocumentClosure { get; set; }

    public virtual DbSet<FileUploadRecord> FileUploadRecord { get; set; }

    public virtual DbSet<UploadFileSyncRecord> UploadFileSyncRecord { get; set; }

    
}

public class TestLength : Entity
{
    public string Name { get; set; }

    [StringLength(1000)]
    public string[] StringList { get; set; } = new string[] { };

    public List<DateTime> DateTimeList { get; set; } = new List<DateTime>();

    [StringLength(1000)]
    public List<TestEnum> TestEnumList { get; set; } = new List<TestEnum>();

    public List<TestJsonObject> TestJsonObjectLsit { get; set; }

    public DateOnly? TestDate { get; set; }
}


public record TestJsonObject
{
    public string Name { get; set; }

    public string Description { get; set; }
}

public enum TestEnum
{
    Default = 0,

    First = 1
}



