using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using HHWMS.Web.Models;
using HHWMS.Web.Support;
using HHWMS.Web.Support.PLC;
using HslCommunication;
using HslCommunication.Profinet.Siemens;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WalkingTec.Mvvm.Core;
using Microsoft.Extensions.Caching.Memory;
using HslCommunication.Core;
namespace HHWMS.Web
{
///
/// 提供给WCS调用接口
/// 调用方向 WCS --> WMS
///
[Public]
[ActionDescription("HHWMS.WCSApi")]
[ApiController]
[Route("api/[controller]/[action]"), ApiExplorerSettings(GroupName = "User")]
public class IWCSController : ApiController
{
private readonly IUnitWork _unitWork;
private readonly IMapper _mapper;
private readonly IMemoryCache _cache;
private const int DEBOUNCE_INTERVAL_MS = 1000; // 防抖间隔1秒
public IWCSController(IUnitWork unitWork, IMapper mapper, IMemoryCache cache)
{
_unitWork = unitWork;
_mapper = mapper;
_cache = cache;
}
///
/// 防抖处理装饰器
///
private async Task WithDebounce(string key, Func> action)
{
try
{
// 使用key作为请求标识
string requestKey = $"Debounce_{key}";
// 检查是否存在处理中的相同请求
if (_cache.TryGetValue(requestKey, out DateTime lastRequestTime))
{
var timeSinceLastRequest = DateTime.Now - lastRequestTime;
if (timeSinceLastRequest.TotalMilliseconds < DEBOUNCE_INTERVAL_MS)
{
var remainingSeconds = Math.Ceiling((DEBOUNCE_INTERVAL_MS - timeSinceLastRequest.TotalMilliseconds) / 1000);
return ApiResultError($"请求过于频繁,请等待{remainingSeconds}秒后重试");
}
}
// 添加或更新缓存(设置防抖间隔时间)
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMilliseconds(DEBOUNCE_INTERVAL_MS));
_cache.Set(requestKey, DateTime.Now, cacheEntryOptions);
try
{
// 执行实际的业务逻辑
return await action();
}
catch (Exception ex)
{
// 处理失败时移除缓存,允许重试
_cache.Remove(requestKey);
throw;
}
}
catch (Exception ex)
{
return ApiResultError($"处理请求时发生错误: {ex.Message}");
}
}
///
/// 请求入库(带防抖)
///
[HttpPost]
public Task RequestIn(WcsRequest request)
{
if (request == null || string.IsNullOrEmpty(request.PalletNo))
{
return Task.FromResult(ApiResultError("请求参数无效"));
}
return WithDebounce($"RequestIn_{request.PalletNo}", async () =>
{
await ProcessRequestIn(request);
return ApiResult(new { Message = "入库请求处理成功" });
});
}
///
/// 处理入库请求的具体业务逻辑
///
private async Task ProcessRequestIn(WcsRequest request)
{
// TODO: 实现具体的入库处理逻辑
await Task.Delay(1000); // 模拟异步处理
}
///
/// 状态返回(带防抖)
///
[HttpPost]
public Task TaskStatusResult(WcsRequest request)
{
if (request == null || string.IsNullOrEmpty(request.PalletNo))
{
return Task.FromResult(ApiResultError("请求参数无效"));
}
return WithDebounce($"TaskStatus_{request.PalletNo}", () => Task.FromResult(ApiResult()));
}
///
/// 请求空闲库位(带防抖)
///
[HttpPost]
public Task RequestLocation(WcsRequest request)
{
if (string.IsNullOrEmpty(request?.PalletNo))
{
return Task.FromResult(ApiResultError("容器编码不能为空"));
}
if (!request.RoadWay.HasValue)
{
return Task.FromResult(ApiResultError("巷道不能为空"));
}
return WithDebounce($"RequestLocation_{request.PalletNo}", () =>
{
var vm = Wtm.CreateVM();
var code = vm.GetLocation(request);
if (code.Status)
{
var updateResult = UpdateLocationAndContainer(code.Data.LocationCode, request.PalletNo);
return Task.FromResult(updateResult);
}
return Task.FromResult(ApiResultError("没有符合条件的可用库位"));
});
}
///
/// 更新库位和容器
///
///
///
///
private IActionResult UpdateLocationAndContainer(string locationCode, string palletNo)
{
var location = _unitWork.Find(x => x.Code == locationCode).FirstOrDefault();
var resultNum = _unitWork.BatchUpdate(x => x.Code == locationCode && x.Version == location.Version,
x => new Location()
{
ContainerCode = palletNo,
// Status = LocationStatus.任务锁,
UpdateTime = DateTime.Now,
UpdateBy = "WMS",
Version = Guid.NewGuid()
});
if (resultNum == 0)
{
//失败
return ApiResult(ApiResultError("更新仓位失败!请重新请求!"));
}
var container = _unitWork.Find(x => x.Code == palletNo).FirstOrDefault();
if (container != null)
{
container.LocationCode = location.Code;
_unitWork.Update(container);
}
return ApiResult(new { LocationCode = location.Code });
}
}
}