刘磊
2025-11-17 efbeb93b3d454f06d65dbcc68ad828cc95bc9404
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
using AngleSharp.Dom;
using Mapster;
using Masuit.Tools.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml.ConditionalFormatting;
using System.Threading.Tasks;
using WIDESEA_Common;
using WIDESEA_Core;
using WIDESEA_Core.HttpContextUser;
using WIDESEA_DTO;
using WIDESEA_Model.Models;
 
namespace WIDESEA_StorageBasicService;
 
public class LocationInfoService : ServiceBase<DtLocationInfo, ILocationInfoRepository>, ILocationInfoService
{
    private readonly LogFactory LogFactory = new LogFactory();
    private readonly IUnitOfWorkManage _unitOfWorkManage;
    private readonly IDt_TaskRepository _taskRepository;
    private readonly IDt_TaskService _taskService;
    private readonly IStockInfoRepository _stockInfoRepository;
    private readonly IStockInfoDetailRepository _stockInfoDetailRepository;
    private readonly IDt_WareAreaInfoRepository _wareAreaInfoRepository;
    private readonly ITaskExecuteDetailRepository _taskExecuteDetailRepository;
    private readonly ILocationStatusChangeRecordRepository _locationStatusChangeRecordRepository;
    private readonly IMapper _mapper;
    private readonly IDt_PalletStockInfoRepository _palletStockInfoRepository;
 
    public LocationInfoService(ILocationInfoRepository BaseDal,
                                    IUnitOfWorkManage unitOfWorkManage,
                                    IDt_TaskRepository taskRepository,
                                    IStockInfoRepository stockInfoRepository,
                                    IDt_WareAreaInfoRepository wareAreaInfoRepository,
                                    ITaskExecuteDetailRepository taskExecuteDetailRepository,
                                    ILocationStatusChangeRecordRepository locationStatusChangeRecordRepository,
                                    IStockInfoDetailRepository stockInfoDetailRepository,
                                    IMapper mapper,
                                    IDt_TaskService taskService,
                                    IDt_PalletStockInfoRepository palletStockInfoRepository) : base(BaseDal)
    {
        _unitOfWorkManage = unitOfWorkManage;
        _taskRepository = taskRepository;
        _stockInfoRepository = stockInfoRepository;
        _wareAreaInfoRepository = wareAreaInfoRepository;
        _taskExecuteDetailRepository = taskExecuteDetailRepository;
        _locationStatusChangeRecordRepository = locationStatusChangeRecordRepository;
        _stockInfoDetailRepository = stockInfoDetailRepository;
        _mapper = mapper;
        _taskService = taskService;
        _palletStockInfoRepository = palletStockInfoRepository;
    }
 
 
    public override WebResponseContent UpdateData(SaveModel saveModel)
    {
        int id = saveModel.MainData["id"].ObjToInt();
        int status = saveModel.MainData["locationStatus"].ObjToInt();
        var location = BaseDal.QueryFirst(x => x.Id == id);
 
        LocationChangeRecordDto changeRecordDto = new LocationChangeRecordDto()
        {
            AfterStatus = status,
            BeforeStatus = location.LocationStatus,
            TaskNum = 0,
            LocationId = id,
            LocationCode = location.LocationCode,
            ChangeType = (int)StatusChangeTypeEnum.ManualOperation
        };
 
        _locationStatusChangeRecordRepository.AddStatusChangeRecord(changeRecordDto);
 
        return base.UpdateData(saveModel);
    }
 
    public override WebResponseContent AddData(SaveModel saveModel)
    {
        WebResponseContent content = new();
        try
        {
            int line = saveModel.MainData["row"].ObjToInt();
            int column = saveModel.MainData["column"].ObjToInt();
            int layer = saveModel.MainData["layer"].ObjToInt();
            int locationType = saveModel.MainData["locationType"].ObjToInt();
            //int status = saveModel.MainData["locationStatus"].ObjToInt();
            //string roadwayNo = saveModel.MainData["roadwayNo"].ToString();
 
            string locationCode = line.ToString().PadLeft(3, '0') + '-' + column.ToString().PadLeft(3, '0') + '-' + layer.ToString().PadLeft(3, '0');
            var location = BaseDal.QueryFirst(x => x.LocationCode == locationCode);
            if (location != null) throw new Exception($"{locationCode}库位已存在,请核查");
 
            DtLocationInfo locationInfo = new DtLocationInfo
            {
                Row = line,
                Column = column,
                Layer = layer,
                LocationCode = line.ToString().PadLeft(3, '0') + '-' + column.ToString().PadLeft(3, '0') + '-' + layer.ToString().PadLeft(3, '0'),
                LocationName = ConvertToFormattedString(line, column, layer),
                LocationType = locationType,
                Remark = "",
                Depth = 0,
                RoadwayNo = locationType == 1 ? "CTU" : "AGV",
                LocationStatus = LocationEnum.Free.ObjToInt(),
                AreaId = 0,
                Creater = App.User.UserName,
                EnalbeStatus = 2,  //默认禁用
                CreateDate = DateTime.Now,
            };
 
            if (BaseDal.AddData(locationInfo) > 0)
            {
                return content.OK("添加成功!");
            }
            else
            {
                return content.Error("添加失败");
            }
        }
        catch (Exception ex)
        {
            return content.Error($"添加失败:{ex.Message}");
        }
 
    }
 
