using Aliyun.OSS;
using IRaCIS.Application.Contracts;
using IRaCIS.Core.Application.BusinessFilter;
using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Application.Helper;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Domain;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infra.EFCore;
using IRaCIS.Core.Infrastructure;
using IRaCIS.Core.Infrastructure.Encryption;
using IRaCIS.Core.Infrastructure.NewtonsoftJson;
using MassTransit;
using MassTransit.Mediator;
using Medallion.Threading;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MiniExcelLibs;
using NPOI.SS.Formula.Functions;
using NPOI.XWPF.UserModel;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using Tea;


namespace IRaCIS.Core.Application.Service
{
    [ApiExplorerSettings(GroupName = "Institution")]
    public class TestService(IRepository<Dictionary> _dicRepository,
        IRepository<Trial> _trialRepository,
        IOptionsMonitor<SystemEmailSendConfig> _systemEmailConfig,
        IOptionsMonitor<ServiceVerifyConfigOption> _basicConfig,
        IRepository<SystemDocument> _systemDocumentRepository,
        IRepository<TrialClinicalDataSetCriterion> _trialClinicalDataSetCriterionRepository,
        IRepository<DicomInstance> _dicomInstanceRepository,
        IRepository<Internationalization> _internationalizationRepository,
        IRepository<SystemDocConfirmedUser> _systemDocConfirmedUserRepository,
        IRepository<DicomStudy> _dicomStudyRepository,
        IRepository<ClinicalDataTrialSet> _clinicalDataTrialSetRepository,
        IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository,
        IRepository<VisitTask> _visitTaskRepository,
        IRepository<DicomSeries> _dicomSeriesRepository,
        IRepository<User> _userRepository,
        IRepository<TrialBodyPart> _trialBodyPartRepository,
        IDistributedLockProvider _distributedLockProvider,
        ILogger<TestService> _logger, IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService
    {
        public static int IntValue = 100;
        /// <summary>
        /// 清理一致性分析任务
        /// </summary>
        /// <param name="trialReadingCriterionId"></param>
        /// <param name="_taskConsistentRuleRepository"></param>
        /// <param name="_readingConsistentClinicalDataPDFRepository"></param>
        /// <param name="_readingConsistentClinicalDataRepository"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> DeleteConsistentDate(Guid trialReadingCriterionId,
             [FromServices] IRepository<TaskConsistentRule> _taskConsistentRuleRepository,
             [FromServices] IRepository<ReadingConsistentClinicalDataPDF> _readingConsistentClinicalDataPDFRepository,
             [FromServices] IRepository<ReadingConsistentClinicalData> _readingConsistentClinicalDataRepository
            )
        {


            var consistentSubjectIdList = _visitTaskRepository.Where(t => t.TrialReadingCriterionId == trialReadingCriterionId && t.IsAnalysisCreate == true).Select(t => t.SubjectId).ToList();

            await _taskConsistentRuleRepository.BatchDeleteNoTrackingAsync(t => t.TrialReadingCriterionId == trialReadingCriterionId);

            await _visitTaskRepository.BatchDeleteNoTrackingAsync(t => t.TrialReadingCriterionId == trialReadingCriterionId && t.IsAnalysisCreate == true);

            await _readingConsistentClinicalDataPDFRepository.BatchDeleteNoTrackingAsync(t => consistentSubjectIdList.Contains(t.ReadingConsistentClinicalData.SubjectId));

            await _readingConsistentClinicalDataRepository.BatchDeleteNoTrackingAsync(t => consistentSubjectIdList.Contains(t.SubjectId));

            await _readingConsistentClinicalDataRepository.SaveChangesAsync();
            return ResponseOutput.Ok();
        }
        public async Task<IResponseOutput> DeleteOSSDate(string rootFolder,
            [FromServices] IOSSService _oSSService, [FromServices] IWebHostEnvironment _hostEnvironment)
        {

            //var deleteIdList = _trialRepository.Where(t => t.IsDeleted == true, false, true).Select(t => t.Id).ToList();
            //foreach (var deleteId in deleteIdList)
            //{
            //    await _oSSService.DeleteFromPrefix($"{deleteId}");
            //}

            await _oSSService.DeleteFromPrefix($"{rootFolder}");

            return ResponseOutput.Ok();
        }

        [LowerCamelCaseJson]
        public class TestModel
        {
            public Guid TestId { get; set; }

            public string? TestName { get; set; }

        }


        public class TestModel2
        {
            public Guid TestId { get; set; }

            public string TestName { get; set; }
        }

        public async Task<IResponseOutput> TestAutoEncretpt([FromServices] IRepository<TestLength> _testLengthRepository)
        {
            await _testLengthRepository.AddAsync(new TestLength() { Name = "zhouhang1" });
            await _testLengthRepository.AddAsync(new TestLength() { Name = "hewentao" });

            await _testLengthRepository.SaveChangesAsync();
            var list = _testLengthRepository.Where().ToList();

            var exist = await _testLengthRepository.AnyAsync(t => t.Name == "zhouhang1");

            return ResponseOutput.Ok(list, exist);

        }

      

        public async Task<IResponseOutput> TestJson()
        {
            var model1 = new TestModel() { TestId = NewId.NextSequentialGuid(), TestName = null };
            var model2 = new TestModel2() { TestId = NewId.NextSequentialGuid(), TestName = "test2" };



            var model4 = _mapper.Map(model1, model2);


            await _trialBodyPartRepository.FirstOrDefaultAsync();

            await _trialBodyPartRepository.Where(t => t.Trial.Id == Guid.Empty).FirstOrDefaultAsync();

            return ResponseOutput.Ok(new TestModel(), IRCEmailPasswordHelper.GenerateRandomPassword(10));
        }

        public string TestHoliday(DateTime startdate, DateTime endDate)
        {
            var timeSpan = HolidayHelper.GetChinaWorkTimeSpan(startdate, endDate);

            _userRepository.Where(t => t.Id == _userInfo.Id).Select(t => t.FullName).FirstOrDefault();

            return $"{timeSpan.Days}天,{timeSpan.Hours}小时{timeSpan.Minutes}分钟{timeSpan.Seconds}秒";
        }

        public async Task<IResponseOutput> TestEFcore8()
        {
            var systemDocQuery = from sysDoc in _systemDocumentRepository.Where()

                                 join confirm in _systemDocConfirmedUserRepository.Where().Where(t => t.ConfirmTime != null) on sysDoc.Id equals confirm.SystemDocumentId
                                 select new UnionDocumentWithConfirmInfoView()
                                 {
                                     IsSystemDoc = true,

                                     Id = sysDoc.Id,
                                     CreateTime = sysDoc.CreateTime,
                                     IsDeleted = sysDoc.IsDeleted,
                                     SignViewMinimumMinutes = sysDoc.SignViewMinimumMinutes,
                                     Name = sysDoc.Name,
                                     Path = sysDoc.Path,
                                     FileType = _userInfo.IsEn_Us ? sysDoc.FileType.Value : sysDoc.FileType.ValueCN,
                                     FileTypeId = sysDoc.FileTypeId,
                                     UpdateTime = sysDoc.UpdateTime,


                                     ConfirmUserId = confirm.ConfirmUserId,
                                     ConfirmTime = confirm.ConfirmTime,
                                     RealName = confirm.ConfirmUser.FullName,
                                     UserName = confirm.ConfirmUser.UserName,
                                     UserTypeId = confirm.ConfirmUser.UserTypeId,
                                     UserTypeShortName = confirm.ConfirmUser.UserTypeRole.UserTypeShortName,

                                     FullFilePath = sysDoc.Path
                                 };

            var list = systemDocQuery.OrderBy(t => t.ConfirmUserId).ThenBy(t => t.ConfirmTime).ToList();

            //var aa= _dicRepository._dbContext.Subject.Where(t => t.Id == Guid.Empty).ExecuteUpdate("FirstName","ddd");

            //await _repository.BatchUpdateAsync<Subject>(t => t.Id == Guid.Empty, u => new Subject() { FirstName = "fddd", LastName = "sss", UpdateTime = DateTime.Now });

            //await _subjectRepository.Where().ExecuteUpdateAsync(t => t.SetProperty(t => t.UpdateTime, u => DateTime.Now));

            return ResponseOutput.Ok(list);
        }
        // 设置 Ne

        [AllowAnonymous]
        public async Task<IResponseOutput> TestMinIO([FromServices] IOSSService oSSService)
        {

            var str = await oSSService.GetSignedUrl("/01000000-c0a8-0242-1c98-08dc7ebcd37d/Read/01000000-c0a8-0242-1c98-08dc7ebcd37d/Visit/1716872544006_1716872544003.png");


            //await oSSService.UploadToOSSAsync("C:\\Users\\Administrator\\Desktop\\TrialSiteUserImportTemplate.xlsx", "myfolder");

            //await oSSService.DownLoadFromOSSAsync("/myfolder/TrialSiteUserImportTemplate.xlsx", "C:\\Users\\Administrator\\Desktop\\aws.xlsx");

            return ResponseOutput.Ok(str);
        }

        [AllowAnonymous]
        public async Task<IResponseOutput> TestDistributedLock()
        {

            await _userRepository.Where().Select(t => t.FullName).FirstNotNullAsync();

            Console.WriteLine($"我进来了当前值是：" + IntValue);
            _logger.LogWarning($"我进来了当前值是：" + IntValue);

            var @lock = _distributedLockProvider.CreateLock($"UserAccount");

            using (await @lock.AcquireAsync())
            {
                await Task.Delay(4);
                IntValue--;

                _logger.LogWarning(IntValue.ToString());
                Console.WriteLine(IntValue);
            }

            return ResponseOutput.Ok(IntValue);
        }


        [AllowAnonymous]
        public async Task<IResponseOutput> InternationazitionInit()
        {


            var rows = await MiniExcel.QueryAsync<InternationalizationAddOrEdit>(@"C:\Users\Administrator\Desktop\i18n-new.xlsx");

            rows = rows.Where(t => !string.IsNullOrEmpty(t.Code)).ToList();

            foreach (var row in rows)
            {
                await _internationalizationRepository.InsertOrUpdateAsync(row);

            }

            await _internationalizationRepository.SaveChangesAsync();

            return ResponseOutput.Ok();
        }


        public class TestEncrept
        {
            public string Name { get; set; }

            public string Code { get; set; }
        }

        public IResponseOutput TestEncreptTest(TestEncrept testModel)
        {
            return ResponseOutput.Ok(testModel);
        }

        //etx5EzcF9XWA6ICzQB5ywEEextuhmUwaHM2TmyyCC8Q=
        [HttpPut("{name}/{code}")]
        public IResponseOutput TestEncreptTest2(string name, string code)
        {
            return ResponseOutput.Ok($"name:{name} Code: {code}");
        }

        public IResponseOutput TestEncreptTest3(string name, string Code)
        {
            return ResponseOutput.Ok($"name:{name} Code: {Code}");
        }


        [UnitOfWork]
        public async Task<string> Get([FromServices] IOptionsMonitor<IRCEncreptOption> _encreptResponseMonitor)
        {
            var _IRCEncreptOption = _encreptResponseMonitor.CurrentValue;

            var publicKey = Encoding.UTF8.GetString(Convert.FromBase64String(_IRCEncreptOption.Base64RSAPublicKey));
            var privateKey = Encoding.UTF8.GetString(Convert.FromBase64String(_IRCEncreptOption.Base64RSAPrivateKey));

            Console.WriteLine(RSAEncryption.Encrypt(publicKey, MD5Helper.Md5("123456")));




            //U2FsdGVkX1+atIRsUP6uhWIMHIVmn7U2sy4HlgWiWJG1qc0WdYyQqzgTJ1JLeQGHvYrIYm90/YCkBYclYbnm1g==


            string plainText = "Hello, BouncyCastle!";
            string key = "12345678901234567890123456789012";  // AES 密钥长度应为 16 字节（128 位）
            string iv = "your-iv-12345678";       // IV 长度为 16 字节


            var encreptMd5 = AesEncryption.Encrypt(MD5Helper.Md5("123456"), key);
            Console.WriteLine(encreptMd5);
            var decrept = AesEncryption.Decrypt(encreptMd5, key);


            Console.WriteLine();

            Console.WriteLine(AesEncryption.Encrypt("cyldev", key));

            Console.WriteLine($"原始文本: {plainText}");

            // 加密
            string encrypted = AesEncryption.Encrypt(plainText, key, iv);
            Console.WriteLine($"加密后的数据: {encrypted}");

            // 解密
            string decrypted = AesEncryption.Decrypt(encrypted, key, iv);
            Console.WriteLine($"解密后的数据: {decrypted}");




            Console.WriteLine($"原始文本: {plainText}");

            // 加密
            string encrypte = AesEncryption.Encrypt(plainText, key);
            Console.WriteLine($"加密后的数据: {encrypte}");

            // 解密
            string decrypte = AesEncryption.Decrypt(encrypte, key);
            Console.WriteLine($"解密后的数据: {decrypte}");


            //// Generate RSA keys
            //var keyPair = RSAEncryption.GenerateRSAKeyPair(2048);

            //// Export the public and private keys to PEM format
            //string publicKey = RSAEncryption.ExportPublicKey(keyPair.Public);
            //string privateKey = RSAEncryption.ExportPrivateKey(keyPair.Private);

            //Console.WriteLine("Public Key:");
            //Console.WriteLine(publicKey);
            //Console.WriteLine($"{Convert.ToBase64String(Encoding.UTF8.GetBytes(publicKey))}");
            //Console.WriteLine("\nPrivate Key:");
            //Console.WriteLine(privateKey);
            //Console.WriteLine($"{Convert.ToBase64String(Encoding.UTF8.GetBytes(privateKey))}");





            Console.WriteLine("Public Key:");
            Console.WriteLine(publicKey);
            Console.WriteLine("\nPrivate Key:");
            Console.WriteLine(privateKey);

            Console.WriteLine("encrept sys Key:");
            Console.WriteLine($"\n{RSAEncryption.Encrypt(publicKey, key)}");

            // Data to encrypt
            string dataToEncrypt = "Hello, RSA!";
            Console.WriteLine("\nOriginal Data: " + dataToEncrypt);

            // Encrypt the data
            var encryptedData = RSAEncryption.Encrypt(publicKey, dataToEncrypt);
            Console.WriteLine("\nEncrypted Data: " + encryptedData);

            // Decrypt the data
            string decryptedData = RSAEncryption.Decrypt(privateKey, encryptedData);
            Console.WriteLine("\nDecrypted Data: " + decryptedData);


            return "测试自动发布--再次提交";
        }



        [AllowAnonymous]
        public async Task<string> testDoc([FromServices] IWebHostEnvironment env, string email)
        {
            #region DocX  测试
            //using (DocX document = DocX.Load("C:\\Users\\hang\\Desktop\\test.docx"))
            //{
            //    // 查找书签
            //    var bookmarkCn_Start = document.Bookmarks.FirstOrDefault(b => b.Name == "zh_cn");
            //    var bookmarkEn_Start = document.Bookmarks.FirstOrDefault(b => b.Name == "en_us");

            //    if (bookmarkCn_Start != null && bookmarkEn_Start != null)
            //    {
            //        // 获取书签的起始位置
            //        int bookmarkCNStartPos = bookmarkCn_Start.Paragraph.StartIndex;

            //        var bookmarkENStartPos = bookmarkEn_Start.Paragraph.StartIndex;

            //        //    // 创建一个要删除段落的列表
            //        List<Paragraph> paragraphsToRemove = new List<Paragraph>();

            //        foreach (var item in document.Paragraphs)
            //        {

            //            //中文模板在前，英文在后，英文模板，就删除英文之前的，中文模板就删除英文之后的
            //            //_userInfo.IsEn_Us?  item.EndIndex< bookmarkENStartPos :item.StartIndex>= bookmarkENStartPos
            //            if (item.StartIndex>= bookmarkENStartPos)
            //            {
            //                paragraphsToRemove.Add(item);

            //            }
            //        }

            //        foreach (var paragraph in paragraphsToRemove) 
            //        {
            //            document.RemoveParagraph(paragraph);
            //        }

            //    }

            //    // 保存修改
            //    document.SaveAs("C:\\Users\\hang\\Desktop\\test1.docx");
            //}
            #endregion

            using (FileStream fs = new FileStream("C:\\Users\\hang\\Desktop\\test.docx", FileMode.Open, FileAccess.Read))
            {
                XWPFDocument doc = new XWPFDocument(fs);


                // 查找包含指定书签的段落及其索引
                var bookmarkParagraph = doc.Paragraphs
                    .FirstOrDefault(p => p.GetCTP().GetBookmarkStartList().Any(b => b.name == "en_us"));


                if (bookmarkParagraph != null)
                {
                    int bookmarkIndex = doc.Paragraphs.IndexOf(bookmarkParagraph);

                    // 删除书签之后的所有段落
                    for (int i = doc.Paragraphs.Count - 1; i >= bookmarkIndex; i--)
                    {
                        doc.RemoveBodyElement(i);
                    }

                }
                else
                {
                    throw new BusinessValidationFailedException("word 模板没有英文书签");
                }

                // 创建一个要删除段落的列表

                //XWPFParagraph bookmarkParagraph = null;

                //foreach (var paragraph in doc.Paragraphs)
                //{

                //    foreach (var bookmark in paragraph.GetCTP().GetBookmarkStartList())
                //    {
                //        if (bookmark.name == "en_us")
                //        {
                //            bookmarkParagraph = paragraph;
                //            break;
                //        }
                //    }
                //}




                //// 从书签所在段落开始，删除之前的所有段落
                //for (int i = bookmarkIndex - 1; i >= 0; i--)
                //{
                //    doc.RemoveBodyElement(i);
                //}



                using (FileStream outStream = new FileStream("C:\\Users\\hang\\Desktop\\test1.docx", FileMode.Create, FileAccess.Write))
                {
                    doc.Write(outStream);
                }
            }


            return "hiddenEmail";
        }


        [AllowAnonymous]
        public async Task<object> GetEnvironmentName([FromServices] IWebHostEnvironment env)
        {
            //var a = IdentifierHelper.CreateGuid("123456");

            //var k = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("123456"));

            //var c = MD5Helper.Md5("123456");



            //return new { env.EnvironmentName, EMailConfig = _systemEmailConfig.CurrentValue, BasicConfig = _basicConfig.CurrentValue };


            // Load a document.
            //using (var document = DocX.Load(Path.Combine(_hostEnvironment.ContentRootPath, "ReplaceText.docx")))
            //{
            //    // Check if all the replace patterns are used in the loaded document.
            //    if (document.FindUniqueByPattern(@"<[\w \=]{4,}>", RegexOptions.IgnoreCase).Count > 0)
            //    {
            //        // Do the replacement of all the found tags and with green bold strings.
            //        //for (int i = 0; i < _replacePatterns.Count; ++i)
            //        //{
            //        //    document.ReplaceText("<(.*?)>", TestService.ReplaceFunc, false, RegexOptions.IgnoreCase, new Formatting() { Bold = true, FontColor = System.Drawing.Color.Green });
            //        //}
            //        // Save this document to disk.

            //        document.ReplaceText("test", "jfdksajfkljflsdjf", false, RegexOptions.IgnoreCase, new Formatting() { Bold = true, FontColor = System.Drawing.Color.Green });
            //        document.SaveAs("ReplacedText.docx");
            //    }

            //}
            //return await NpoiWordHelper.TemplateExportWordAsync(Path.Combine(_hostEnvironment.ContentRootPath, "ReplaceText.docx"), new { test = "xiugai", ZZZZ = "ModiffyZZZZ" }, null, _hostEnvironment);

            //_cache.SetString("test" , "cacheStr");

            //var aa=  _trialRepository.Where(t => t.Id == Guid.Empty).First();

            //var aaabb = _trialRepository.BatchDeleteNoTrackingAsync(t => t.Id == Guid.Empty).Result;

            //var aaaa = _dicRepository.BatchDeleteNoTrackingAsync(t => t.Id == Guid.Empty).Result;


            //var waitModifyEntity = _dicRepository.FirstOrDefaultAsync(t => t.Id == Guid.Parse("e2b97a6c-35a6-4aa3-7f27-08da13ab33ff")).GetAwaiter().GetResult();

            //var tt = _dicRepository.UpdateAsync(waitModifyEntity, t => new Dictionary() { Description = "xxxxx" }, true).Result;



            //var tt2 = _trialRepository.UpdatePartialFromQueryAsync(Guid.Parse("543d0000-3e10-0016-77e9-08da2827228a"), t => new Trial() { Indication = "WCH测试稽查002" }, true).Result;




            //var d = _userRepository.Where(t => t.FullName.Contains("cc")).Select(t => t.FullName).FirstOrDefault();
            //var c = _dicRepository.Where(t => t.ParentId != null).Select(t => t.MappedValue).First();
            //CultureInfo culture = CultureInfo.CurrentUICulture;

            //var dd = _dicRepository.UpdatePartialFields(Guid.Parse("8a90c96e-0776-4f7b-82a6-18933d339584"),
            //        u => new Dictionary() { ParentId = null, Code = "test" }, true);


            //var ggggg = _dicRepository.UpdateFromQueryAsync(t => t.ParentId == Guid.Parse("8a90c96e-0776-4f7b-82a6-18933d339584"), u=>new Dictionary(){Code = "test"}).Result;

            //var ddd = _dicRepository.BatchUpdateAsync(t => t.Id == Guid.Parse("8a90c96e-0776-4f7b-82a6-18933d339584"),
            //   u => new Dictionary() { /*ParentId = null,*/ Code = "test" }).Result;


            //var  aaaaa= _trialRepository.BatchUpdateAsync(t => t.Id == Guid.Empty,
            //    u => new SubjectVisit() { CurrentActionUserId = null }).Result;


            //var d = _dicRepository.UpdateFromDTOAsync(new AddOrEditBasicDic() { Id = Guid.Parse("60d86683-c33b-4349-b672-08da1e91b622"), ParentId = null, ChildGroup = null, Code = null }, true, true).Result;
            //var a = 123;

            throw new BusinessValidationFailedException(_localizer["TrialIsDoubleCheck{0}", "测试"]);

            var b = _localizer["test{0}", "测试"];
            return _localizer["test{0}", "测试"];


            //var list = _subjectVisitRepository.Where(t => t.Id == Guid.NewGuid()).SelectMany(t => t.VisitTaskList).ToList();

            //var list2 = _visitTaskRepository.Where(t => t.Id == Guid.NewGuid()).Select(t => t.SourceSubjectVisit).ToList();

            //var list3 = _visitTaskRepository.Where(t => t.Id == Guid.NewGuid()).SelectMany(t => t.SourceSubjectVisit.VisitTaskList).ToList();
            //var list2 = _subjectRepository.Where(t => t.Id == Guid.NewGuid()).SelectMany(t => t.SubjectVisitTaskList).ToList();
            //return _userInfo.LocalIp;
        }



        public async Task<IResponseOutput> ModifyTrialBodyPart()
        {

            var searchList = await _dicRepository.Where(t => t.Parent.Code == "BodyPart" && t.ParentId != null && t.IsEnable).ProjectTo<BasicDicSelect>(_mapper.ConfigurationProvider).ToListAsync();

            var needAddBodyPartList = searchList.Select(t => new TrialBodyPart() { Code = t.Code, Name = t.Value, NameCN = t.ValueCN });

            var trialIds = _trialRepository.Where(t => !t.TrialBodyPartList.Any()).Select(t => t.Id).ToList();

            foreach (var trialId in trialIds)
            {
                var tempList = needAddBodyPartList.Clone();

                tempList.ForEach(t => t.TrialId = trialId);

                await _trialBodyPartRepository.AddRangeAsync(tempList);
            }

            await _dicRepository.SaveChangesAsync();
            return ResponseOutput.Ok();
        }

        #region 历史维护
        /// <summary>
        /// 维护临床数据  --一定要在同步表前同步数据才行
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public async Task<IResponseOutput> ModifyClinicalDataTable()
        {
            var needAddList = _clinicalDataTrialSetRepository.Where(t => t.CriterionEnumListStr != String.Empty && t.TrialClinicalDataSetCriteriaList.Count() == 0).ToList();


            //遍历项目
            foreach (var needAddTrialGroup in needAddList.GroupBy(t => t.TrialId))
            {
                //找到项目存在的项目标准

                var trialCritrialList = _readingQuestionCriterionTrialRepository.Where(t => t.TrialId == needAddTrialGroup.Key).ToList();

                //遍历项目下的临床数据
                foreach (var needAddTrial in needAddTrialGroup)
                {

                    //遍历每条临床数据配置的标准

                    foreach (var item in needAddTrial.CriterionEnumList)
                    {
                        var find = trialCritrialList.Where(t => (int)t.CriterionType == item).FirstOrDefault();

                        if (find != null)
                        {
                            await _trialClinicalDataSetCriterionRepository.AddAsync(new TrialClinicalDataSetCriterion() { TrialClinicalDataSetId = needAddTrial.Id, TrialReadingCriterionId = find.Id });
                        }
                    }
                }
            }
            await _trialClinicalDataSetCriterionRepository.SaveChangesAsync();
            return ResponseOutput.Ok();
        }


        /// <summary>
        /// 维护OSS 影像数据
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [UnitOfWork]
        public async Task<IResponseOutput> OldLocalImageResizeJpg([FromServices] IOSSService oSSService, [FromServices] IWebHostEnvironment _hostEnvironment)
        {

            var aliConfig = oSSService.ObjectStoreServiceOptions.AliyunOSS;
            var _ossClient = new OssClient(aliConfig.EndPoint, aliConfig.AccessKeyId, aliConfig.AccessKeySecret);

            var rootPath = FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment);

            var studyList = _dicomStudyRepository.Where(t => t.SeriesList.Any(t => t.ImageResizePath.Length < 10)).Select(t => new { t.TrialId, t.Subject.TrialSiteId, t.SubjectId, t.SubjectVisitId, t.Id }).ToList();

            foreach (var studyitem in studyList)
            {

                var relativePath = $"{studyitem.TrialId}/{studyitem.TrialSiteId}/{studyitem.SubjectId}/{studyitem.SubjectVisitId}/{StaticData.Folder.DicomFolder}/{studyitem.Id}/";

                try
                {
                    string nextMarker = null;
                    do
                    {
                        // 使用 prefix 模拟目录结构，设置 MaxKeys 和 NextMarker
                        var objectListing = _ossClient.ListObjects(new ListObjectsRequest(aliConfig.BucketName)
                        {
                            Prefix = relativePath,
                            MaxKeys = 1000,
                            Marker = nextMarker
                        });

                        var jpgInfoList = objectListing.ObjectSummaries
                                                     .Where(summary => summary.Key.EndsWith(".jpg"))
                                                     .Select(summary =>
                                                     {
                                                         string fileName = summary.Key.Split('/').Last(); // 提取文件夹名
                                                         return new
                                                         {

                                                             Key = summary.Key,
                                                             InstanceId = Guid.TryParse(
                                                                 fileName.Split('.')[0],
                                                                 out Guid instanceId)
                                                                 ? instanceId
                                                                 : Guid.Empty
                                                         };
                                                     })
                                                     .Where(info => info.InstanceId != Guid.Empty)
                                                     .ToList();

                        foreach (var jpg in jpgInfoList)
                        {
                            var seriesId = _dicomInstanceRepository.Where(t => t.Id == jpg.InstanceId).Select(t => t.SeriesId).FirstOrDefault();

                            await _dicomSeriesRepository.BatchUpdateNoTrackingAsync(t => t.Id == seriesId, t => new DicomSeries() { ImageResizePath = "/" + jpg.Key });
                        }

                        // 设置 NextMarker 以获取下一页的数据
                        nextMarker = objectListing.NextMarker;

                    } while (!string.IsNullOrEmpty(nextMarker));
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                }

                await _dicomStudyRepository.SaveChangesAsync();
            }



            return ResponseOutput.Ok();
        }


        #endregion



    }

    public class TestModel
    {

        //[Required]
        public string Id { get; set; }

        public string Name { get; set; }

        public DateTime? Time { get; set; }
    }
}


namespace Localization
{
    public class SharedResource
    {
    }
}