using System.Diagnostics;
using WIDESEA_Common.StockEnum;
using WIDESEA_Core;
using WIDESEA_DTO.MES;
using WIDESEA_IStockService;
using WIDESEA_IBasicService;
namespace WIDESEA_StockService
{
///
/// MES异步上传辅助服务实现
///
public class MesUploadHelper : IMesUploadHelper
{
private readonly IStockInfoService _stockInfoService;
private readonly IMesLogService _mesLogService;
///
/// 构造函数
///
/// 库存信息服务
/// MES日志服务
public MesUploadHelper(IStockInfoService stockInfoService, IMesLogService mesLogService)
{
_stockInfoService = stockInfoService;
_mesLogService = mesLogService;
}
///
/// 以fire-and-forget方式异步执行MES调用,自动更新上传状态并记录日志
///
public void FireAndForget(
string palletCode,
MesUploadStatusEnum successStatus,
string apiType,
string requestJson,
Func<(bool isSuccess, string responseJson, string errorMessage)> mesCall,
string creator = "System")
{
_ = Task.Run(async () =>
{
var stopwatch = Stopwatch.StartNew();
try
{
var (isSuccess, responseJson, errorMessage) = mesCall();
stopwatch.Stop();
// 奇数=成功,偶数=失败
int status = isSuccess ? (int)successStatus : (int)successStatus + 1;
await _stockInfoService.UpdateMesUploadStatusAsync(palletCode, status);
await LogAsync(palletCode, apiType, requestJson, responseJson,
stopwatch.ElapsedMilliseconds, isSuccess, errorMessage, creator);
}
catch (Exception ex)
{
stopwatch.Stop();
int status = (int)successStatus + 1;
await _stockInfoService.UpdateMesUploadStatusAsync(palletCode, status);
await LogAsync(palletCode, apiType, requestJson, "",
stopwatch.ElapsedMilliseconds, false, ex.Message, creator);
}
});
}
///
/// 记录MES接口调用日志
///
private async Task LogAsync(string palletCode, string apiType, string requestJson,
string responseJson, long elapsedMs, bool isSuccess, string errorMessage, string creator)
{
try
{
await _mesLogService.LogAsync(new MesApiLogDto
{
PalletCode = palletCode,
ApiType = apiType,
RequestJson = requestJson,
ResponseJson = responseJson,
IsSuccess = isSuccess,
ErrorMessage = errorMessage,
ElapsedMs = (int)elapsedMs,
Creator = creator
});
}
catch
{
// 日志记录失败不影响主流程
}
}
}
}