    #region 初始化库位
    public async Task<WebResponseContent> initializeLocation(int locationID)
    {
        WebResponseContent content = new WebResponseContent();
        try
        {
            DtLocationInfo? location = BaseDal.QueryData(x => x.Id == locationID).FirstOrDefault();
            int LastStatus = location.LocationStatus;
            if (location == null)
            {
                return content.Error("未找到货位信息!");
            }
            DtStockInfo stock = _stockInfoRepository.QueryFirst(x => x.LocationId == location.Id);
            if (stock == null)
            {
                location.LocationStatus = (int)LocationEnum.Lock;
                BaseDal.UpdateData(location);
            }
            else
            {
                _unitOfWorkManage.BeginTran();
                DtStockInfo_Hty stockInfo_Hty = stock.Adapt<DtStockInfo_Hty>();
                stockInfo_Hty.ModifyDate = DateTime.Now;
                await DeleteStockInfoAsync(stock.Id);
                List<DtStockInfoDetail> detail = _stockInfoDetailRepository.QueryData(x => x.StockId == stock.Id).ToList();
                if (detail is not null && detail.Count() > 0)
                {
                    List<DtStockInfoDetail_Hty> details = detail.Adapt<List<DtStockInfoDetail_Hty>>();
                    await DeleteStockInfoDetailsAsync(detail);
                    AddStockInfoDetailHty(details);
                }
                await AddStockInfoHtyAsync(stockInfo_Hty);
 
 
                location.LocationStatus = (int)LocationEnum.Lock;
                BaseDal.UpdateData(location);
 
                _locationStatusChangeRecordRepository.AddLocationStatusChangeRecord(location, LastStatus, (int)StatusChangeTypeEnum.ManualOperation, 0);
                _unitOfWorkManage.CommitTran();
            }
            return content.OK();
        }
        catch (Exception ex)
        {
            _unitOfWorkManage.RollbackTran();
            return content.Error(ex.Message);
        }
    }
    #endregion
 
    #region 创建原始货位数据
 
    /// <summary>
    /// 创建原始货位数据
    /// </summary>
    /// <param name="x">行</param>
    /// <param name="y">列</param>
    /// <param name="z">层</param>
    /// <param name="locType">货位类型(1、单深,2、双深)</param>
    /// <param name="areaId">库区编码</param>
    /// <returns></returns>
    public WebResponseContent CreateLocation(int x, int y, int z, int locType, int areaId)
    {
        //string[] chineseNumbers = new string[] { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
        var locationList = new List<DtLocationInfo>();
        for (int line = 1; line <= x; line++)
        {
            for (int column = 1; column <= y; column++)
            {
                for (int layer = 1; layer <= z; layer++)
                {
                    locationList.Add(new DtLocationInfo()
                    {
                        Row = line,
                        Column = column,
                        Layer = layer,
                        LocationCode = line.ToString().PadLeft(3, '0') + '-' + column.ToString().PadLeft(3, '0') + '-' + layer.ToString().PadLeft(3, '0'),
                        LocationName = ConvertToFormattedString(line, column, layer),
                        LocationType = 2,
                        Remark = "",
                        Depth = 1,//locType > 1 ? (((line - 1) % 4) + 1) == 2 || (((line - 1) % 4) + 1) == 3 ? 1 : 2 : 1,
                        RoadwayNo = locType > 1 ? $"SC{((line - 1) / 4) + 1}" : $"SC{((line - 1) / 2) + 1}",
                        LocationStatus = LocationEnum.Free.ObjToInt(),
                        AreaId = areaId,
                        Creater = "systeam",
                        EnalbeStatus = 2,
                    });
                }
            }
        } 
        var isResult = BaseDal.AddData(locationList) > 0;
        if (isResult)
            return new WebResponseContent().OK();
        else
            return new WebResponseContent().Error();
    }
 
    #endregion 创建原始货位数据
 
    #region 启用禁用货位
 
