using Newtonsoft.Json;
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using Wicture.DbRESTFul;

namespace JiaZhiQuan.Common.Utils
{
    public class QTUtils
    {
        const string BASE_URL = "http://qt.olssglobal.com/api/";

        public static async Task<T> GetAKSData<T>(IHttpClientFactory httpClientFactory, string api, object queryData = null, int retryCount = 0)
        {
            string url = BASE_URL + api + (queryData == null ? "" : "?" + ToUrlParams(queryData));

            try
            {
                using var httpClient = httpClientFactory.CreateClient();
                var rst = await httpClient.GetStringAsync(url);
                return JsonConvert.DeserializeObject<T>(rst);
            }
            catch (Exception ex)
            {
                if (retryCount < 1)
                {
                    LoggerManager.Logger.Error(ex, $"请求失败：【{url}】" + ex.Message);
                    throw ex;
                }
                await Task.Delay(2000);
                return await GetAKSData<T>(httpClientFactory, api, queryData, --retryCount);
            }
        }


        public static string ToUrlParams(object obj)
        {
            return string.Join("&",
                obj.GetType().GetProperties().Where(x => x.GetValue(obj) != null).Select(x =>
                    $"{x.Name}={HttpUtility.UrlEncode(x.GetValue(obj, null).ToString())}"));
        }
    }
}
