using Newtonsoft.Json;
using RestSharp;

namespace IRaCIS.Core.Application.Helper.OtherTool
{
    public static class RestClientAPI
    {
        public static async Task<T> GetAsync<T>(string api, Dictionary<string, string> query = null, Dictionary<string, string> headers = null)
        {
            using var _client = new RestClient();

            var request = new RestRequest(api, Method.Get);

            if (query != null)
            {
                foreach (var kv in query)
                {
                    request.AddParameter(kv.Key, kv.Value);
                }
            }

            if (headers != null)
            {
                foreach (var header in headers)
                {
                    request.AddHeader(header.Key, header.Value);
                }
            }


            var response = await _client.ExecuteAsync(request);

            if (response.IsSuccessful)
            {
                return JsonConvert.DeserializeObject<T>(response.Content ?? string.Empty);

            }
            else
            {
                Console.WriteLine($"请求失败，错误代码: {response.StatusCode}, 错误消息: {response.ErrorMessage}");
                return JsonConvert.DeserializeObject<T>(string.Empty);
            }

        }

        public static async Task<T> PostAsync<T>(string api, object jsonObj = null, Dictionary<string, string> headers = null)
        {
            using var _client = new RestClient();

            var request = new RestRequest(api, Method.Post);

            if (jsonObj != null)
            {
                request.AddJsonBody(jsonObj);
            }

            if (headers != null)
            {
                foreach (var header in headers)
                {
                    request.AddHeader(header.Key, header.Value);
                }
            }


            var response = await _client.ExecuteAsync(request);

            if (response.IsSuccessful)
            {
                return JsonConvert.DeserializeObject<T>(response.Content ?? string.Empty);

            }
            else
            {
                Console.WriteLine($"请求失败，错误代码: {response.StatusCode}, 错误消息: {response.ErrorMessage}");
                return JsonConvert.DeserializeObject<T>(string.Empty);
            }
        }
    }
}
