using Azure.Core;
using IRaCIS.Core.Infrastructure.Extention;
using IRaCIS.Core.Infrastructure;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using RestSharp;
using System.Net;
using IRaCIS.Application.Contracts;
using System.Security.Policy;

namespace EI_TestProject
{
    public static class RestHelper
    {
        private static RestClient _client { get; set; }

        private static string _token { get; set; }



        public static RestClient InitRestHelper(string baseUrl, string userName, string md5Pwd)
        {
            _client = new RestClient(baseUrl);

            _client.AddDefaultHeader("Content-Type", "application/json");

            var result = (LoginAndGetAccessTokenAsync<ResponseOutput<LoginReturnDTO>>(userName, md5Pwd)).Result;

            _token = result.Data.JWTStr;

            return _client;
        }



        /// <summary>
        /// 登录获取Token
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="userName"></param>
        /// <param name="md5Pwd"></param>
        /// <returns></returns>
        private static async Task<T> LoginAndGetAccessTokenAsync<T>(string userName, string md5Pwd)
        {
            var jsonBody = new JObject {
            { "UserName", userName.Trim() },
            { "Password", md5Pwd }
            };

            var result = await Post_JsonBodyRequestAsync<T>("/user/login", jsonBody, false);
            return result;
        }

        /// <summary>
        /// json   Post 请求 封装
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="jsonBody"></param>
        /// <param name="isAddToken"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static async Task<T> Post_JsonBodyRequestAsync<T>(string url, object jsonBody, bool isAddToken = true, RestClient? restClient=null)
        {
            var client = restClient ?? _client;

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

            if (isAddToken)
            {
                var accessToken = _token;
                request.AddHeader("Authorization", "Bearer " + accessToken);
            }

            request.AddParameter("application/json", jsonBody.ToString(), ParameterType.RequestBody);

            var response = await client.ExecuteAsync(request);
            if (response.StatusCode == HttpStatusCode.OK)
            {
                return JsonConvert.DeserializeObject<T>(response.Content);
            }
            else
            {
                throw new Exception($"Error {response.StatusCode}: {response.StatusDescription}. {response.Content}");
            }
        }


        public static async Task<T> Put_JsonBodyRequestAsync<T>(string url, JObject jsonBody, bool isAddToken = true, RestClient? restClient = null)
        {
            var client = restClient ?? _client;

            var request = new RestRequest(url, Method.Put);

            if (isAddToken)
            {
                var accessToken = _token;
                request.AddHeader("Authorization", "Bearer " + accessToken);
            }

            request.AddParameter("application/json", jsonBody.ToString(), ParameterType.RequestBody);

            var response = await client.ExecuteAsync(request);
            if (response.StatusCode == HttpStatusCode.OK)
            {
                return JsonConvert.DeserializeObject<T>(response.Content);
            }
            else
            {
                throw new Exception($"Error {response.StatusCode}: {response.StatusDescription}. {response.Content}");
            }
        }


        /// <summary>
        /// URL  Delete 请求封装
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static async Task<T> DeleteRequestAsync<T>(string url)
        {
            var request = new RestRequest(url, Method.Delete);
            var accessToken = _token;
            request.AddHeader("Authorization", "Bearer " + accessToken);

            var response = await _client.ExecuteAsync(request);
            if (response.StatusCode == HttpStatusCode.OK)
            {
                return JsonConvert.DeserializeObject<T>(response.Content);
            }
            else
            {
                throw new Exception($"Error {response.StatusCode}: {response.StatusDescription}. {response.Content}");
            }
        }


        public static async Task<T> GetRequestAsync<T>(string url)
        {
            var request = new RestRequest(url, Method.Get);
            var accessToken = _token;
            request.AddHeader("Authorization", "Bearer " + accessToken);

            var response = await _client.ExecuteAsync(request);
            if (response.StatusCode == HttpStatusCode.OK)
            {
                return JsonConvert.DeserializeObject<T>(response.Content);
            }
            else
            {
                throw new Exception($"Error {response.StatusCode}: {response.StatusDescription}. {response.Content}");
            }
        }


    }
}