using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using YunDa.Server.ISMSTcp.Configuration; using YunDa.SOMS.DataTransferObject; namespace YunDa.Server.ISMSTcp.Services { /// /// 孪生体ID API服务实现 /// public class TwinIdApiService : ITwinIdApiService { private readonly HttpClient _httpClient; private readonly ILogger _logger; private readonly ApiEndpointsConfiguration _apiConfig; public TwinIdApiService( HttpClient httpClient, ILogger logger, IOptions apiConfig) { _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _apiConfig = apiConfig?.Value ?? throw new ArgumentNullException(nameof(apiConfig)); } /// /// 通过孪生体代码获取设备信息ID /// /// 孪生体代码 /// 取消令牌 /// 设备信息ID public async Task> GetTwIdAsync(string code, CancellationToken cancellationToken = default) { try { if (string.IsNullOrWhiteSpace(code)) { _logger.LogWarning("GetTwIdAsync called with empty or null code"); return RequestResult.CreateFailed("孪生体代码不能为空"); } // 构建完整的API URL var baseUrl = _apiConfig.BaseUrl.TrimEnd('/'); var getTwIdPath = _apiConfig.GetTwId ?? "/api/services/SOMS/RackEquipment/GetTwId"; var fullUrl = $"{baseUrl}{getTwIdPath}?code={Uri.EscapeDataString(code)}"; _logger.LogDebug("Making API call to GetTwId: {Url}", fullUrl); // 发送HTTP GET请求 var response = await _httpClient.GetAsync(fullUrl, cancellationToken).ConfigureAwait(false); if (response.IsSuccessStatusCode) { var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); _logger.LogDebug("GetTwId API response: {Response}", responseContent); // 反序列化响应 var result = JsonConvert.DeserializeObject>(responseContent); if (result != null) { _logger.LogInformation("Successfully retrieved TwId for code: {Code}, EquipmentInfoId: {EquipmentInfoId}", code, result.ResultData); return result; } else { _logger.LogWarning("GetTwId API returned null result for code: {Code}", code); return RequestResult.CreateFailed("API返回空结果"); } } else { var errorContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); _logger.LogError("GetTwId API call failed with status {StatusCode}: {ErrorContent}", response.StatusCode, errorContent); return RequestResult.CreateFailed($"API调用失败: {response.StatusCode}"); } } catch (HttpRequestException ex) { _logger.LogError(ex, "HTTP request exception when calling GetTwId API for code: {Code}", code); return RequestResult.CreateFailed($"网络请求异常: {ex.Message}"); } catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException) { _logger.LogError(ex, "Timeout when calling GetTwId API for code: {Code}", code); return RequestResult.CreateFailed("API调用超时"); } catch (TaskCanceledException ex) when (cancellationToken.IsCancellationRequested) { _logger.LogWarning("GetTwId API call was cancelled for code: {Code}", code); return RequestResult.CreateFailed("请求已取消"); } catch (JsonException ex) { _logger.LogError(ex, "JSON deserialization error when calling GetTwId API for code: {Code}", code); return RequestResult.CreateFailed($"响应解析失败: {ex.Message}"); } catch (Exception ex) { _logger.LogError(ex, "Unexpected error when calling GetTwId API for code: {Code}", code); return RequestResult.CreateFailed($"未知错误: {ex.Message}"); } } } }