using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace ProjectManagementSystem.Common.Service
{
    public class RestApi<T> /*where T : class, new()*/
    {
        private RestClient client = new RestClient();

        public RestApi()
        {
            //client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator("admin", "123456");
            //client.CookieContainer = new System.Net.CookieContainer();
            //client.ClearHandlers();
            //client.AddHandler("text/plain", () => new RestSharp.Serialization.Json.JsonDeserializer());
        }

        public T Get(string url, object pars, object body, out string content)
        {
            IRestResponse<T> reval = GetApiInfo(url, pars, null, body, Method.GET);
            content = reval.Content;
            return reval.Data;
        }
        public T Post(string url, object pars, object body, out string content)
        {
            IRestResponse<T> reval = GetApiInfo(url, pars, null, body, Method.POST);
            content = reval.Content;
            return reval.Data;
        }
        public T Delete(string url, object pars, object body, out string content)
        {
            IRestResponse<T> reval = GetApiInfo(url, pars, null, body, Method.DELETE);
            content = reval.Content;
            return reval.Data;
        }
        public T Put(string url, object pars, object body, out string content)
        {
            IRestResponse<T> reval = GetApiInfo(url, pars, null, body, Method.PUT);
            content = reval.Content;
            return reval.Data;
        }

        public IRestResponse<T> GetApiInfo(string url, object pars, Dictionary<string, string> header, object body, Method type)
        {
            var request = new RestRequest(url, type);
            if (pars != null)
            {
                request.AddObject(pars);
            }

            if (header != null)
            {
                request.AddHeaders(header);
            }

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

            IRestResponse<T> reval = client.Execute<T>(request);
            if (reval.ErrorException != null)
            {
                throw new Exception($"请求出错 {url} {reval.ErrorMessage} {reval.Content}");
            }
            return reval;
        }
    }

}
