using DataSharing.Share.Dtos.Province;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using XF.Domain.Cache;
using XF.Domain.Dependency;

namespace DataSharing.Province
{
    public class HuiJuClient : ProvinceClient, ISingletonDependency, ISelfDependency
    {
        private readonly IServiceScopeFactory _scopeFactory;
        private readonly ILogger<HuiJuClient> _logger;

        public HuiJuClient(IServiceScopeFactory scopeFactory, ILogger<HuiJuClient> logger) : base(scopeFactory)
        {
            _scopeFactory = scopeFactory;
            _logger = logger;
        }

        public Task<TResponse?> RequestAsync<TRequest, TResponse>(TRequest request, CancellationToken cancellationToken)
            where TRequest : IProvinceRequest, new()
        {
            using var scope = _scopeFactory.CreateScope();
            var provider = scope.ServiceProvider;
            var channelconfigManager = provider.GetRequiredService<IChannelConfigurationManager>();

            var configProvince = channelconfigManager.GetConfigurationProvince();
            return base.RequestAsync<TRequest, TResponse>(request, configProvince.HuiJu, configProvince, cancellationToken);
        }

        public Task<TResponse?> RequestAsync<TResponse>(string url, string httpMethod, string? stringContent = null, CancellationToken cancellationToken = default)
        {
            using var scope = _scopeFactory.CreateScope();
            var provider = scope.ServiceProvider;
            var channelconfigManager = provider.GetRequiredService<IChannelConfigurationManager>();
//var httpInvoker = provider.GetRequiredService<IHttpInvoker>();
          //  var cacheToken = provider.GetRequiredService<ITypedCache<TokenInfo>>();

            var configProvince = channelconfigManager.GetConfigurationProvince();
            return base.RequestAsync<TResponse>(configProvince.HuiJu, configProvince, url, httpMethod, stringContent, cancellationToken);
        }

        /// <summary>
        /// 测试获取Token
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<TokenInfo> GetTokenHJAsync(CancellationToken cancellationToken)
        {
            using var scope = _scopeFactory.CreateScope();
            var provider = scope.ServiceProvider;
            var channelconfigManager = provider.GetRequiredService<IChannelConfigurationManager>();

            var configProvince = channelconfigManager.GetConfigurationProvince();
             _logger.LogInformation("配置信息：" + System.Text.Json.JsonSerializer.Serialize(configProvince));
             _logger.LogInformation("配置信息--地址" + configProvince.HuiJu);
            var token = await GetTokenAsync(configProvince.HuiJu, cancellationToken);
            return token;
        }
    }
}
