using Microsoft.Extensions.Configuration; using System.Net.Http; using System.IO; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; using System.Globalization; using System.Web; using Prism.Events; using YY.Admin.Core; using YY.Admin.Core.Entity; using YY.Admin.Core.Events; using YY.Admin.Core.Services; namespace YY.Admin.Services.Service.RawMaterialEntry; public class RawMaterialEntryService : IRawMaterialEntryService, ISingletonDependency { private readonly IHttpClientFactory _httpClientFactory; private readonly IConfiguration _configuration; private readonly INetworkMonitor _networkMonitor; private readonly IEventAggregator _eventAggregator; private readonly ILoggerService _logger; private readonly IPrintBizTemplateBindService _printBizTemplateBindService; private readonly IPrintTemplateService _printTemplateService; private readonly SemaphoreSlim _syncLock = new(1, 1); private readonly object _cacheLock = new(); private readonly string _pendingOpsFilePath; private readonly string _cacheFilePath; private List _pendingOps = new(); private List _localCache = new(); private static readonly JsonSerializerOptions _jsonOpts = new() { PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, Converters = { new NullableDateTimeJsonConverter() } }; public RawMaterialEntryService( IHttpClientFactory httpClientFactory, IConfiguration configuration, INetworkMonitor networkMonitor, IEventAggregator eventAggregator, ILoggerService logger, IPrintBizTemplateBindService printBizTemplateBindService, IPrintTemplateService printTemplateService) { _httpClientFactory = httpClientFactory; _configuration = configuration; _networkMonitor = networkMonitor; _eventAggregator = eventAggregator; _logger = logger; _printBizTemplateBindService = printBizTemplateBindService; _printTemplateService = printTemplateService; var appDataDir = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "YY.Admin", "sync-cache"); Directory.CreateDirectory(appDataDir); _pendingOpsFilePath = Path.Combine(appDataDir, "mes-xsl-raw-material-entry-pending-ops.json"); _cacheFilePath = Path.Combine(appDataDir, "mes-xsl-raw-material-entry-cache.json"); LoadPendingOpsFromDisk(); LoadCacheFromDisk(); _logger.Information($"[原料入场] 服务初始化完成,缓存={_localCache.Count},待上传={_pendingOps.Count},在线={_networkMonitor.IsOnline}"); _networkMonitor.StatusChanged += OnNetworkStatusChanged; if (_networkMonitor.IsOnline) { _ = Task.Run(() => SyncAfterReconnectAsync(CancellationToken.None)); } } private const int MaxPendingRetries = 5; private const string RawMaterialEntryBizCode = "1900000000000000530"; private const string RawMaterialEntryTemplateCode = "MES_RAW_MATERIAL_ENTRY"; private string BaseUrl => (_configuration.GetValue("JeecgIntegration:BaseUrl") ?? "http://localhost:8080/jeecg-boot").TrimEnd('/'); private int DefaultTenantId => (int?)_configuration.GetValue("JeecgIntegration:DefaultTenantId") ?? 1002; private HttpClient CreateClient() => _httpClientFactory.CreateClient("JeecgApi"); public async Task PageAsync( int pageNo, int pageSize, string? barcode = null, string? batchNo = null, string? billNo = null, string? materialName = null, string? supplierName = null, CancellationToken ct = default) { List? source = null; if (_networkMonitor.IsOnline) { try { source = await FetchRemoteListAsync(ct).ConfigureAwait(false); lock (_cacheLock) { _localCache = source.Select(Clone).ToList(); SaveCacheToDiskUnsafe(); } _logger.Information($"[原料入场列表] 远端拉取成功 count={source.Count}"); } catch (Exception ex) { source = null; _logger.Warning($"[原料入场列表] 远端拉取失败,回退缓存:{ex.Message}"); } } lock (_cacheLock) { source ??= _localCache.Select(Clone).ToList(); source = ApplyPendingOpsSnapshotUnsafe(source); } var filtered = ApplyFilters(source, barcode, batchNo, billNo, materialName, supplierName); var total = filtered.Count; var pageRecords = filtered.Skip(Math.Max(0, (pageNo - 1) * pageSize)).Take(pageSize).ToList(); return new RawMaterialEntryPageResult(pageRecords, total, pageNo, pageSize); } public async Task GetByIdAsync(string id, CancellationToken ct = default) { if (_networkMonitor.IsOnline) { try { var url = $"{BaseUrl}/xslmes/mesXslRawMaterialEntry/anon/queryById?id={Uri.EscapeDataString(id)}&tenantId={DefaultTenantId}"; using var client = CreateClient(); var resp = await client.GetAsync(url, ct).ConfigureAwait(false); if (!resp.IsSuccessStatusCode) return null; var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false); using var doc = JsonDocument.Parse(json); if (!doc.RootElement.TryGetProperty("result", out var resultEl)) return null; return resultEl.Deserialize(_jsonOpts); } catch (Exception ex) { _logger.Warning($"[原料入场详情] 远端查询失败,回退缓存 id={id}:{ex.Message}"); } } lock (_cacheLock) { return _localCache.FirstOrDefault(e => string.Equals(e.Id, id, StringComparison.OrdinalIgnoreCase)) is { } found ? Clone(found) : null; } } public async Task AddAsync(MesXslRawMaterialEntry entry, CancellationToken ct = default) { if (!entry.TenantId.HasValue || entry.TenantId.Value <= 0) entry.TenantId = DefaultTenantId; var local = Clone(entry); if (string.IsNullOrWhiteSpace(local.Id)) local.Id = $"local-{Guid.NewGuid():N}"; EnsureBarcodeAndBatchNo(local); if (_networkMonitor.IsOnline) { try { var ok = await RemoteAddAsync(local, ct).ConfigureAwait(false); if (ok) { UpsertLocalCache(local); return true; } return false; } catch (Exception ex) { _logger.Warning($"[原料入场新增] 远端失败,转离线 id={local.Id}:{ex.Message}"); } } EnqueuePendingOperation(new EntryPendingOperation { OpType = EntryOpType.Add, EntryId = local.Id, Entry = local, CreatedAt = DateTime.UtcNow }); UpsertLocalCache(local); return true; } public async Task EditAsync(MesXslRawMaterialEntry entry, CancellationToken ct = default) { if (!entry.TenantId.HasValue || entry.TenantId.Value <= 0) entry.TenantId = DefaultTenantId; var local = Clone(entry); if (_networkMonitor.IsOnline) { try { var (ok, _) = await RemoteEditAsync(local, ct).ConfigureAwait(false); if (ok) { UpsertLocalCache(local); return true; } return false; } catch (Exception ex) { _logger.Warning($"[原料入场修改] 远端失败,转离线 id={local.Id}:{ex.Message}"); } } EnqueuePendingOperation(new EntryPendingOperation { OpType = EntryOpType.Edit, EntryId = local.Id, Entry = local, AnchorUpdateTime = local.UpdateTime, CreatedAt = DateTime.UtcNow }); UpsertLocalCache(local); return true; } public async Task DeleteAsync(string id, CancellationToken ct = default) { if (_networkMonitor.IsOnline) { try { var ok = await RemoteDeleteAsync(id, ct).ConfigureAwait(false); if (ok) { RemoveFromLocalCache(id); return true; } return false; } catch (Exception ex) { _logger.Warning($"[原料入场删除] 远端失败,转离线 id={id}:{ex.Message}"); } } DateTime? anchor; lock (_cacheLock) { anchor = _localCache.FirstOrDefault(e => string.Equals(e.Id, id, StringComparison.OrdinalIgnoreCase))?.UpdateTime; } EnqueuePendingOperation(new EntryPendingOperation { OpType = EntryOpType.Delete, EntryId = id, AnchorUpdateTime = anchor, CreatedAt = DateTime.UtcNow }); RemoveFromLocalCache(id); return true; } public async Task DeleteBatchAsync(string ids, CancellationToken ct = default) { var idList = ids.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); var allSuccess = true; foreach (var id in idList) allSuccess &= await DeleteAsync(id, ct).ConfigureAwait(false); return allSuccess; } public async Task GenerateBarcodeAsync(string materialCode, CancellationToken ct = default) { if (!_networkMonitor.IsOnline) { return GenerateLocalBarcode(materialCode); } var url = $"{BaseUrl}/xslmes/mesXslRawMaterialEntry/anon/generateBarcode?materialCode={Uri.EscapeDataString(materialCode ?? "")}"; try { using var client = CreateClient(); var resp = await client.GetAsync(url, ct).ConfigureAwait(false); resp.EnsureSuccessStatusCode(); var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false); using var doc = JsonDocument.Parse(json); if (doc.RootElement.TryGetProperty("result", out var el)) return el.GetString(); } catch (Exception ex) { _logger.Warning($"[原料入场] 生成条码失败: {ex.Message}"); } return GenerateLocalBarcode(materialCode); } /// /// 桌面端离线兜底产号:保持与服务端一致的格式 QH + 物料编码 + yyMMdd + 3位流水。 /// 流水号口径与服务端一致:按当前前缀匹配条码计数 + 1(非 max+1)。 /// private string GenerateLocalBarcode(string materialCode) { var normalizedCode = (materialCode ?? string.Empty).Trim(); var dateStr = DateTime.Now.ToString("yyMMdd", CultureInfo.InvariantCulture); var prefix = $"QH{normalizedCode}{dateStr}"; int sequence; lock (_cacheLock) { var snapshot = ApplyPendingOpsSnapshotUnsafe(_localCache.Select(Clone).ToList()); var count = snapshot.Count(x => !string.IsNullOrWhiteSpace(x.Barcode) && x.Barcode!.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)); sequence = count + 1; } return $"{prefix}{sequence:000}"; } /// /// 新增入场记录时保证条码和批次号本地可用: /// 条码为空时本地生成,批次号为空时回填为条码。 /// private void EnsureBarcodeAndBatchNo(MesXslRawMaterialEntry entry) { if (string.IsNullOrWhiteSpace(entry.Barcode)) { entry.Barcode = GenerateLocalBarcode(entry.MaterialCode ?? string.Empty); } if (string.IsNullOrWhiteSpace(entry.BatchNo)) { entry.BatchNo = entry.Barcode; } } public async Task<(string templateJson, string printDataJson, string? errorMessage)> PrepareNativePrintAsync(string id, CancellationToken ct = default) { if (_networkMonitor.IsOnline) { try { var url = $"{BaseUrl}/xslmes/mesXslRawMaterialEntry/anon/prepareNativePrint?id={Uri.EscapeDataString(id)}&tenantId={DefaultTenantId}"; using var client = CreateClient(); var resp = await client.GetAsync(url, ct).ConfigureAwait(false); var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false); using var doc = JsonDocument.Parse(json); var root = doc.RootElement; if (!root.TryGetProperty("code", out var codeEl) || codeEl.GetInt32() != 200) { var msg = root.TryGetProperty("message", out var msgEl) ? msgEl.GetString() : "未知错误"; return (string.Empty, "{}", msg ?? "服务端返回错误"); } var result = root.GetProperty("result"); var templateJson = result.TryGetProperty("templateJson", out var tjEl) ? tjEl.GetString() : null; var printDataJson = result.TryGetProperty("printData", out var pdEl) ? pdEl.GetRawText() : "{}"; if (string.IsNullOrWhiteSpace(templateJson)) return (string.Empty, "{}", "服务端未返回模板 JSON,请先在「业务打印绑定」中配置原料入场记录"); return (templateJson!, printDataJson, null); } catch (Exception ex) { _logger.Warning($"[原料入场] 远端准备打印数据失败,回退本地模板渲染 id={id}: {ex.Message}"); } } return await PrepareLocalNativePrintAsync(id, ct).ConfigureAwait(false); } private async Task<(string templateJson, string printDataJson, string? errorMessage)> PrepareLocalNativePrintAsync(string id, CancellationToken ct) { var entry = GetEntrySnapshotById(id); if (entry == null) { return (string.Empty, "{}", "本地未找到入场记录,无法离线打印"); } var bindList = _printBizTemplateBindService.GetCached(); if (bindList.Count == 0) { try { bindList = await _printBizTemplateBindService.ListAsync(ct).ConfigureAwait(false); } catch { } } var bind = bindList.FirstOrDefault(x => string.Equals(x.BizCode, RawMaterialEntryBizCode, StringComparison.OrdinalIgnoreCase)) ?? bindList.FirstOrDefault(x => string.Equals(x.TemplateCode, RawMaterialEntryTemplateCode, StringComparison.OrdinalIgnoreCase)) ?? bindList.FirstOrDefault(x => (x.BizName ?? string.Empty).Contains("原料入场记录", StringComparison.OrdinalIgnoreCase)); if (bind == null) { return (string.Empty, "{}", "未找到本地业务打印绑定,请先在线同步「原料入场记录」模板配置"); } var templates = _printTemplateService.GetCached(); if (templates.Count == 0) { try { templates = await _printTemplateService.ListAsync(ct).ConfigureAwait(false); } catch { } } var templateCode = string.IsNullOrWhiteSpace(bind.TemplateCode) ? RawMaterialEntryTemplateCode : bind.TemplateCode!; var tpl = templates.FirstOrDefault(t => !string.IsNullOrWhiteSpace(bind.TemplateId) && string.Equals(t.Id, bind.TemplateId, StringComparison.OrdinalIgnoreCase)) ?? templates.FirstOrDefault(t => string.Equals(t.TemplateCode, templateCode, StringComparison.OrdinalIgnoreCase)); if (tpl == null || string.IsNullOrWhiteSpace(tpl.TemplateJson)) { return (string.Empty, "{}", "本地未找到打印模板,请先在线同步模板后再离线打印"); } var mappingJson = string.IsNullOrWhiteSpace(bind.FieldMappingJson) ? "[]" : bind.FieldMappingJson!; var printData = BuildPrintDataFromMapping(entry, mappingJson, tpl.TemplateJson!); return (tpl.TemplateJson!, printData.ToJsonString(), null); } private MesXslRawMaterialEntry? GetEntrySnapshotById(string id) { if (string.IsNullOrWhiteSpace(id)) return null; lock (_cacheLock) { var snapshot = ApplyPendingOpsSnapshotUnsafe(_localCache.Select(Clone).ToList()); return snapshot.FirstOrDefault(e => string.Equals(e.Id, id, StringComparison.OrdinalIgnoreCase)) is { } found ? Clone(found) : null; } } private JsonObject BuildPrintDataFromMapping(T source, string mappingJson, string templateJson) { JsonObject printData = new(); JsonNode? bizRoot = JsonSerializer.SerializeToNode(source, _jsonOpts); try { var mappingNode = JsonNode.Parse(mappingJson) as JsonArray; if (mappingNode != null) { foreach (var rule in mappingNode) { if (rule is not JsonObject obj) continue; var templateField = obj["templateField"]?.GetValue()?.Trim(); if (string.IsNullOrWhiteSpace(templateField)) continue; var bizField = obj["bizField"]?.GetValue()?.Trim(); JsonNode? value = string.IsNullOrWhiteSpace(bizField) ? JsonValue.Create(string.Empty) : ResolvePath(bizRoot, bizField!); SetPath(printData, templateField!, NormalizePrintNodeValue(value)); } } } catch { // 映射异常时继续按模板字段补空,避免影响整体打印 } try { var templateNode = JsonNode.Parse(templateJson); var bindFields = new HashSet(StringComparer.OrdinalIgnoreCase); CollectTemplateBindFields(templateNode, bindFields); foreach (var key in bindFields) { if (!HasPath(printData, key)) { SetPath(printData, key, JsonValue.Create(string.Empty)!); } } } catch { // 模板结构异常时忽略补空逻辑 } return printData; } private static void CollectTemplateBindFields(JsonNode? node, HashSet fields) { if (node == null) return; if (node is JsonObject obj) { if (obj["dataBinding"] is JsonObject db && db["params"] is JsonArray paramArr) { foreach (var p in paramArr) { var key = p?["key"]?.GetValue()?.Trim(); if (!string.IsNullOrWhiteSpace(key)) fields.Add(key!); } } var bindField = obj["bindField"]?.GetValue()?.Trim(); if (!string.IsNullOrWhiteSpace(bindField)) fields.Add(bindField!); if (obj["columns"] is JsonArray cols) { foreach (var c in cols) { var cBind = c?["bindField"]?.GetValue()?.Trim(); var cField = c?["field"]?.GetValue()?.Trim(); if (!string.IsNullOrWhiteSpace(cBind)) fields.Add(cBind!); else if (!string.IsNullOrWhiteSpace(cField)) fields.Add(cField!); } } foreach (var kv in obj) { CollectTemplateBindFields(kv.Value, fields); } return; } if (node is JsonArray arr) { foreach (var item in arr) { CollectTemplateBindFields(item, fields); } } } private static JsonNode? ResolvePath(JsonNode? root, string path) { if (root == null || string.IsNullOrWhiteSpace(path)) return null; var parts = path.Split('.', StringSplitOptions.RemoveEmptyEntries); JsonNode? current = root; foreach (var part in parts) { if (current == null) return null; if (current is JsonArray arr) { if (int.TryParse(part, out var index)) { current = index >= 0 && index < arr.Count ? arr[index] : null; } else { current = arr.Count > 0 ? arr[0]?[part] : null; } } else { current = current[part]; } } return current; } private static bool HasPath(JsonObject root, string path) { var parts = path.Split('.', StringSplitOptions.RemoveEmptyEntries); JsonNode? current = root; for (int i = 0; i < parts.Length; i++) { if (current is not JsonObject obj) return false; if (!obj.TryGetPropertyValue(parts[i], out current)) return false; if (i == parts.Length - 1) return true; } return false; } private static JsonNode NormalizePrintNodeValue(JsonNode? node) { if (node == null) return JsonValue.Create(string.Empty)!; if (node is JsonValue value) { if (value.TryGetValue(out var dt)) { return JsonValue.Create(dt.ToString("yyyy-MM-dd HH:mm:ss"))!; } if (value.TryGetValue(out var dto)) { return JsonValue.Create(dto.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"))!; } if (value.TryGetValue(out var text) && !string.IsNullOrWhiteSpace(text)) { if ((text.Contains('T') || text.EndsWith("Z", StringComparison.OrdinalIgnoreCase) || text.Contains('+')) && DateTimeOffset.TryParse(text, out var parsed)) { return JsonValue.Create(parsed.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"))!; } } } return node.DeepClone(); } private static void SetPath(JsonObject target, string path, JsonNode value) { var parts = path.Split('.', StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 0) return; JsonObject current = target; for (int i = 0; i < parts.Length - 1; i++) { if (current[parts[i]] is not JsonObject child) { child = new JsonObject(); current[parts[i]] = child; } current = child; } current[parts[^1]] = value; } public IReadOnlyList GetCachedSnapshot() { // 注意:不允许直接返回 _localCache 引用,避免外部修改污染缓存;用 Clone 做深拷贝。 lock (_cacheLock) { return _localCache.Select(Clone).ToList(); } } // ─── Remote ──────────────────────────────────────────────────────────────── private async Task> FetchRemoteListAsync(CancellationToken ct) { var query = HttpUtility.ParseQueryString(string.Empty); query["pageNo"] = "1"; query["pageSize"] = "10000"; query["tenantId"] = DefaultTenantId.ToString(); var url = $"{BaseUrl}/xslmes/mesXslRawMaterialEntry/anon/list?{query}"; using var client = CreateClient(); var resp = await client.GetAsync(url, ct).ConfigureAwait(false); resp.EnsureSuccessStatusCode(); var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false); using var doc = JsonDocument.Parse(json); var result = doc.RootElement.GetProperty("result"); return result.GetProperty("records").Deserialize>(_jsonOpts) ?? new(); } private async Task RemoteAddAsync(MesXslRawMaterialEntry entry, CancellationToken ct) { var url = $"{BaseUrl}/xslmes/mesXslRawMaterialEntry/anon/add?tenantId={DefaultTenantId}"; var payload = Clone(entry); if (IsLocalTempId(payload.Id)) payload.Id = null; return await PostJsonAsync(url, payload, ct).ConfigureAwait(false); } private async Task<(bool Ok, bool IsVersionConflict)> RemoteEditAsync(MesXslRawMaterialEntry entry, CancellationToken ct) { var url = $"{BaseUrl}/xslmes/mesXslRawMaterialEntry/anon/edit?tenantId={DefaultTenantId}"; return await PostJsonCheckVersionAsync(url, entry, ct).ConfigureAwait(false); } private async Task RemoteDeleteAsync(string id, CancellationToken ct) { var url = $"{BaseUrl}/xslmes/mesXslRawMaterialEntry/anon/delete?id={Uri.EscapeDataString(id)}&tenantId={DefaultTenantId}"; using var client = CreateClient(); var resp = await client.DeleteAsync(url, ct).ConfigureAwait(false); return resp.IsSuccessStatusCode && await IsSuccessResultAsync(resp, ct).ConfigureAwait(false); } private async Task PostJsonAsync(string url, object body, CancellationToken ct) { var content = new StringContent(JsonSerializer.Serialize(body, _jsonOpts), Encoding.UTF8, "application/json"); using var client = CreateClient(); var resp = await client.PostAsync(url, content, ct).ConfigureAwait(false); return resp.IsSuccessStatusCode && await IsSuccessResultAsync(resp, ct).ConfigureAwait(false); } private async Task<(bool Ok, bool IsVersionConflict)> PostJsonCheckVersionAsync(string url, object body, CancellationToken ct) { var content = new StringContent(JsonSerializer.Serialize(body, _jsonOpts), Encoding.UTF8, "application/json"); using var client = CreateClient(); var resp = await client.PostAsync(url, content, ct).ConfigureAwait(false); if (!resp.IsSuccessStatusCode) return (false, false); try { var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false); using var doc = JsonDocument.Parse(json); int code = 200; if (doc.RootElement.TryGetProperty("code", out var codeEl)) code = codeEl.GetInt32(); if (code == 200) return (true, false); if (doc.RootElement.TryGetProperty("message", out var msgEl)) if ((msgEl.GetString() ?? "").Contains("已被他人修改")) return (false, true); return (false, false); } catch { return (true, false); } } private static async Task IsSuccessResultAsync(HttpResponseMessage resp, CancellationToken ct) { try { var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false); using var doc = JsonDocument.Parse(json); if (doc.RootElement.TryGetProperty("code", out var code)) return code.GetInt32() == 200; if (doc.RootElement.TryGetProperty("success", out var success)) return success.GetBoolean(); return true; } catch { return true; } } // ─── Network / Reconnect ─────────────────────────────────────────────────── private void OnNetworkStatusChanged(bool isOnline) { if (!isOnline) return; _ = Task.Run(() => SyncAfterReconnectAsync(CancellationToken.None)); } private async Task SyncAfterReconnectAsync(CancellationToken cancellationToken) { var pushResult = await PushPendingOnReconnectAsync(cancellationToken).ConfigureAwait(false); if (!_networkMonitor.IsOnline) return; try { var remote = await FetchRemoteListAsync(cancellationToken).ConfigureAwait(false); lock (_cacheLock) { _localCache = remote.Select(Clone).ToList(); SaveCacheToDiskUnsafe(); } _eventAggregator.GetEvent().Publish(new RawMaterialEntryChangedPayload { Action = "pull" }); _logger.Information($"[原料入场重连] 全量回拉成功 count={remote.Count}"); } catch (Exception ex) { _logger.Warning($"[原料入场重连] 全量回拉失败:{ex.Message}"); } if (pushResult.PushedCount > 0 || pushResult.ConflictCount > 0 || pushResult.NewRecordsPushed > 0) { _eventAggregator.GetEvent().Publish(new SyncConflictPayload { EntityName = "原料入场", PushedCount = pushResult.PushedCount, ConflictCount = pushResult.ConflictCount, NewRecordsPushed = pushResult.NewRecordsPushed }); } } private sealed record PendingReplayResult(bool Ok, bool IsConflict, string? EntityId); private async Task PushPendingOnReconnectAsync(CancellationToken cancellationToken) { if (!await _syncLock.WaitAsync(0, cancellationToken).ConfigureAwait(false)) return new PushPendingResult(0, 0, 0); try { List snapshot; lock (_cacheLock) { snapshot = _pendingOps.OrderBy(x => x.CreatedAt).ToList(); } int pushed = 0, conflicts = 0, newPushed = 0; foreach (var op in snapshot) { if (!_networkMonitor.IsOnline) break; lock (_cacheLock) { if (!_pendingOps.Any(x => x.Id == op.Id)) continue; } var result = await ExecutePendingOperationAsync(op, cancellationToken).ConfigureAwait(false); if (!result.Ok) { lock (_cacheLock) { op.RetryCount++; if (op.RetryCount >= MaxPendingRetries) _pendingOps.RemoveAll(x => x.Id == op.Id); SavePendingOpsToDiskUnsafe(); } break; } if (result.IsConflict) { conflicts++; if (!string.IsNullOrWhiteSpace(result.EntityId)) RemovePendingOpsByEntryId(result.EntityId!); continue; } lock (_cacheLock) { if (op.OpType == EntryOpType.Add) newPushed++; else pushed++; _pendingOps.RemoveAll(x => x.Id == op.Id); SavePendingOpsToDiskUnsafe(); } } return new PushPendingResult(pushed, conflicts, newPushed); } finally { _syncLock.Release(); } } private async Task ExecutePendingOperationAsync(EntryPendingOperation op, CancellationToken ct) { try { switch (op.OpType) { case EntryOpType.Add: var ok = op.Entry != null && await RemoteAddAsync(op.Entry, ct).ConfigureAwait(false); return ok ? new PendingReplayResult(true, false, op.EntryId) : new PendingReplayResult(false, false, null); case EntryOpType.Edit: if (op.Entry == null || string.IsNullOrWhiteSpace(op.Entry.Id)) return new PendingReplayResult(false, false, null); var id = op.Entry.Id; var remote = await FetchRemoteSingleAsync(id, ct).ConfigureAwait(false); if (remote != null && op.AnchorUpdateTime != null && remote.UpdateTime != op.AnchorUpdateTime) { UpsertLocalCache(remote); return new PendingReplayResult(true, true, id); } var (editOk, isConflict) = await RemoteEditAsync(op.Entry, ct).ConfigureAwait(false); if (isConflict) { var fresh = await FetchRemoteSingleAsync(id, ct).ConfigureAwait(false); if (fresh != null) UpsertLocalCache(fresh); return new PendingReplayResult(true, true, id); } return editOk ? new PendingReplayResult(true, false, id) : new PendingReplayResult(false, false, null); case EntryOpType.Delete: if (string.IsNullOrWhiteSpace(op.EntryId)) return new PendingReplayResult(false, false, null); var delId = op.EntryId!; var delRemote = await FetchRemoteSingleAsync(delId, ct).ConfigureAwait(false); if (delRemote == null) return new PendingReplayResult(true, false, delId); if (op.AnchorUpdateTime != null && delRemote.UpdateTime != op.AnchorUpdateTime) { UpsertLocalCache(delRemote); return new PendingReplayResult(true, true, delId); } var delOk = await RemoteDeleteAsync(delId, ct).ConfigureAwait(false); return delOk ? new PendingReplayResult(true, false, delId) : new PendingReplayResult(false, false, null); default: return new PendingReplayResult(true, false, null); } } catch (Exception ex) { _logger.Warning($"[原料入场推送] 执行异常 op={op.OpType},entryId={op.EntryId}:{ex.Message}"); return new PendingReplayResult(false, false, null); } } private async Task FetchRemoteSingleAsync(string id, CancellationToken ct) { try { var url = $"{BaseUrl}/xslmes/mesXslRawMaterialEntry/anon/queryById?id={Uri.EscapeDataString(id)}&tenantId={DefaultTenantId}"; using var client = CreateClient(); var resp = await client.GetAsync(url, ct).ConfigureAwait(false); if (!resp.IsSuccessStatusCode) return null; var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false); using var doc = JsonDocument.Parse(json); if (doc.RootElement.TryGetProperty("result", out var resultEl)) return resultEl.Deserialize(_jsonOpts); return null; } catch { return null; } } // ─── Local cache helpers ─────────────────────────────────────────────────── private static List ApplyFilters( List source, string? barcode, string? batchNo, string? billNo, string? materialName, string? supplierName) { IEnumerable q = source; if (!string.IsNullOrWhiteSpace(barcode)) q = q.Where(e => (e.Barcode ?? "").Contains(barcode, StringComparison.OrdinalIgnoreCase)); if (!string.IsNullOrWhiteSpace(batchNo)) q = q.Where(e => (e.BatchNo ?? "").Contains(batchNo, StringComparison.OrdinalIgnoreCase)); if (!string.IsNullOrWhiteSpace(billNo)) q = q.Where(e => (e.BillNo ?? "").Contains(billNo, StringComparison.OrdinalIgnoreCase)); if (!string.IsNullOrWhiteSpace(materialName)) q = q.Where(e => (e.MaterialName ?? "").Contains(materialName, StringComparison.OrdinalIgnoreCase)); if (!string.IsNullOrWhiteSpace(supplierName)) q = q.Where(e => (e.SupplierName ?? "").Contains(supplierName, StringComparison.OrdinalIgnoreCase)); return q.OrderByDescending(e => e.EntryTime ?? e.CreateTime ?? DateTime.MinValue).ToList(); } private List ApplyPendingOpsSnapshotUnsafe(List source) { var map = source.Where(e => !string.IsNullOrWhiteSpace(e.Id)) .ToDictionary(e => e.Id!, Clone, StringComparer.OrdinalIgnoreCase); foreach (var op in _pendingOps.OrderBy(x => x.CreatedAt)) { switch (op.OpType) { case EntryOpType.Add: case EntryOpType.Edit: if (op.Entry != null && !string.IsNullOrWhiteSpace(op.Entry.Id)) map[op.Entry.Id] = Clone(op.Entry); break; case EntryOpType.Delete: if (!string.IsNullOrWhiteSpace(op.EntryId)) map.Remove(op.EntryId); break; } } return map.Values.ToList(); } private void EnqueuePendingOperation(EntryPendingOperation op) { lock (_cacheLock) { _pendingOps.Add(op); SavePendingOpsToDiskUnsafe(); } } private void UpsertLocalCache(MesXslRawMaterialEntry entry) { lock (_cacheLock) { var idx = _localCache.FindIndex(e => string.Equals(e.Id, entry.Id, StringComparison.OrdinalIgnoreCase)); if (idx >= 0) _localCache[idx] = Clone(entry); else _localCache.Insert(0, Clone(entry)); SaveCacheToDiskUnsafe(); } } private void RemoveFromLocalCache(string id) { lock (_cacheLock) { _localCache.RemoveAll(e => string.Equals(e.Id, id, StringComparison.OrdinalIgnoreCase)); SaveCacheToDiskUnsafe(); } } private void RemovePendingOpsByEntryId(string entryId) { lock (_cacheLock) { _pendingOps.RemoveAll(x => (!string.IsNullOrWhiteSpace(x.EntryId) && string.Equals(x.EntryId, entryId, StringComparison.OrdinalIgnoreCase)) || (x.Entry?.Id != null && string.Equals(x.Entry.Id, entryId, StringComparison.OrdinalIgnoreCase))); SavePendingOpsToDiskUnsafe(); } } private void LoadPendingOpsFromDisk() { try { if (!File.Exists(_pendingOpsFilePath)) return; var data = JsonSerializer.Deserialize>(File.ReadAllText(_pendingOpsFilePath), _jsonOpts); _pendingOps = data ?? new(); } catch { _pendingOps = new(); } } private void LoadCacheFromDisk() { try { if (!File.Exists(_cacheFilePath)) return; var data = JsonSerializer.Deserialize>(File.ReadAllText(_cacheFilePath), _jsonOpts); _localCache = data ?? new(); } catch { _localCache = new(); } } private void SavePendingOpsToDiskUnsafe() => File.WriteAllText(_pendingOpsFilePath, JsonSerializer.Serialize(_pendingOps, _jsonOpts)); private void SaveCacheToDiskUnsafe() => File.WriteAllText(_cacheFilePath, JsonSerializer.Serialize(_localCache, _jsonOpts)); private static MesXslRawMaterialEntry Clone(MesXslRawMaterialEntry e) => new() { Id = e.Id, Barcode = e.Barcode, BatchNo = e.BatchNo, EntryTime = e.EntryTime, WeightRecordId = e.WeightRecordId, BillNo = e.BillNo, MaterialId = e.MaterialId, MaterialName = e.MaterialName, SupplyCustomer = e.SupplyCustomer, SupplierId = e.SupplierId, SupplierName = e.SupplierName, ManufacturerMaterialName = e.ManufacturerMaterialName, ShelfLife = e.ShelfLife, TotalWeight = e.TotalWeight, TotalPortions = e.TotalPortions, PortionWeight = e.PortionWeight, PortionPackages = e.PortionPackages, PortionWarehouseLocations = e.PortionWarehouseLocations, PortionDetailIds = e.PortionDetailIds, PortionCardFlags = e.PortionCardFlags, TestResult = e.TestResult, TestStatus = e.TestStatus, PrintFlag = e.PrintFlag, StockBalance = e.StockBalance, WarehouseLocation = e.WarehouseLocation, UnloadOperator = e.UnloadOperator, IsSpecialAdoption = e.IsSpecialAdoption, SpecialAdoptionOperator = e.SpecialAdoptionOperator, SpecialAdoptionTime = e.SpecialAdoptionTime, SpecialAdoptionReason = e.SpecialAdoptionReason, Status = e.Status, Remark = e.Remark, CreateBy = e.CreateBy, CreateTime = e.CreateTime, UpdateBy = e.UpdateBy, UpdateTime = e.UpdateTime, TenantId = e.TenantId }; private static bool IsLocalTempId(string? id) => !string.IsNullOrWhiteSpace(id) && id.StartsWith("local-", StringComparison.OrdinalIgnoreCase); private sealed class EntryPendingOperation { public string Id { get; set; } = Guid.NewGuid().ToString("N"); public EntryOpType OpType { get; set; } public string? EntryId { get; set; } public MesXslRawMaterialEntry? Entry { get; set; } public DateTime? AnchorUpdateTime { get; set; } public DateTime CreatedAt { get; set; } = DateTime.UtcNow; public int RetryCount { get; set; } = 0; } private enum EntryOpType { Add = 1, Edit = 2, Delete = 3 } private sealed class NullableDateTimeJsonConverter : JsonConverter { private static readonly string[] SupportedFormats = [ "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss.fff", "yyyy-MM-ddTHH:mm:ss", "yyyy-MM-ddTHH:mm:ss.fff", "yyyy-MM-ddTHH:mm:ssZ", "yyyy-MM-ddTHH:mm:ss.fffZ" ]; public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) return null; if (reader.TokenType == JsonTokenType.String) { var raw = reader.GetString(); if (string.IsNullOrWhiteSpace(raw)) return null; if (DateTime.TryParseExact(raw, SupportedFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeLocal, out var exact)) return exact; if (DateTime.TryParse(raw, out var fallback)) return fallback; } throw new JsonException($"无法将 JSON 值转换为 DateTime?,token={reader.TokenType}"); } public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options) { if (value.HasValue) writer.WriteStringValue(value.Value.ToString("yyyy-MM-dd HH:mm:ss")); else writer.WriteNullValue(); } } }