wanshenmean
10 小时以前 1330eff40e79aecc1722402786b4aa52cc1b574f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
using Mapster;
using MapsterMapper;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using System.DirectoryServices.Protocols;
using System.Text.Json;
using WIDESEA_Common.Constants;
using WIDESEA_Common.LocationEnum;
using WIDESEA_Common.StockEnum;
using WIDESEA_Common.TaskEnum;
using WIDESEA_Common.WareHouseEnum;
using WIDESEA_Core;
using WIDESEA_Core.BaseRepository;
using WIDESEA_Core.BaseServices;
using WIDESEA_Core.Core;
using WIDESEA_Core.Enums;
using WIDESEA_Core.Helper;
using WIDESEA_DTO.GradingMachine;
using WIDESEA_DTO.MES;
using WIDESEA_DTO.Stock;
using WIDESEA_DTO.Task;
using Newtonsoft.Json;
using System.Diagnostics;
using WIDESEA_IBasicService;
using WIDESEA_IRecordService;
using WIDESEA_IStockService;
using WIDESEA_ITaskInfoService;
using WIDESEA_Model.Models;
 
namespace WIDESEA_TaskInfoService
{
    public partial class TaskService : ServiceBase<Dt_Task, IRepository<Dt_Task>>, ITaskService
    {
        private readonly IMapper _mapper;
        private readonly IStockInfoService _stockInfoService;
        private readonly ILocationInfoService _locationInfoService;
        private readonly HttpClientHelper _httpClientHelper;
        private readonly IConfiguration _configuration;
        private readonly RoundRobinService _roundRobinService;
        private readonly IMesService _mesService;
        private readonly ITask_HtyService _task_HtyService;
        private readonly IStockInfo_HtyService _stockInfo_HtyService;
        private readonly IUnitOfWorkManage _unitOfWorkManage;
        private readonly IRecordService _recordService;
        private readonly IMESDeviceConfigService _mesDeviceConfigService;
        private readonly IMesLogService _mesLogService;
 
        public IRepository<Dt_Task> Repository => BaseDal;
 
        private readonly Dictionary<string, OrderByType> _taskOrderBy = new()
        {
            { nameof(Dt_Task.Grade), OrderByType.Desc },
            { nameof(Dt_Task.CreateDate), OrderByType.Asc },
        };
 
        public List<int> TaskTypes => typeof(TaskTypeEnum).GetEnumIndexList();
        public List<int> TaskOutboundTypes => typeof(TaskTypeEnum).GetEnumIndexList();
 
        public TaskService(
            IRepository<Dt_Task> BaseDal,
            IMapper mapper,
            IStockInfoService stockInfoService,
            ILocationInfoService locationInfoService,
            HttpClientHelper httpClientHelper,
            IConfiguration configuration,
            RoundRobinService roundRobinService,
            IMesService mesService,
            ITask_HtyService task_HtyService,
            IStockInfo_HtyService stockInfo_HtyService,
            IUnitOfWorkManage unitOfWorkManage,
            IRecordService recordService,
            IMESDeviceConfigService mesDeviceConfigService,
            IMesLogService mesLogService) : base(BaseDal)
        {
            _mapper = mapper;
            _stockInfoService = stockInfoService;
            _locationInfoService = locationInfoService;
            _httpClientHelper = httpClientHelper;
            _configuration = configuration;
            _roundRobinService = roundRobinService;
            _mesService = mesService;
            _task_HtyService = task_HtyService;
            _stockInfo_HtyService = stockInfo_HtyService;
            _unitOfWorkManage = unitOfWorkManage;
            _recordService = recordService;
            _mesDeviceConfigService = mesDeviceConfigService;
            _mesLogService = mesLogService;
        }
 
        /// <summary>
        /// 查找托盘是否存在未完成任务。
        /// </summary>
        private async Task<WebResponseContent> GetTaskByPalletCodeAsync(string palletCode)
        {
            try
            {
                var task = await BaseDal.QueryFirstAsync(s => s.PalletCode == palletCode);
                if (task == null)
                    return WebResponseContent.Instance.Error("未找到对应的任务");
 
                var taskDto = _mapper.Map<WMSTaskDTO>(task);
                return WebResponseContent.Instance.OK("查询成功", taskDto);
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error($"查询任务失败: {ex.Message}");
            }
        }
 
        /// <summary>
        /// 保存任务历史。
        /// </summary>
        private async Task<WebResponseContent> SaveTaskHistoryAsync(Dt_Task task, string operateType)
        {
            var historyTask = _mapper.Map<Dt_Task_Hty>(task);
            historyTask.InsertTime = DateTime.Now;
            historyTask.OperateType = operateType;
 
            var saved = await _task_HtyService.Repository.AddDataAsync(historyTask) > 0;
            return saved
                ? WebResponseContent.Instance.OK()
                : WebResponseContent.Instance.Error("任务历史保存失败");
        }
 
        /// <summary>
        /// 保存库存历史。
        /// </summary>
        private async Task<WebResponseContent> SaveStockHistoryAsync(Dt_StockInfo stockInfo, string operateType)
        {
            var historyStock = _mapper.Map<Dt_StockInfo_Hty>(stockInfo);
            historyStock.InsertTime = DateTime.Now;
            historyStock.OperateType = operateType;
 
            var saved = await _stockInfo_HtyService.Repository.AddDataAsync(historyStock) > 0;
            return saved
                ? WebResponseContent.Instance.OK()
                : WebResponseContent.Instance.Error("库存历史保存失败");
        }
 
