using Aliyun.OSS;
using BeetleX;
using BeetleX.BNR;
using Castle.DynamicProxy.Generators.Emitters.SimpleAST;
using IP2Region.Net.XDB;
using IRaCIS.Application.Contracts;
using IRaCIS.Core.Application.Contracts;
using IRaCIS.Core.Application.Helper;
using IRaCIS.Core.Application.Service;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using MassTransit;
using Medallion.Threading;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MiniExcelLibs;
using Minio;
using Minio.DataModel.Args;
using NPOI.HPSF;
using NPOI.POIFS.Crypt;
using SharpCompress.Common;
using Spire.Doc;
using System.Linq.Expressions;
using System.Reflection.Metadata;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;


namespace IRaCIS.Application.Services
{
    [ApiExplorerSettings(GroupName = "Institution")]
    public class TestService : BaseService
    {

        public static int IntValue = 100;
        private readonly IRepository<Dictionary> _dicRepository;
        private readonly IRepository<Trial> _trialRepository;

        //private readonly IDistributedCache _cache;

        private readonly IOptionsMonitor<SystemEmailSendConfig> _systemEmailConfig;

        private readonly IOptionsMonitor<ServiceVerifyConfigOption> _basicConfig;
        private readonly IRepository<VisitTask> _visitTaskRepositoryy;

        private readonly IDistributedLockProvider _distributedLockProvider;

        private readonly ILogger<TestService> _logger;

        public TestService(IRepository<Dictionary> dicRepository, IRepository<Trial> trialRepository, ILogger<TestService> logger

            , IOptionsMonitor<SystemEmailSendConfig> systemEmailConfig, IOptionsMonitor<ServiceVerifyConfigOption> basicConfig, IRepository<VisitTask> visitTaskRepository, IDistributedLockProvider distributedLockProvider)
        {
            _visitTaskRepositoryy = visitTaskRepository;

            _systemEmailConfig = systemEmailConfig;
            _basicConfig = basicConfig;

            _dicRepository = dicRepository;
            _trialRepository = trialRepository;

            _distributedLockProvider = distributedLockProvider;

            _logger = logger;
            //_cache = cache;
        }



        public async Task<IResponseOutput> TestEFcore8()
        {
            var systemDocQuery = from sysDoc in _repository.GetQueryable<SystemDocument>()

                                 join confirm in _repository.GetQueryable<SystemDocConfirmedUser>().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.User.FullName,
                                     UserName = confirm.User.UserName,
                                     UserTypeId = confirm.User.UserTypeId,
                                     UserTypeShortName = confirm.User.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 _repository.Where<Subject>().ExecuteUpdateAsync(t => t.SetProperty(t => t.UpdateTime, u => DateTime.Now));

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

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

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

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

            await _repository.Where<User>().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 _repository.InsertOrUpdateAsync<Internationalization, InternationalizationAddOrEdit>(row);

            }

            await _repository.SaveChangesAsync();

            return ResponseOutput.Ok();
        }

