using Dm;
using OASystem.Domain.ViewModels.JuHeExchangeRate;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using Ubiety.Dns.Core;
namespace OASystem.API.OAMethodLib.JuHeAPI
{
    /// 
    /// 聚合Api 服务
    /// 
    public class JuHeApiService: IJuHeApiService
    {
        private readonly HttpClient _httpClient;
        private readonly string _appKey = "0f5429e9fbb8637c0ff3f14bbb42c732"; //配置您申请的appkey
        /// 
        /// 初始化
        /// 
        /// 
        public JuHeApiService(IHttpClientFactory clientFactory)
        {
            _httpClient = clientFactory.CreateClient("PublicJuHeApi"); ;
        }
        /// 
        /// 汇率转换
        /// 
        /// 
        /// 
        public async Task GetExchangeRateAsync()
        {
            var result = new JuHeAPIResult() { Resultcode = "10000",Reason="未知错误" };
            string url = string.Format("/finance/exchange/rmbquot");
            try
            {
                var exchangeReq = await _httpClient.PostAsync(url,
                                    new FormUrlEncodedContent(new List>()
                                    {
                                        new KeyValuePair("key",_appKey),//你申请的key 
                                        new KeyValuePair("type","0"),   //两种格式(0或者1,默认为0)
                                        new KeyValuePair("bank","3")    //(0:工商银行,1:招商银行,2:建设银行,3:中国银行,
                                                                                        //4:交通银行,5:农业银行,默认为:0)
                                    }));
                if (exchangeReq.IsSuccessStatusCode)
                {
                    var stringResponse = await exchangeReq.Content.ReadAsStringAsync();
                    result = System.Text.Json.JsonSerializer.Deserialize(stringResponse,
                    new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
                }
                else
                {
                    result.Reason = "汇率接口请求失败!";
                }
            }
            catch (Exception ex)
            {
                result.Reason = ex.Message;
            }
            
            return result;
        }
    }
}