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> GetPackagesAsync() { try { return await _httpClient.GetFromJsonAsync>("api/packages") ?? new List(); } catch (HttpRequestException ex) { throw new Exception($"无法连接到服务器: {ex.Message}", ex); } } public async Task CreateOrderAsync(int packageId) { try { var response = await _httpClient.PostAsJsonAsync("api/orders", new { packageId }); response.EnsureSuccessStatusCode(); return await response.Content.ReadFromJsonAsync(); } catch (HttpRequestException ex) { throw new Exception($"创建订单失败: {ex.Message}", ex); } } public async Task ConfirmPaymentAsync(int orderId) { try { var response = await _httpClient.PostAsync($"api/orders/{orderId}/payment", null); response.EnsureSuccessStatusCode(); return await response.Content.ReadFromJsonAsync(); } catch (HttpRequestException ex) { throw new Exception($"确认支付失败: {ex.Message}", ex); } } public async Task GetPaymentStatusAsync(int orderId, string outTradeNo) { try { return await _httpClient.GetFromJsonAsync( $"api/orders/{orderId}/payment-status?outTradeNo={Uri.EscapeDataString(outTradeNo)}"); } catch (HttpRequestException ex) { throw new Exception($"获取支付状态失败: {ex.Message}", ex); } } public async Task GetOrderAsync(int orderId) { try { return await _httpClient.GetFromJsonAsync($"api/orders/{orderId}"); } catch (HttpRequestException ex) { throw new Exception($"获取订单失败: {ex.Message}", ex); } } public async Task UpdateOrderStatusAsync(int orderId, OrderStatus status) { try { var response = await _httpClient.PutAsJsonAsync($"api/orders/{orderId}/status", new { status }); response.EnsureSuccessStatusCode(); return await response.Content.ReadFromJsonAsync(); } catch (HttpRequestException ex) { throw new Exception($"更新订单状态失败: {ex.Message}", ex); } } public async Task UpdatePackageAsync(Package package) { try { var response = await _httpClient.PutAsJsonAsync($"api/packages/{package.Id}", new { package.Price, package.FirstSprayWaterTime, package.AfterShampoo1SprayTime, package.AfterShampoo2SprayTime, package.AfterShampoo3SprayTime, package.SprayShampoo1Time, package.SprayShampoo2Time, package.SprayShampoo3Time, package.HotAirTime, package.ColdAirTime, package.UvSterilizationTime }); response.EnsureSuccessStatusCode(); return await response.Content.ReadFromJsonAsync(); } catch (HttpRequestException ex) { throw new Exception($"保存套餐配置失败: {ex.Message}", ex); } } }