using MapsterMapper;
using Microsoft.Extensions.Logging;
using Org.BouncyCastle.Asn1.Ocsp;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;

namespace DataSharing.LuZhou.LZ110
{
    public class LZ110Invoker
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly IMapper _mapper;
        private readonly ILogger<LZ110Invoker> _logger;
        private readonly ISharingConfigurationManager _sharingConfigurationManager;

        public LZ110Invoker(
            IHttpClientFactory httpClientFactory,
            IMapper mapper,
            ILogger<LZ110Invoker> logger,
           ISharingConfigurationManager sharingConfigurationManager)
        {
            _httpClientFactory = httpClientFactory;
            _mapper = mapper;
            _logger = logger;
            _sharingConfigurationManager = sharingConfigurationManager;
        }

        public async Task<LZ110ApiResponse<TResponse>> InvokeAsync<TRequest, TResponse>(TRequest request,
            CancellationToken cancellationToken)
            where TRequest : ILZ110RequestBase<TResponse>
            where TResponse : class
        {
            using var client = _httpClientFactory.CreateClient();
            client.BaseAddress = new Uri(_sharingConfigurationManager.GetLuZhouConfig().LuZhou110.SendDataAddress);
            client.DefaultRequestHeaders.Add("User-Identify", "12345rexian");
            var serializeOptions = new JsonSerializerOptions
            {
                PropertyNamingPolicy = new JsonPascalNamingPolicy(),
            };

            _logger.LogInformation($"发起请求LZ110：{request.GetRequestUrl()}");
            var result = await client.PostAsJsonAsync(request.GetRequestUrl(), request, serializeOptions, cancellationToken);

            if (result is null || !result.IsSuccessStatusCode)
            {
                _logger.LogError($"泸州110接口请求失败，request: {request}");
                return new LZ110ApiResponse<TResponse> { Code = 1, Message = $"泸州110接口请求失败，request: {request}" };
            }
            var response = await result.Content.ReadFromJsonAsync<TResponse>();
            return new LZ110ApiResponse<TResponse> { Code = 0, Data = response };
        }

        /// <summary>
        /// 请求
        /// </summary>
        /// <typeparam name="TResponse"></typeparam>
        /// <param name="url"></param>
        /// <param name="stringContent"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<LZ110ApiResponse<TResponse>> RequestStringContentAsync<TResponse>(string url, string? stringContent = null, CancellationToken cancellationToken = default)
        {
            using var client = _httpClientFactory.CreateClient();
            client.BaseAddress = new Uri(_sharingConfigurationManager.GetLuZhouConfig().LuZhou110.SendDataAddress);
            client.DefaultRequestHeaders.Add("User-Identify", "12345rexian");
            var serializeOptions = new JsonSerializerOptions
            {
                PropertyNamingPolicy = new JsonPascalNamingPolicy(),
            };

            _logger.LogInformation($"发起请求LZ110地址：{url}");
            _logger.LogInformation($"发起请求LZ110内容：{stringContent}");
            var result = await client.PostAsJsonAsync(url, new StringContent(stringContent, Encoding.UTF8, new MediaTypeWithQualityHeaderValue("application/json")), serializeOptions, cancellationToken);

            if (result is null || !result.IsSuccessStatusCode)
            {
                _logger.LogError($"泸州110接口请求失败，request: {url}");
                return new LZ110ApiResponse<TResponse> { Code = 1, Message = $"泸州110接口请求失败，request: {url}" };
            }
            var response = await result.Content.ReadFromJsonAsync<TResponse>();
            return new LZ110ApiResponse<TResponse> { Code = 0, Data = response };
        }

    }
}
