using JLHHJSvr.LJException;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;

namespace JLHHJSvr.LJFramework.Tools
{
    public class LJHttpUtil
    {
        private static readonly HttpClient httpClient = new HttpClient();
        private const string ContentType = "application/json";

        public static JObject PostRequest(string url, JObject requestObj)
        {
            var jsonStr = requestObj.ToString();
            var content = new StringContent(jsonStr, Encoding.UTF8, ContentType);

            try
            {
                using (var response = httpClient.PostAsync(url, content).Result)
                {
                    response.EnsureSuccessStatusCode();
                    var responseBody = response.Content.ReadAsStringAsync().Result;

                    try
                    {
                        var result = JsonConvert.DeserializeObject<JObject>(responseBody);
                        return result;
                    }
                    catch (JsonReaderException e)
                    {
                        throw new LJCommonException($"JSON 反序列化失败：{e.Message}\r\n响应体：{responseBody}");
                    }
                }
            }
            catch (HttpRequestException e)
            {
                throw new HttpRequestException($"请求错误：{e.Message}", e);
            }
        }
    }
}
