using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Security;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
using Newtonsoft.Json;
using IRaCIS.Core.Infrastructure.Extention;
using NPOI.SS.Formula.Functions;

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);
            }
        }
    }
}