        [UnitOfWork]
        public async Task<string> Get()
        {

            //Expression<Func<VisitTask, bool>> visitTaskLambda = x => x.TrialId == Guid.Empty && x.SubjectId == Guid.Empty && x.TrialReadingCriterionId == Guid.Empty;

            //var visitTaskIdQueryable = _visitTaskRepositoryy.Where(visitTaskLambda).Where(t => t.Subject.SubjectVisitTaskList.AsQueryable().Where(visitTaskLambda).Any(c => c.IsNeedClinicalDataSign == true && c.IsClinicalDataSign == false && c.VisitTaskNum < t.VisitTaskNum)).Select(t => t.Id);

            //await _visitTaskRepositoryy.BatchUpdateNoTrackingAsync(t => visitTaskIdQueryable.Contains(t.Id), u => new VisitTask()
            //{
            //    IsFrontTaskNeedSignButNotSign = true
            //});


            //var a = ((Decimal)1.00).ToString().TrimEnd(new char[] { '.', '0' });
            //var b = ((Decimal)1.01).ToString().TrimEnd(new char[] { '.', '0' });
            //var c = ((Decimal)100).ToString().TrimEnd(new char[] { '.', '0' });
            //var subject1 = Guid.Parse("431D0C58-ABC5-4166-B9BC-08DA0E391693");
            //var subject2 = Guid.Parse("431D0C58-ABC5-4166-B9BC-08DA0E391694");

            //    var subjectList = new List<Guid>() { Guid.Parse("431D0C58-ABC5-4166-B9BC-08DA0E391693") ,
            //                                      Guid.Parse("431D0C58-ABC5-4166-B9BC-08DA0E391694") ,
            //                                       Guid.Parse("431D0C58-ABC5-4166-B9BC-08DA0E391695")
            //    };

            //string[] citys = new string[] { "广州", "深圳", "上海", "北京" };
            //foreach (var item in subjectList)
            //{
            //    Console.WriteLine(await BNRFactory.Default.Create($"[CN:{item}][N:[CN:{item}]/0000000]"));
            //}
            //foreach (var item in subjectList)
            //{
            //    Console.WriteLine(await BNRFactory.Default.Create($"[N:[CN:{item}]/0000000]"));
            //}

            //foreach (var item in subjectList)
            //{
            //    Console.WriteLine(await BNRFactory.Default.Create($"[CN:{item}][redis:city/0000000]"));
            //}

            //var needAddVisitList = await _repository.Where<VisitTask>(t => t.TrialId == Guid.Empty).DistinctBy(t => t.VisitTaskNum).ToListAsync();


            //await _repository.BatchUpdateAsync<VisitTask>(t => t.Id == Guid.Empty, u => new VisitTask()
            //{
            //    SuggesteFinishedTime = u.IsUrgent ? DateTime.Now.AddDays(2) : DateTime.Now.AddDays(7),

            //    Code = u.Code + 1
            //});

            //var query = from item1 in _repository.Where<ReadingQuestionTrial>()
            //            join item2 in _repository.Where<ReadingQuestionTrial>() on item1.ValueType equals item2.ValueType
            //            select new
            //            {
            //                item1.ValueType,
            //                dd = item2.ValueType
            //            };

            //var list2 = query.ToList();

            //await Task.CompletedTask;

            //var list = await _repository.Where<ClinicalDataTrialSet>(t => t.TrialId == Guid.Parse("40400000-3e2c-0016-239b-08da581f0e74")).ToListAsync();

            ////await _repository.BatchDeleteAsync<ClinicalDataTrialSet>(t => t.TrialId == Guid.Parse("40400000-3e2c-0016-239b-08da581f0e74"));

            //await _repository.AddRangeAsync(list, true);

            //await _repository.SaveChangesAsync();

            //await _repository.BatchUpdateAsync<DataInspection>(t => t.TrialId == Guid.Parse("40400000-3e2c-0016-239b-08da581f0e74") && t.EntityName== "ClinicalDataTrialSet", t => new DataInspection() { CreateTime= DateTime.Now.AddMonths(-2) }  );

            //await _visitTaskRepositoryy.UpdatePartialFromQueryAsync( Guid.Parse("78360000-3E2C-0016-9B53-08DA6A002040"), c => new VisitTask() { UpdateTime = DateTime.Now });

            //await _visitTaskRepositoryy.UpdatePartialFromQueryAsync( Guid.Parse("78360000-3E2C-0016-9B53-08DA6A002040"), c => new VisitTask() { UpdateTime = DateTime.Now.AddMinutes(1) });

            //var a = _userInfo.IsTestUser;

            //var list1 = await _repository.Where<Dictionary>().Select(t => t.TranslateValue(t.Value, t.ValueCN, true)).ToListAsync();
            //var list2 = await _repository.Where<Dictionary>().Select(t => t.TranslateValue(t.Value, t.ValueCN, false)).ToListAsync();

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



        [AllowAnonymous]
        public async Task testwwwww([FromServices] IWebHostEnvironment env)
        {
            await Task.CompletedTask;
        }


        [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 = _repository.Where<User>(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 = _repository.Where<SubjectVisit>(t => t.Id == Guid.NewGuid()).SelectMany(t => t.VisitTaskList).ToList();

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

            //var list3 = _repository.Where<VisitTask>(t => t.Id == Guid.NewGuid()).SelectMany(t => t.SourceSubjectVisit.VisitTaskList).ToList();
            //var list2 = _repository.Where<Subject>(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 = _repository.Where<Trial>(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 _repository.AddRangeAsync(tempList);
            }

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

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


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

                var trialCritrialList = _repository.Where<ReadingQuestionCriterionTrial>(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 _repository.AddAsync(new TrialClinicalDataSetCriterion() { TrialClinicalDataSetId = needAddTrial.Id, TrialReadingCriterionId = find.Id });
                        }
                    }
                }
            }
            await _repository.SaveChangesAsync();
            return ResponseOutput.Ok();
        }


        /// <summary>
        /// 维护OSS 影像数据
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [UnitOfWork]
        public async Task<IResponseOutput> OldLocalImageResizeJpg([FromServices] IOSSService oSSService, [FromServices] IRepository _repository, [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 = _repository.Where<DicomStudy>(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 = _repository.Where<DicomInstance>(t => t.Id == jpg.InstanceId).Select(t => t.SeriesId).FirstOrDefault();

                            await _repository.BatchUpdateAsync<DicomSeries>(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 _repository.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
    {
    }
}