using IRaCIS.Core.Application.Service;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using MassTransit;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Options;
using MiniExcelLibs;
using System.Linq.Expressions;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;


namespace IRaCIS.Application.Services
{
    [ApiExplorerSettings(GroupName = "Institution")]
    public class TestService : BaseService
    {
        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;


        public TestService(IRepository<Dictionary> dicRepository, IRepository<Trial> trialRepository/*, IDistributedCache cache*/

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

            _systemEmailConfig = systemEmailConfig;
            _basicConfig = basicConfig;

            _dicRepository = dicRepository;
            _trialRepository = trialRepository;
            //_cache = cache;
        }


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


           

            return ResponseOutput.Ok(new { StaticData.En_US_Dic , StaticData.Zh_CN_Dic });
        }


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


        //    var rows = await MiniExcel.QueryAsync<InternationalizationAddOrEdit>(@"C:\Users\Administrator\Desktop\Export\vue.xlsx");

        //    foreach (var row in rows)
        //    {
        //        await _repository.InsertOrUpdateAsync<Internationalization, InternationalizationAddOrEdit>(row);

        //    }

        //    await _repository.SaveChangesAsync();

        //    return ResponseOutput.Ok();
        //}
        [AllowAnonymous]
        [UnitOfWork]
        public async Task<string> Get()
        {
     
            return "修改服务器时间自动发布测试--我又修改了";
        }



        private static Dictionary<string, string> _replacePatterns = new Dictionary<string, string>()
      {
        { "test", "Atlanta Knight" },
        { "GAME_TIME", "7:30pm" },
        { "GAME_NUMBER", "161" },
        { "DATE", "October 18 2018" },
      };

        private static string ReplaceFunc(string findStr)
        {
            if (_replacePatterns.ContainsKey(findStr))
            {
                return _replacePatterns[findStr];
            }
            return findStr;
        }


        [AllowAnonymous]
        public async Task<List<Guid>> testwwwww([FromServices] IWebHostEnvironment env)
        {
            int count = 200;

            var list=new List<Guid>();

            for (int i = 0; i < count; i++)
            {
                Guid guid = NewId.NextGuid();
                list.Add(guid);
            }

            return list;
        }


        [AllowAnonymous]
        public async Task<object> GetEnvironmentName([FromServices] IWebHostEnvironment env)
        {
            var a = IdentifierHelper.CreateGuid("1.2.840.113619.2.416.3358551739363725609857319676326094825431.2.840.113619.2.80.2338912612.50499.1563432834.1.4.11.2.840.113619.2.80.2338912612.50499.1563432835.4b8340000-3e2c-0016-fbdd-08db883b137f");


            var c = MD5Helper.Md5("1.2.840.113619.2.416.3358551739363725609857319676326094825431.2.840.113619.2.80.2338912612.50499.1563432834.1.4.11.2.840.113619.2.80.2338912612.50499.1563432835.4b8340000-3e2c-0016-fbdd-08db883b137f");


            //update DicomInstance set Path = '/IRaCISData/TrialData/' + cast(DicomInstance.TrialId as varchar) + '/' + DicomInstance.SiteId + '/' + DicomInstance.SubjectId + '/' + DicomInstance.SubjectVisitId + '/Dicom/' + DicomInstance.StudyId + '/' + DicomInstance.Id + '.dcm'


            //await _repository.BatchUpdateAsync<DicomInstance>(u => u.Path.Contains(".dcm"), t => new DicomInstance() { Path = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{t.TrialId}/{t.SiteId}/{t.SubjectId}/{t.SubjectVisitId}/{StaticData.Folder.DicomFolder}/{t.StudyId}/{t.Id}.dcm" });

            //await _repository.BatchUpdateAsync<DicomInstance>(u => !u.Path.Contains(".dcm"), t => new DicomInstance() { Path = $"/{StaticData.Folder.IRaCISDataFolder}/{StaticData.Folder.TrialDataFolder}/{t.TrialId}/{t.SiteId}/{t.SubjectId}/{t.SubjectVisitId}/{StaticData.Folder.DicomFolder}/{t.StudyId}/{t.Id}" });


            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 string PostData(TestModel testModelList)
        {
            return String.Empty;
        }

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


    }

    public class TestModel
    {

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

        public string Name { get; set; }

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


namespace Localization
{
    public class SharedResource
    {
    }
}