using DataSharing.Share.Dtos.LuZhou;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Org.BouncyCastle.Asn1.Ocsp;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using XF.Domain.Dependency;

namespace DataSharing.LuZhou.LuZhou110
{
    public class LZ110Invoker : ISingletonDependency, ISelfDependency
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly IServiceScopeFactory _scopeFactory;
        private readonly ILogger<LZ110Invoker> _logger;

        public LZ110Invoker(
            IHttpClientFactory httpClientFactory,
            ILogger<LZ110Invoker> logger, IServiceScopeFactory scopeFactory)
        {
            _httpClientFactory = httpClientFactory;
            _logger = logger;
            _scopeFactory = scopeFactory;
        }

        public async Task<LZ110ApiResponse<TResponse>> InvokeAsync<TRequest, TResponse>(TRequest request,
            CancellationToken cancellationToken)
            where TRequest : ILZ110RequestBase<TResponse>
            where TResponse : class
        {
            using var scope = _scopeFactory.CreateScope();
            var provider = scope.ServiceProvider;
            var httpInvoker = provider.GetRequiredService<IHttpInvoker>();

            using var client = _httpClientFactory.CreateClient();
            var _sharingConfigurationManager = provider.GetRequiredService<ISharingConfigurationManager>();
            client.BaseAddress = new Uri(_sharingConfigurationManager.GetLuZhouConfig().LuZhou110.SendDataAddress);
            client.DefaultRequestHeaders.Add("User-Identify", "12345rexian");
            var serializeOptions = new JsonSerializerOptions
            {
                PropertyNamingPolicy = new JsonPascalNamingPolicy(),
            };

            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 scope = _scopeFactory.CreateScope();
            var provider = scope.ServiceProvider;
            var httpInvoker = provider.GetRequiredService<IHttpInvoker>();
            using var client = _httpClientFactory.CreateClient();

            var _sharingConfigurationManager = provider.GetRequiredService<ISharingConfigurationManager>();

            client.BaseAddress = new Uri(_sharingConfigurationManager.GetLuZhouConfig().LuZhou110.SendDataAddress);
            client.DefaultRequestHeaders.Add("User-Identify", "12345rexian");
            var serializeOptions = new JsonSerializerOptions
            {
                PropertyNamingPolicy = new JsonPascalNamingPolicy(),
            };

            //var result = await client.PostAsJsonAsync(url, new StringContent(stringContent, Encoding.UTF8, new MediaTypeWithQualityHeaderValue("application/json")), serializeOptions, cancellationToken);

            object requst = null;
            switch (url)
            {
                case "/PSPC/SC/12345/GDJCXX": //12345工单基础信息
                    requst = System.Text.Json.JsonSerializer.Deserialize<GDJCXXInfo>(stringContent);
                    break;
                case "/PSPC/SC/12345/GDLZBL": //12345工单流转办理
                    requst = System.Text.Json.JsonSerializer.Deserialize<GDLZBLInfo>(stringContent);
                    break;
                case "/PSPC/SC/12345/GDBLJG": //12345工单办理结果
                    requst = System.Text.Json.JsonSerializer.Deserialize<GDBLJGInfo>(stringContent);
                    break;
                case "/PSPC/SC/12345/GDBLZT": //12345工单办理状态
                    requst = System.Text.Json.JsonSerializer.Deserialize<GDBLZTInfo>(stringContent);
                    break;
                case "/PSPC/SC/12345/GDYQSQ": //12345工单延期申请
                    requst = System.Text.Json.JsonSerializer.Deserialize<GDYQSQInfo>(stringContent);
                    break;
                case "/PSPC/SC/12345/GDHFXX": //12345工单回访信息
                    requst = System.Text.Json.JsonSerializer.Deserialize<GDHFXXInfo>(stringContent);
                    break;
            }

            var result = await client.PostAsJsonAsync(url, requst, 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 };
        }

    }
}
