89 lines
2.6 KiB
C#
89 lines
2.6 KiB
C#
|
|
using System.Net.Http;
|
||
|
|
using System.Net.Http.Json;
|
||
|
|
using PetWashControl.Models;
|
||
|
|
|
||
|
|
namespace PetWashControl.Services;
|
||
|
|
|
||
|
|
public class ApiService
|
||
|
|
{
|
||
|
|
private readonly HttpClient _httpClient;
|
||
|
|
private readonly ConfigurationService _config;
|
||
|
|
|
||
|
|
public ApiService(ConfigurationService? config = null)
|
||
|
|
{
|
||
|
|
_config = config ?? new ConfigurationService();
|
||
|
|
_httpClient = new HttpClient
|
||
|
|
{
|
||
|
|
BaseAddress = new Uri(_config.ApiBaseUrl),
|
||
|
|
Timeout = TimeSpan.FromSeconds(30)
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task<List<Package>> GetPackagesAsync()
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
return await _httpClient.GetFromJsonAsync<List<Package>>("api/packages")
|
||
|
|
?? new List<Package>();
|
||
|
|
}
|
||
|
|
catch (HttpRequestException ex)
|
||
|
|
{
|
||
|
|
throw new Exception($"无法连接到服务器: {ex.Message}", ex);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task<Order?> CreateOrderAsync(int packageId)
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var response = await _httpClient.PostAsJsonAsync("api/orders", new { packageId });
|
||
|
|
response.EnsureSuccessStatusCode();
|
||
|
|
return await response.Content.ReadFromJsonAsync<Order>();
|
||
|
|
}
|
||
|
|
catch (HttpRequestException ex)
|
||
|
|
{
|
||
|
|
throw new Exception($"创建订单失败: {ex.Message}", ex);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task<Order?> ConfirmPaymentAsync(int orderId)
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var response = await _httpClient.PostAsync($"api/orders/{orderId}/payment", null);
|
||
|
|
response.EnsureSuccessStatusCode();
|
||
|
|
return await response.Content.ReadFromJsonAsync<Order>();
|
||
|
|
}
|
||
|
|
catch (HttpRequestException ex)
|
||
|
|
{
|
||
|
|
throw new Exception($"确认支付失败: {ex.Message}", ex);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task<Order?> GetOrderAsync(int orderId)
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
return await _httpClient.GetFromJsonAsync<Order>($"api/orders/{orderId}");
|
||
|
|
}
|
||
|
|
catch (HttpRequestException ex)
|
||
|
|
{
|
||
|
|
throw new Exception($"获取订单失败: {ex.Message}", ex);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task<Order?> UpdateOrderStatusAsync(int orderId, OrderStatus status)
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var response = await _httpClient.PutAsJsonAsync($"api/orders/{orderId}/status", new { status });
|
||
|
|
response.EnsureSuccessStatusCode();
|
||
|
|
return await response.Content.ReadFromJsonAsync<Order>();
|
||
|
|
}
|
||
|
|
catch (HttpRequestException ex)
|
||
|
|
{
|
||
|
|
throw new Exception($"更新订单状态失败: {ex.Message}", ex);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|