wanshenmean
8 小时以前 ba9c1994b95624b88ef606ec00394990d8f2009f
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
#region << 版 本 注 释 >>
 
/*----------------------------------------------------------------
 * 命名空间:WIDESEAWCS_TaskInfoService
 * 创建者:胡童庆
 * 创建时间:2024/8/2 16:13:36
 * 版本:V1.0.0
 * 描述:
 *
 * ----------------------------------------------------------------
 * 修改人:
 * 修改时间:
 * 版本:V1.0.1
 * 修改说明:
 *
 *----------------------------------------------------------------*/
 
#endregion << 版 本 注 释 >>
 
using MapsterMapper;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using SqlSugar;
using System.Diagnostics.CodeAnalysis;
using WIDESEA_Core;
using WIDESEAWCS_Common.HttpEnum;
using WIDESEAWCS_Common.TaskEnum;
using WIDESEAWCS_Core;
using WIDESEAWCS_Core.BaseServices;
using WIDESEAWCS_Core.Helper;
using WIDESEAWCS_DTO.Stock;
using WIDESEAWCS_DTO.TaskInfo;
using WIDESEAWCS_ITaskInfoRepository;
using WIDESEAWCS_ITaskInfoService;
using WIDESEAWCS_Model.Models;
using WIDESEAWCS_QuartzJob;
using WIDESEAWCS_QuartzJob.DTO;
 
namespace WIDESEAWCS_TaskInfoService
{
    public class RobotTaskService : ServiceBase<Dt_RobotTask, IRobotTaskRepository>, IRobotTaskService
    {
        private readonly IMapper _mapper;
        private readonly HttpClientHelper _httpClientHelper;
        private readonly ITaskExecuteDetailService _taskExecuteDetailService;
 
        private Dictionary<string, OrderByType> _taskOrderBy = new()
            {
                {nameof(Dt_RobotTask.RobotGrade),OrderByType.Desc },
                {nameof(Dt_RobotTask.CreateDate),OrderByType.Asc},
            };
 
        public Dictionary<string, OrderByType> TaskOrderBy
        { get { return _taskOrderBy; } set { _taskOrderBy = value; } }
 
        public List<int> TaskInboundTypes => typeof(TaskInboundTypeEnum).GetEnumIndexList();
 
        public List<int> TaskOutboundTypes => typeof(TaskOutboundTypeEnum).GetEnumIndexList();
 
        public List<int> TaskRobotTypes => typeof(TaskOtherTypeEnum).GetEnumIndexList();
 
        public RobotTaskService(IRobotTaskRepository BaseDal, IMapper mapper, HttpClientHelper httpClientHelper, ITaskExecuteDetailService taskExecuteDetailService) : base(BaseDal)
        {
            _mapper = mapper;
            _httpClientHelper = httpClientHelper;
            _taskExecuteDetailService = taskExecuteDetailService;
        }
 
        public WebResponseContent ReceiveWMSTask([NotNull] WMSTaskDTO taskDTO, StockDTO stockDTO)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                if (BaseDal.QueryFirst(x => x.RobotTaskNum == taskDTO.TaskNum || x.RobotSourceAddressPalletCode == taskDTO.PalletCode) != null)
                {
                    return content.Error("任务已存在");
                }
 
                Dt_RobotTask task = new Dt_RobotTask
                {
                    RobotTaskNum = taskDTO.TaskNum,
                    RobotSourceAddressLineCode = stockDTO.SourceLineNo,
                    RobotTargetAddressLineCode = stockDTO.TargetLineNo,
                    RobotRoadway = stockDTO.Roadway,
                    RobotSourceAddress = taskDTO.SourceAddress,
                    RobotTargetAddress = taskDTO.TargetAddress,
                    RobotSourceAddressPalletCode = stockDTO.SourcePalletNo,
                    RobotTargetAddressPalletCode = stockDTO.TargetPalletNo,
                    RobotTaskType = taskDTO.TaskType,
                    RobotTaskState = taskDTO.TaskStatus,
                    RobotGrade = taskDTO.Grade,
                    Creater = "WMS",
                    RobotTaskTotalNum = 48,
                };
 
                BaseDal.AddData(task);
 
                _taskExecuteDetailService.AddTaskExecuteDetail(new List<int> { task.RobotTaskNum }, "接收WMS任务");
 