        /// <summary>
        /// 完成任务后统一处理。
        /// </summary>
        private async Task<WebResponseContent> CompleteTaskAsync(Dt_Task task, string operateType = "")
        {
            var deleteTaskResult = await BaseDal.DeleteDataAsync(task);
            if (!deleteTaskResult)
                return WebResponseContent.Instance.Error("任务完成失败");
 
            return await SaveTaskHistoryAsync(task, operateType);
        }
 
        /// <summary>
        /// 根据巷道确定目标地址,支持多出库口轮询。
        /// </summary>
        private string DetermineTargetAddress(string roadway, Dictionary<string, List<string>> addressMap)
        {
            if (string.IsNullOrWhiteSpace(roadway))
                return TaskAddressConstants.DEFAULT_ADDRESS;
 
            string? matchedPrefix = null;
            foreach (var kvp in addressMap)
            {
                if (roadway.Contains(kvp.Key))
                {
                    matchedPrefix = kvp.Key;
                    break;
                }
            }
 
            if (matchedPrefix == null)
                return TaskAddressConstants.DEFAULT_ADDRESS;
 
            if (!addressMap.TryGetValue(matchedPrefix, out var addresses) || addresses == null || addresses.Count == 0)
                return TaskAddressConstants.DEFAULT_ADDRESS;
 
            if (addresses.Count == 1)
                return addresses[0];
 
            return _roundRobinService.GetNextAddress(matchedPrefix, addresses);
        }
 
        /// <summary>
        /// 根据库存 Remark 确定目标地址(GW_1→[11001,11010]轮询,GW_2→CWSC1,CW_1→22001)。
        /// </summary>
        private string DetermineTargetAddressByRemark(string remark, string roadway, Dictionary<string, List<string>> addressMap)
        {
            // 根据 Remark 确定目标地址
            if (!string.IsNullOrWhiteSpace(remark))
            {
                return remark switch
                {
                    StockRemarkConstants.GW1 => _roundRobinService.GetNextAddress(StockRemarkConstants.GW1, TaskAddressConstants.GW1_ADDRESSES.ToList()),
                    StockRemarkConstants.GW2 => TaskAddressConstants.GW2_ADDRESS,
                    StockRemarkConstants.CW1 => TaskAddressConstants.CW1_ADDRESS,
                    _ => DetermineTargetAddress(roadway, addressMap)
                };
            }
 
            // Remark 为空时,回退到巷道配置
            return DetermineTargetAddress(roadway, addressMap);
        }
 
        /// <summary>
        /// 异步执行MES上传 - 不阻塞主业务逻辑
        /// </summary>
        /// <param name="palletCode">托盘号</param>
        /// <param name="successStatus">成功时的状态枚举值(奇数)</param>
        /// <param name="uploadFunc">具体的MES调用函数</param>
        private async Task MesUploadAsync(string palletCode, MesUploadStatusEnum successStatus, Func<Task<HttpResponseResult<MesResponse>>> uploadFunc)
        {
            var stopwatch = Stopwatch.StartNew();
            string requestJson = "";
            string responseJson = "";
            bool isSuccess = false;
            string errorMessage = "";
 
            try
            {
                // 调用MES
                var result = await uploadFunc();
 
                stopwatch.Stop();
                isSuccess = result?.Data?.IsSuccess ?? false;
                errorMessage = result?.Data?.Msg ?? result?.ErrorMessage ?? "未知错误";
                responseJson = JsonConvert.SerializeObject(result);
 
                // 根据成功/失败决定状态值:奇数=成功,偶数=失败
                var uploadStatus = isSuccess ? (int)successStatus : (int)successStatus + 1;
 
                // 更新库存表状态(不等待)
                _ = _stockInfoService.UpdateMesUploadStatusAsync(palletCode, uploadStatus);
 
                // 记录MES日志
                await LogMesCallAsync(palletCode, successStatus.ToString(), requestJson, responseJson,
                    stopwatch.ElapsedMilliseconds, isSuccess ? "成功" : "失败", errorMessage);
            }
            catch (Exception ex)
            {
                stopwatch.Stop();
                errorMessage = ex.Message;
 
                // 更新状态为失败(successStatus+1 即为失败状态)
                var uploadStatus = (int)successStatus + 1;
                _ = _stockInfoService.UpdateMesUploadStatusAsync(palletCode, uploadStatus);
 
                // 记录异常日志
                await LogMesCallAsync(palletCode, successStatus.ToString(), requestJson, responseJson,
                    stopwatch.ElapsedMilliseconds, "失败", errorMessage);
            }
        }
 
        /// <summary>
        /// 记录MES接口调用日志
        /// </summary>
        private async Task LogMesCallAsync(string palletCode, string apiType, string requestJson,
            string responseJson, long durationMs, string status, string errorMessage)
        {
            try
            {
                var mesLog = new MesApiLogDto
                {
                    PalletCode = palletCode,
                    ApiType = apiType,
                    RequestJson = requestJson,
                    ResponseJson = responseJson,
                    IsSuccess = status == "成功",
                    ErrorMessage = errorMessage,
                    ElapsedMs = (int)durationMs,
                    Creator = "System"
                };
                await _mesLogService.LogAsync(mesLog);
            }
            catch
            {
                // 日志记录失败不影响主流程
            }
        }
    }
}