Files
jinko.yikatong/Src/Dlhis.Middle/Services/Implements/RemoteOrderService.cs
2024-07-04 10:46:11 +08:00

87 lines
2.9 KiB
C#

using System.Net.Http.Headers;
using System.Text;
using Dlhis.Middle.Entities;
using Dlhis.Middle.Request;
using Dlhis.Middle.Response;
using Kurisu.AspNetCore.DataAccess.SqlSugar.Services;
using Kurisu.AspNetCore.UnifyResultAndValidation;
using Kurisu.AspNetCore.Utils.Extensions;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
namespace Dlhis.Middle.Services.Implements;
public class RemoteOrderService : IRemoteOrderService
{
private readonly string _hostName;
private readonly IHttpClientFactory _httpClientFactory;
private readonly IMemoryCache _memoryCache;
private readonly IHealthCheckService _healthCheckService;
private readonly IDbContext _dbContext;
public RemoteOrderService(IHttpClientFactory httpClientFactory,
IMemoryCache memoryCache,
IConfiguration configuration,
IHealthCheckService healthCheckService,
IDbContext dbContext)
{
_httpClientFactory = httpClientFactory;
_memoryCache = memoryCache;
_hostName = configuration.GetSection("hostName").Value;
_healthCheckService = healthCheckService;
_dbContext = dbContext;
}
/// <inheritdoc />
public async Task<DefaultApiResult<OrderResultResponse>> AddAsync(OrderAddRequest request)
{
var token = await AuthAsync();
var httpClient = _httpClientFactory.CreateClient("face");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var content = new StringContent(request.ToJson(), Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync($"https://{_hostName}/api/canteen/orders", content);
var responseJson = await response.Content.ReadAsStringAsync();
return responseJson.ToObject<DefaultApiResult<OrderResultResponse>>();
}
/// <inheritdoc />
public async Task<bool> AbleRemoteCallAsync()
{
if (await _dbContext.Queryable<LocalBalanceRecordEntity>().AnyAsync(x => !x.IsSync))
{
return false;
}
return !_healthCheckService.GetIsOffline();
}
private async Task<string> AuthAsync()
{
var httpClient = _httpClientFactory.CreateClient("face");
if (_memoryCache.TryGetValue("token", out string token)) return token;
var tokenResponse = await httpClient.PostAsync($"https://{_hostName}/api/User/OAuth2/clientgrant", new StringContent(JsonConvert.SerializeObject(new
{
ClientId = "e509c2aaa98e300c",
ClientSecret = "6184d8979fc48105"
}), Encoding.UTF8, "application/json"));
var tokenJson = await tokenResponse.Content.ReadAsStringAsync();
var tokenInfo = JsonConvert.DeserializeObject<DefaultApiResult<TokenResponse>>(tokenJson);
token = tokenInfo.Data.AccessToken;
_memoryCache.Set("token", token, TimeSpan.FromSeconds(tokenInfo.Data.Expires));
return token;
}
}