    public WebResponseContent LocationEnable(SaveModel saveModel)
    {
        WebResponseContent content = new WebResponseContent();
        try
        {
            List<DtLocationInfo> locations = new List<DtLocationInfo>();
            int enable = Convert.ToBoolean(saveModel.Extra) ? 1 : 2;
            for (int i = 0; i < saveModel.DelKeys.Count; i++)
            {
                DtLocationInfo location = BaseDal.QueryData(x => x.Id == int.Parse(saveModel.DelKeys[i].ToString())).FirstOrDefault();
                location.EnalbeStatus = enable;
                locations.Add(location);
            }
            BaseDal.UpdateData(locations);
            content = WebResponseContent.Instance.OK();
        }
        catch (Exception ex)
        {
            content = WebResponseContent.Instance.Error(ex.Message);
        }
        finally
        {
            //日志记录
        }
        return content;
    }
 
    #endregion 启用禁用货位
 
    #region 获取货位状态(库位平面图)
    /// <summary>
    /// 获取货位状态
    /// </summary>
    /// <param name="area"></param>
    /// <returns></returns>
    public object GetLocationStatu([FromBody] Area area)
    {
        var data = BaseDal.QueryData(x => x.AreaId == Convert.ToInt32(area.areaCode));
 
        List<LocationLayer> layers = new List<LocationLayer>();
        foreach (var layer in data.GroupBy(t => t.Column))
        {
            var rows = new List<LocationRow>();
            var data_rows = layer.GroupBy(t => t.Row);
            foreach (var data_row in data_rows)
            {
                var cols = new List<LocationCol>();
                foreach (var data_col in data_row)
                {
                    cols.Add(new LocationCol()
                    {
                        //列
                        index = data_col.Layer,
                        locationCode = data_col.LocationCode,
                        location_state = data_col.LocationStatus.ToString(),
                        location_lock = data_col.EnalbeStatus.ToString(),
                    });
                }
                cols = cols.OrderBy(t => t.index).ToList();
                rows.Add(new LocationRow()
                {
                    //行
                    index = data_row.Key,
                    cols = cols
                });
            }
            rows = rows.OrderBy(t => t.index).ToList();
            layers.Add(new LocationLayer()
            {
                //层
                index = layer.Key,
                //locationCode = layer.LocationCode,
                rows = rows
            });
        }
        layers = layers.OrderBy(t => t.index).ToList();
        return layers;
    }
    #endregion
 
 
    #region 内部方法
 
 
 
    #region 移库方法
 
    /// <summary>
    /// 计算相对的库位ID
    /// </summary>
    /// <param name="locationID">当前库位ID</param>
    /// <returns>相对的库位ID</returns>
    private string GetRelativeLocationID(DtLocationInfo locationInfo)
    {
        int line = locationInfo.Row;
 
        // 计算相对的货位行值,奇数行的下一行或者偶数行的上一行
        int relativeLine = line % 2 == 1 ? line + 1 : line - 1;
        LogFactory.GetLog("检查是否需要移库").InfoFormat(true, "需要移库,计算相对行", $"原始货位行:{line},计算相对货位行:{relativeLine}");
 
        // 构建新的库位ID
        string[] newLocationParts = new string[] { relativeLine.ToString().PadLeft(3, '0'), locationInfo.Column.ToString().PadLeft(3, '0'), locationInfo.Layer.ToString().PadLeft(3, '0') };
        return string.Join("-", newLocationParts);
    }
 
 
 
    /// <summary>
    /// 根据货位是否需要移库
    /// </summary>
    /// <param name="locationID">货位ID</param>
    /// <returns>是否需要移库</returns>
    private bool CheckForInternalTransfer(DtLocationInfo location)
    {
        return location.Depth == 2 ? true : false;
    }
 
 
 
