using SqlSugar;
namespace Admin.NET.Plugin.AiDOP.DataPlatform.Wms;
///
/// 领料保管员解析。移植基准:旧 DOP ResourceExamineAppService.GenerateNbr
/// (按 EmpWorkDutyMaster.ItemNum1..ItemNum2 字符串区间匹配 Employee;非存储过程 Bonded 分支)。
///
public sealed class KeeperResolveService : ITransient
{
private readonly MdpSourceScopeFactory _scopeFactory;
public KeeperResolveService(MdpSourceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
public sealed class KeeperHit
{
public string ItemNum { get; set; } = "";
public int DutyRecID { get; set; }
public string Employee { get; set; } = "";
public string? Location { get; set; }
}
///
/// 按物料号匹配职责;返回命中列表。未命中不抛错(旧 C# 仅跳过收集 User1)。
/// 若业务要求「未设置保管员则中断建单」,由调用方检查空命中。
///
public async Task> ResolveByItemsAsync(
string domain, IEnumerable itemNums, CancellationToken ct = default)
{
var items = itemNums.Where(x => !string.IsNullOrWhiteSpace(x)).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
if (items.Count == 0) return Array.Empty();
var db = await _scopeFactory.GetScopeAsync("DOPDEMORQ_SQLSERVER", ct);
var duties = await db.Ado.SqlQueryAsync(
@"SELECT RecID, Employee, ItemNum1, ItemNum2, Location
FROM EmpWorkDutyMaster
WHERE Domain=@d",
new SugarParameter("@d", domain));
var hits = new List();
foreach (var item in items)
{
// 与旧 C# 一致:0 >= Compare(ItemNum1, item) && 0 >= Compare(item, ItemNum2)
var ewdm = duties.Find(s =>
string.Compare(s.ItemNum1, item, StringComparison.OrdinalIgnoreCase) <= 0
&& string.Compare(item, s.ItemNum2, StringComparison.OrdinalIgnoreCase) <= 0);
if (ewdm == null || string.IsNullOrEmpty(ewdm.Employee))
continue;
hits.Add(new KeeperHit
{
ItemNum = item,
DutyRecID = ewdm.RecID,
Employee = ewdm.Employee!,
Location = ewdm.Location
});
}
return hits;
}
/// 拼 NbrMaster.User1(逗号)与 User2(JSON 数组字符串),与旧 DOP 一致。
public static (string user1, string user2) FormatKeeperUsers(IEnumerable hits)
{
var emps = hits.Select(x => x.Employee).Where(x => !string.IsNullOrWhiteSpace(x)).Distinct().ToList();
if (emps.Count == 0) return ("", "[]");
var user1 = string.Join(",", emps);
var user2 = System.Text.Json.JsonSerializer.Serialize(emps);
return (user1, user2);
}
private sealed class DutyRow
{
public int RecID { get; set; }
public string? Employee { get; set; }
public string? ItemNum1 { get; set; }
public string? ItemNum2 { get; set; }
public string? Location { get; set; }
}
}