                content = WebResponseContent.Instance.OK("成功", task);
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error($"任务接收错误,错误信息:{ex.Message}");
            }
            return content;
        }
 
        public Dt_RobotTask? QueryRobotCraneTask(string deviceCode)
        {
            return BaseDal.QueryFirst(x => x.RobotRoadway == deviceCode && x.RobotTaskState != (int)TaskRobotStatusEnum.RobotExecuting, TaskOrderBy);
        }
 
        public Dt_RobotTask? QueryRobotCraneExecutingTask(string deviceCode)
        {
            return BaseDal.QueryFirst(x => x.RobotRoadway == deviceCode && x.RobotTaskState == (int)TaskRobotStatusEnum.RobotExecuting, TaskOrderBy);
        }
 
        public async Task<bool> UpdateRobotTaskAsync(Dt_RobotTask robotTask)
        {
            return await BaseDal.UpdateDataAsync(robotTask);
        }
 
        /// <summary>
        /// 获取WMS系统机械手任务
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        public WebResponseContent GetWMSRobotTask(Dt_Task task)
        {
            string configKey = ResolveRobotTaskConfigKey(task.TargetAddress);
            StockDTO stock = BuildRobotTaskStock(task, configKey);
 
            var result = _httpClientHelper.Post<WebResponseContent>(configKey, stock.ToJson());
 
            if (!result.IsSuccess || !result.Data.Status)
                return WebResponseContent.Instance.Error($"获取WMS系统机械手任务失败,任务号:【{task.TaskNum}】,托盘号:【{task.PalletCode}】,目标地址:【{task.TargetAddress}】,接口:【{configKey}】,错误信息:【{result.Data?.Message}】");
 
            var wMSTask = JsonConvert.DeserializeObject<WMSTaskDTO>(result.Data.Data?.ToString() ?? string.Empty);
            if (wMSTask == null)
                return WebResponseContent.Instance.Error($"获取WMS系统机械手任务失败,任务号:【{task.TaskNum}】,托盘号:【{task.PalletCode}】,错误信息:【WMS未返回有效任务数据】");
 
            return ReceiveWMSTask(wMSTask, stock);
        }
 
        /// <summary>
        /// 根据输送线目标地址解析机械手任务接口。
        /// 规则:
        /// 1. 从配置读取精确地址映射(AddressMap)
        /// 2. 未命中时默认换盘
        /// </summary>
        public string ResolveRobotTaskConfigKey(string? targetAddress)
        {
            string address = (targetAddress ?? string.Empty).Trim();
            if (string.IsNullOrWhiteSpace(address))
                return nameof(ConfigKey.CreateRobotChangePalletTask);
 
            var section = App.Configuration.GetSection("RobotTaskAddressRules");
            var addressMap = ReadRobotRuleMap(section.GetSection("AddressMap"));
            if (addressMap.TryGetValue(address, out string? exactTaskType))
                return MapRobotTaskTypeToConfigKey(exactTaskType);
 
            return nameof(ConfigKey.CreateRobotChangePalletTask);
        }
 
        public int MapWarehouseIdConfigKey(string? targetAddress)
        {
            return targetAddress switch
            {
                "11068" => 1,
                "11001" => 3,
                "11010" => 3,
                "10010" => 1,
                "10030" => 1,
                _ => 1
            };
        }
 
        /// <summary>
        /// 将配置任务类型转换为接口配置键。
        /// 支持值:Split/Group/Change(大小写不敏感)
        /// </summary>
        public string MapRobotTaskTypeToConfigKey(string? taskType)
        {
            string type = (taskType ?? string.Empty).Trim().ToLowerInvariant();
            return type switch
            {
                "split" => nameof(ConfigKey.CreateRobotSplitPalletTask),
                "group" => nameof(ConfigKey.CreateRobotGroupPalletTask),
                _ => nameof(ConfigKey.CreateRobotChangePalletTask)
            };
        }
 
        /// <summary>
        /// 根据接口类型构建机械手任务入参。
        /// </summary>
        public StockDTO BuildRobotTaskStock(Dt_Task task, string configKey)
        {
            string targetAddress = task.TargetAddress ?? string.Empty;
            string roadway = ResolveRobotRuleValue(targetAddress, "AddressRoadwayMap", task.Roadway);
            string sourceLineNo = ResolveRobotRuleValue(targetAddress, "AddressSourceLineNoMap", task.SourceAddress);
 
            var stock = new StockDTO
            {
                Roadway = roadway,
                SourceLineNo = sourceLineNo,
                TargetLineNo = task.TargetAddress,
                SourcePalletNo = task.PalletCode,
                TargetPalletNo = task.PalletCode
            };
 
            if (configKey == nameof(ConfigKey.CreateRobotSplitPalletTask))
            {
                stock.TargetPalletNo = string.Empty;
            }
            else if (configKey == nameof(ConfigKey.CreateRobotGroupPalletTask))
            {
                stock.SourcePalletNo = string.Empty;
            }
            else if (configKey == nameof(ConfigKey.CreateRobotChangePalletTask))
            {
                IDevice? device = Storage.Devices.FirstOrDefault(x => x.DeviceProDTOs.Any(d => d.DeviceChildCode == sourceLineNo));
                if (device != null)
                {
                    CommonConveyorLine conveyorLine = (CommonConveyorLine)device;
 
                    DeviceProDTO? devicePro = conveyorLine.DeviceProDTOs.FirstOrDefault(x => x.DeviceProParamName == nameof(ConveyorLineDBNameNew.Barcode) && x.DeviceChildCode == sourceLineNo);
                    //ConveyorLineTaskCommandNew command = conveyorLine.ReadCustomer<ConveyorLineTaskCommandNew>(sourceLineNo);  // 测试用
                    var barcode = conveyorLine.GetValue<ConveyorLineDBNameNew, string>(ConveyorLineDBNameNew.Barcode, sourceLineNo);
                    stock.SourcePalletNo = string.IsNullOrEmpty(barcode) ? string.Empty : barcode;
                }
            }
 
            return stock;
        }
 
        /// <summary>
        /// 根据目标地址按「精确 > 回退值」解析规则值。
        /// </summary>
        public string ResolveRobotRuleValue(string? targetAddress, string addressSectionName, string? fallback)
        {
            string address = (targetAddress ?? string.Empty).Trim();
            string defaultValue = fallback ?? string.Empty;
            if (string.IsNullOrWhiteSpace(address))
                return defaultValue;
 
            var section = App.Configuration.GetSection("RobotTaskAddressRules");
            var addressMap = ReadRobotRuleMap(section.GetSection(addressSectionName));
            if (addressMap.TryGetValue(address, out string? value))
                return value;
 
            return defaultValue;
        }
 
        /// <summary>
        /// 读取规则映射段。
        /// </summary>
        private Dictionary<string, string> ReadRobotRuleMap(IConfigurationSection section)
        {
            return section
                .GetChildren()
                .Where(x => !string.IsNullOrWhiteSpace(x.Key) && !string.IsNullOrWhiteSpace(x.Value))
                .ToDictionary(x => x.Key.Trim(), x => x.Value!.Trim());
        }
    }
}