    #region 库位分配
    #region 获取货位
    object objLOCK = new object();
    /// <summary>
    /// 双升库位分配
    /// </summary>
    /// <param name="RoadWayNo"></param>
    /// <param name="locationInfos"></param>
    /// <returns></returns>
    public DtLocationInfo RequestLocation(string RoadWayNo, List<DtLocationInfo> locationInfos = null)
    {
        lock (objLOCK)
        {
            try
            {
                //List<DtLocationInfo> locations = new List<DtLocationInfo>();
                if (locationInfos == null || locationInfos.Count == 0)
                {
                    locationInfos = BaseDal.QueryData(x => x.LocationStatus == (int)LocationEnum.Free && x.RoadwayNo == "SC1" && x.EnalbeStatus == 1 && x.LocationType == 1);
                }
 
                var location = GetEmptyLocation(locationInfos);
 
                if (location != null)
                {
                    if (location.Depth == 2)
                    {
                        int row = location.Row;
                        int relativeLine = row % 2 == 1 ? row + 1 : row - 1;
 
                        var insideLocation = BaseDal.QueryFirst(x => x.Row == relativeLine && x.Layer == location.Layer && x.Column == location.Column);
 
                        if (insideLocation.LocationStatus != (int)LocationEnum.Free /*|| insideLocation.EnalbeStatus ==*/ )
                        {
                            locationInfos.Remove(location);
                            if (locationInfos.Count == 0) return null;
                            RequestLocation(RoadWayNo, locationInfos);
                        }
                    }
                }
 
                if (location == null)
                {
                    return null;
                }
 
                return location;
            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message.ToString());
                return null;
            }
        }
    }
    private DtLocationInfo GetEmptyLocation(List<DtLocationInfo> dtLocationInfos)
    {
        var locationinfo = dtLocationInfos.Where(x => x.LocationStatus == (int)LocationEnum.Free && x.RoadwayNo == "SC1" && x.EnalbeStatus == 1 && x.LocationType == 1).OrderBy(x => x.Layer).ThenByDescending(x => x.Depth).ThenBy(x => x.Row).ThenBy(x => x.Column).FirstOrDefault();
 
        return locationinfo;
    }
 
    #endregion 获取货位
 
 
    #endregion 库位分配
 
    /// <summary>
    /// 根据巷道获取二深位的空库位
    /// </summary>
    /// <param name="roadway">巷道</param>
    /// <returns>货位对象</returns>
    private DtLocationInfo GetTransferLocationEmpty(string roadway)
    {
        var locationInfo = BaseDal.QueryFirst(x => x.EnalbeStatus == (int)EnableEnum.Enable && x.LocationStatus == (int)LocationEnum.Free && x.RoadwayNo == roadway);
        return locationInfo;
 
        /* x.Depth == 2 &&*/
        //Db.Queryable<Dt_LocationInfo>()
        //.Where(x => x.Status == LocationEnum.Free.ObjToInt())
        //.Where(x => x.Depth == 2.ToString())
        //.Where(x => x.Roadway == roadway)
        //.First();
    }
 
    #endregion 移库方法
 
    #region 创建初始货位方法
 
    public static string ConvertToFormattedString(int line, int column, int layer)
    {
        // 将每个部分转换为目标格式
        string lineString = ConvertNumberToChineseString(line);
        string columnString = ConvertNumberToChineseString(column);
        string layerString = ConvertNumberToChineseString(layer);
 
        // 格式化输出
        return $"{lineString}行{columnString}列{layerString}层";
    }
 
    public static string ConvertNumberToChineseString(int number)
    {
        string[] chineseNumbers = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十" };
 
        if (number <= 10)
        {
            return chineseNumbers[number];
        }
 
        // 处理大于10的数字
        string result = string.Empty;
        if (number / 10 > 1)
        {
            result += chineseNumbers[number / 10] + "十";
        }
        else
        {
            result += "十";
        }
 
        if (number % 10 > 0)
        {
            result += chineseNumbers[number % 10];
        }
 
        return result;
    }
 
    #endregion 创建初始货位方法
 
    #region 库存移入历史
    private async Task DeleteStockInfoAsync(int stockId)
    {
        var isStockUpdated = await _stockInfoRepository.DeleteDataByIdAsync(stockId);
        if (!isStockUpdated)
        {
            throw new Exception("库存信息更新失败");
        }
    }
 
    private async Task AddStockInfoHtyAsync(DtStockInfo_Hty dtStock)
    {
        var isStockAdd = await SqlSugarHelper.DbWMS.InsertNav(dtStock).IncludesAllFirstLayer().ExecuteCommandAsync();
        if (!isStockAdd)
        {
            throw new Exception("库存历史信息添加失败");
        }
    }
 
    private async Task DeleteStockInfoDetailsAsync(IEnumerable<DtStockInfoDetail> details)
    {
        var ids = details.Select(x => (object)x.Id).ToArray();
        var isStockDetailUpdated = await _stockInfoDetailRepository.DeleteDataByIdsAsync(ids);
        if (!isStockDetailUpdated)
        {
            throw new Exception("库存详情信息更新失败");
        }
    }
    private void AddStockInfoDetailHty(List<DtStockInfoDetail_Hty> details)
    {
 
        var isStockAdd = SqlSugarHelper.DbWMS.Insertable(details).ExecuteCommand();
        if (isStockAdd == 0)
        {
            throw new Exception("库存明细历史信息添加失败");
        }
    }
 
    #endregion
 
    #endregion 内部方法
}