using System;
using System.Diagnostics;
using System.Threading.Tasks;
using HHWMS.Web.Models;
using HHWMS.Web.Models.Agv;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using WalkingTec.Mvvm.Core;
namespace HHWMS.Web.Services.Agv
{
///
/// AGV 工具类:封装与 AGV 调度系统的全部 HTTP 通信(方案 11.5)
/// 职责:显式超时、报文留痕(AgvTaskLog)、响应统一解析、失败抛业务异常
///
public class AgvApiClient
{
private readonly AgvOption _option;
private readonly WTMContext _wtm;
private readonly IUnitWork _unitWork;
private readonly ILogger _logger;
public AgvApiClient(IOptions option, WTMContext wtm, IUnitWork unitWork, ILogger logger)
{
_option = option.Value;
_wtm = wtm;
_unitWork = unitWork;
_logger = logger;
}
///
/// 下发:创建运单(方案 11.2)。成功返回 orderId(=TaskNo);失败抛异常
///
public async Task CreateOrderAsync(AgvCreateOrderRequest request, string taskNo)
{
// Mock 模式:不联网,直接返回约定成功报文
if (_option.MockEnabled)
{
WriteLog(taskNo, "down", "create", request, new AgvApiResponse
{
Code = "0",
Msg = "mock success",
Data = new AgvCreateOrderResult { OrderId = taskNo, ExternalId = request.ExternalId }
}, 0, null);
return new AgvCreateOrderResult { OrderId = taskNo, ExternalId = request.ExternalId };
}
var sw = Stopwatch.StartNew();
try
{
var result = await _wtm.CallAPI>(
"AGV", "api/fleet/orders/create", HttpMethodEnum.POST, request, _option.CallTimeoutSeconds);
sw.Stop();
WriteLog(taskNo, "down", "create", request, result, sw.ElapsedMilliseconds, null);
if (result?.Data == null || result.Data.Code != "0" || result.Data.Data == null)
{
throw new Exception($"AGV下发失败: {result?.Data?.Msg ?? result?.ErrorMsg ?? "无响应"}");
}
return result.Data.Data;
}
catch (Exception ex)
{
_logger.LogError(ex, "AGV下发任务[{taskNo}]异常", taskNo);
throw;
}
}
///
/// 取消运单(方案 11.6)。sceneId 与 orderId 均必填,orderId 即 TaskNo;厂商侧幂等
///
public async Task CancelOrderAsync(string sceneId, string orderId)
{
var request = new AgvCancelOrderRequest { SceneId = sceneId, OrderId = orderId };
if (_option.MockEnabled)
{
WriteLog(orderId, "down", "cancel", request, new AgvApiResponse