using System.Diagnostics;
|
using WIDESEA_Common.StockEnum;
|
using WIDESEA_Core;
|
using WIDESEA_DTO.MES;
|
using WIDESEA_IStockService;
|
using WIDESEA_IBasicService;
|
|
namespace WIDESEA_StockService
|
{
|
/// <summary>
|
/// MES异步上传辅助服务实现
|
/// </summary>
|
public class MesUploadHelper : IMesUploadHelper
|
{
|
private readonly IStockInfoService _stockInfoService;
|
private readonly IMesLogService _mesLogService;
|
|
/// <summary>
|
/// 构造函数
|
/// </summary>
|
/// <param name="stockInfoService">库存信息服务</param>
|
/// <param name="mesLogService">MES日志服务</param>
|
public MesUploadHelper(IStockInfoService stockInfoService, IMesLogService mesLogService)
|
{
|
_stockInfoService = stockInfoService;
|
_mesLogService = mesLogService;
|
}
|
|
/// <summary>
|
/// 以fire-and-forget方式异步执行MES调用,自动更新上传状态并记录日志
|
/// </summary>
|
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);
|
}
|
});
|
}
|
|
/// <summary>
|
/// 记录MES接口调用日志
|
/// </summary>
|
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
|
{
|
// 日志记录失败不影响主流程
|
}
|
}
|
}
|
}
|