skyouc
昨天 45430b88dab1451ecff39236dab01d5668b5b9c8
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
package com.vincent.rsf.server.manager.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.vincent.rsf.framework.common.Cools;
import com.vincent.rsf.server.manager.enums.*;
import com.vincent.rsf.framework.common.R;
import com.vincent.rsf.framework.exception.CoolException;
import com.vincent.rsf.server.api.utils.LocUtils;
import com.vincent.rsf.server.manager.controller.params.GenerateTaskParams;
import com.vincent.rsf.server.manager.entity.*;
import com.vincent.rsf.server.manager.mapper.TaskMapper;
import com.vincent.rsf.server.manager.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vincent.rsf.server.manager.utils.LocManageUtil;
import com.vincent.rsf.server.system.constant.SerialRuleCode;
import com.vincent.rsf.server.system.enums.LocStsType;
import com.vincent.rsf.server.system.utils.SerialRuleUtils;
import lombok.Synchronized;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.*;
import java.util.stream.Collectors;
 
@Service("taskService")
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements TaskService {
 
    @Autowired
    private WaitPakinService waitPakinService;
    @Autowired
    private TaskItemService taskItemService;
    @Autowired
    private WaitPakinItemService waitPakinItemService;
    @Autowired
    private LocService locService;
    @Autowired
    private PurchaseService purchaseService;
    @Autowired
    private AsnOrderService asnOrderService;
    @Autowired
    private AsnOrderItemService asnOrderItemService;
    @Autowired
    private StockService stockService;
    @Autowired
    private StockItemService stockItemService;
    @Autowired
    private DeviceSiteService deviceSiteService;
    @Autowired
    private LocItemService locItemService;
    @Autowired
    private DeviceBindService deviceBindService;
    @Autowired
    private WarehouseAreasService warehouseAreasService;
    @Autowired
    private WarehouseAreasItemService warehouseAreasItemService;
    @Autowired
    private WaveItemService waveItemService;
    @Autowired
    private WaveService waveService;
    @Autowired
    private BasStationService basStationService;
    @Autowired
    private TaskService taskService;
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized R generateAGVTasks(WaitPakin pakins, String locCode, String orgSta, Long loginUserId) {
        if (Cools.isEmpty(pakins) || Cools.isEmpty(locCode)) {
            throw new CoolException("参数不能为空!!");
        }
        /**获取组拖*/
//        List<Long> ids = pakins.stream().map(WaitPakin::getId).collect(Collectors.toList());
        List<WaitPakin> waitPakins = waitPakinService.list(new LambdaQueryWrapper<WaitPakin>()
                .in(WaitPakin::getId, pakins.getId())
                .eq(WaitPakin::getIoStatus, Short.parseShort(PakinIOStatus.PAKIN_IO_STATUS_DONE.val)));
        if (waitPakins.isEmpty()) {
            throw new CoolException("请检查组托状态是否完成!!");
        }
        waitPakins.forEach(pakin -> {
            /**获取库位*/
            String targetLoc = locCode;
            if (Cools.isEmpty(targetLoc)) {
                throw new CoolException("该站点对应库区未找到库位");
            }
 
            List<TaskItem> taskItems = new ArrayList<>();
            String ruleCode = SerialRuleUtils.generateRuleCode(SerialRuleCode.SYS_TASK_CODE, null);
            if (StringUtils.isBlank(ruleCode)) {
                throw new CoolException("编码错误:请确认编码「SYS_TASK_CODE」是否已生成!!");
            }
            Task task = new Task();
            task.setTaskCode(ruleCode)
                    .setTaskStatus(TaskStsType.GENERATE_IN.id.shortValue())
                    .setTaskType(TaskType.TASK_TYPE_IN.type.shortValue())
                    .setWarehType(WarehType.WAREHOUSE_TYPE_AGV.id)
                    .setTargLoc(targetLoc)
                    .setOrgSite(orgSta)
                    .setBarcode(pakin.getBarcode())
                    .setCreateBy(loginUserId)
                    .setUpdateBy(loginUserId);
 
            if (!this.save(task)) {
                throw new CoolException("任务保存失败!!");
            }
            if (!locService.update(new LambdaUpdateWrapper<Loc>().eq(Loc::getCode, task.getTargLoc())
                    .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_S.type).set(Loc::getBarcode, pakin.getBarcode()))) {
                throw new CoolException("库位预约失败!!");
            }
            /**获取组拖明细**/
            List<WaitPakinItem> waitPakinItems = waitPakinItemService.list(new LambdaQueryWrapper<WaitPakinItem>().eq(WaitPakinItem::getPakinId, pakin.getId()));
            if (waitPakinItems.isEmpty()) {
                throw new CoolException("数据错误:组拖明细不存在");
            }
            waitPakinItems.forEach(item -> {
                TaskItem taskItem = new TaskItem();
                BeanUtils.copyProperties(item, taskItem);
                taskItem.setTaskId(task.getId())
                        .setOrderType(OrderType.ORDER_IN.type)
                        .setSource(item.getId())
                        .setTrackCode(item.getTrackCode())
                        .setCreateBy(loginUserId)
                        .setUpdateBy(loginUserId)
                        .setExtendFields(item.getExtendFields())
                        .setOrderId(item.getAsnId())
                        .setOrderItemId(item.getAsnItemId());
                taskItems.add(taskItem);
            });
            if (!taskItemService.saveBatch(taskItems)) {
                throw new CoolException("任务明细保存失败!!");
            }
            waitPakinItems.forEach(item -> {
                if (!waitPakinItemService.update(new LambdaUpdateWrapper<WaitPakinItem>()
                        .set(WaitPakinItem::getWorkQty, item.getAnfme())
                        .eq(WaitPakinItem::getId, item.getId()))) {
                    throw new CoolException("组托明细修执行数量修改失败!!");
                }
            });
        });
 
        if (!waitPakinService.update(new LambdaUpdateWrapper<WaitPakin>()
                .in(WaitPakin::getId, pakins.getId())
                .set(WaitPakin::getUpdateBy, loginUserId)
                .set(WaitPakin::getCreateBy, loginUserId)
                .set(WaitPakin::getIoStatus, PakinIOStatus.PAKIN_IO_STATUS_TASK_EXCE.val))) {
            throw new CoolException("组托状态修改失败!!");
        }
        return R.ok("任务生成完毕!");
    }
 
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized R generateFlatWarehouseTasks(WaitPakin pakins, String locCode, Long loginUserId) {
        if (Cools.isEmpty(pakins) || Cools.isEmpty(locCode)) {
            throw new CoolException("参数不能为空!!");
        }
        /**获取组拖*/
//        List<Long> ids = pakins.stream().map(WaitPakin::getId).collect(Collectors.toList());
        List<WaitPakin> waitPakins = waitPakinService.list(new LambdaQueryWrapper<WaitPakin>()
                .in(WaitPakin::getId, pakins.getId())
                .eq(WaitPakin::getIoStatus, Short.parseShort(PakinIOStatus.PAKIN_IO_STATUS_DONE.val)));
        if (waitPakins.isEmpty()) {
            throw new CoolException("请检查组托状态是否完成!!");
        }
        waitPakins.forEach(pakin -> {
            /**获取库位*/
            String targetLoc = locCode;
            if (Cools.isEmpty(targetLoc)) {
                throw new CoolException("该站点对应库区未找到库位");
            }
 
            List<TaskItem> taskItems = new ArrayList<>();
            String ruleCode = SerialRuleUtils.generateRuleCode(SerialRuleCode.SYS_TASK_CODE, null);
            if (StringUtils.isBlank(ruleCode)) {
                throw new CoolException("编码错误:请确认编码「SYS_TASK_CODE」是否已生成!!");
            }
            Task task = new Task();
            task.setTaskCode(ruleCode)
                    .setTaskStatus(TaskStsType.COMPLETE_IN.id.shortValue())
                    .setTaskType(TaskType.TASK_TYPE_IN.type.shortValue())
                    .setWarehType(WarehType.WAREHOUSE_TYPE_PLAT.id)
                    .setTargLoc(targetLoc)
                    .setBarcode(pakin.getBarcode())
                    .setCreateBy(loginUserId)
                    .setUpdateBy(loginUserId);
 
            if (!this.save(task)) {
                throw new CoolException("任务保存失败!!");
            }
            if (!locService.update(new LambdaUpdateWrapper<Loc>().eq(Loc::getCode, task.getTargLoc())
                    .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_S.type).set(Loc::getBarcode, pakin.getBarcode()))) {
                throw new CoolException("库位预约失败!!");
            }
            /**获取组拖明细**/
            List<WaitPakinItem> waitPakinItems = waitPakinItemService.list(new LambdaQueryWrapper<WaitPakinItem>().eq(WaitPakinItem::getPakinId, pakin.getId()));
            if (waitPakinItems.isEmpty()) {
                throw new CoolException("数据错误:组拖明细不存在");
            }
            waitPakinItems.forEach(item -> {
                TaskItem taskItem = new TaskItem();
                BeanUtils.copyProperties(item, taskItem);
                taskItem.setTaskId(task.getId())
                        .setOrderType(OrderType.ORDER_IN.type)
                        .setSource(item.getId())
                        .setTrackCode(item.getTrackCode())
                        .setCreateBy(loginUserId)
                        .setUpdateBy(loginUserId)
                        .setExtendFields(item.getExtendFields())
                        .setOrderId(item.getAsnId())
                        .setOrderItemId(item.getAsnItemId());
                taskItems.add(taskItem);
            });
            if (!taskItemService.saveBatch(taskItems)) {
                throw new CoolException("任务明细保存失败!!");
            }
            waitPakinItems.forEach(item -> {
                if (!waitPakinItemService.update(new LambdaUpdateWrapper<WaitPakinItem>()
                        .set(WaitPakinItem::getWorkQty, item.getAnfme())
                        .eq(WaitPakinItem::getId, item.getId()))) {
                    throw new CoolException("组托明细修执行数量修改失败!!");
                }
            });
        });
 
        if (!waitPakinService.update(new LambdaUpdateWrapper<WaitPakin>()
                .in(WaitPakin::getId, pakins.getId())
                .set(WaitPakin::getUpdateBy, loginUserId)
                .set(WaitPakin::getCreateBy, loginUserId)
                .set(WaitPakin::getIoStatus, PakinIOStatus.PAKIN_IO_STATUS_TASK_EXCE.val))) {
            throw new CoolException("组拖状态修改失败!!");
        }
        return R.ok("任务生成完毕!");
    }
 
 
    /**
     * @param
     * @param loginUserId
     * @return
     * @author Ryan
     * @description 生成任务列表
     * @time 2025/3/29 15:59
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized R generateTasks(GenerateTaskParams waitPakin, Long loginUserId) {
        if (Objects.isNull(waitPakin) || waitPakin.getWaitPakins().isEmpty()) {
            throw new CoolException("参数不能为空!!");
        }
 
        DeviceSite deviceSite = deviceSiteService.getById(waitPakin.getSiteId());
        if (Objects.isNull(deviceSite)) {
            throw new CoolException("站点不存在!!");
        }
        DeviceBind deviceBind = deviceBindService.getById(LocUtils.getAreaType(Integer.valueOf(deviceSite.getSite())));
        if (Cools.isEmpty(deviceBind)) {
            throw new CoolException("库位规则未知");
        }
        WarehouseAreas warehouseArea = warehouseAreasService.getById(deviceBind.getTypeId());
        if (Cools.isEmpty(warehouseArea)) {
            throw new CoolException("未找到所属库区信息");
        }
 
        /**获取组拖*/
        List<Long> ids = waitPakin.getWaitPakins().stream().map(WaitPakin::getId).collect(Collectors.toList());
        List<WaitPakin> waitPakins = waitPakinService.list(new LambdaQueryWrapper<WaitPakin>()
                .in(WaitPakin::getId, ids)
                .eq(WaitPakin::getIoStatus, Short.parseShort(PakinIOStatus.PAKIN_IO_STATUS_DONE.val)));
        if (waitPakins.isEmpty()) {
            throw new CoolException("请检查组拖状态是否完成!!");
        }
        waitPakins.forEach(pakin -> {
            /**获取库位*/
            String targetLoc = LocManageUtil.getTargetLoc(warehouseArea.getId());
            if (Cools.isEmpty(targetLoc)) {
                throw new CoolException("该站点对应库区未找到库位");
            }
 
            List<TaskItem> taskItems = new ArrayList<>();
            String ruleCode = SerialRuleUtils.generateRuleCode(SerialRuleCode.SYS_TASK_CODE, null);
            if (StringUtils.isBlank(ruleCode)) {
                throw new CoolException("编码错误:请确认编码「SYS_TASK_CODE」是否已生成!!");
            }
            Task task = new Task();
            task.setTaskCode(ruleCode)
                    .setTaskStatus(TaskStsType.GENERATE_IN.id.shortValue())
                    .setTaskType(TaskType.TASK_TYPE_IN.type.shortValue())
                    .setTargLoc(targetLoc)
                    .setBarcode(pakin.getBarcode())
                    .setOrgSite(deviceSite.getSite())
                    .setTargSite(deviceSite.getDeviceSite())
                    .setCreateBy(loginUserId)
                    .setUpdateBy(loginUserId);
//            if (!Objects.isNull(waitPakin.getSiteId()) && waitPakin.getSiteId() > 0) {
//                DeviceSite site = deviceSiteService.getById(waitPakin.getSiteId());
//                task.setTargSite(site.getSite() + "");
//            } else {
//                task.setTargSite(LocManageUtil.getTargetSite());
//            }
//            if (!Objects.isNull(waitPakin.getLocCode()) && StringUtils.isNotBlank(waitPakin.getLocCode())) {
//                List<Loc> locs = locService.list(new LambdaQueryWrapper<Loc>().eq(Loc::getCode, waitPakin.getLocCode()));
////                if (!locs.isEmpty()) {
////                    throw new CoolException("库位错误:相同库位应只一条")
////                }
//                Loc loc = locs.stream().findFirst().get();
//                task.setTargSite(loc.getCode());
//            } else {
//                task.setTargSite(LocManageUtil.getTargetSite());
//            }
 
            if (!this.save(task)) {
                throw new CoolException("任务保存失败!!");
            }
            if (!locService.update(new LambdaUpdateWrapper<Loc>().eq(Loc::getCode, task.getTargLoc())
                    .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_S.type).set(Loc::getBarcode, pakin.getBarcode()))) {
                throw new CoolException("库位预约失败!!");
            }
            /**获取组拖明细**/
            List<WaitPakinItem> waitPakinItems = waitPakinItemService.list(new LambdaQueryWrapper<WaitPakinItem>().eq(WaitPakinItem::getPakinId, pakin.getId()));
            if (waitPakinItems.isEmpty()) {
                throw new CoolException("数据错误:组拖明细不存在");
            }
            waitPakinItems.forEach(item -> {
                TaskItem taskItem = new TaskItem();
                BeanUtils.copyProperties(item, taskItem);
//                AsnOrder order = asnOrderService.getOne(new LambdaQueryWrapper<AsnOrder>().eq(AsnOrder::getId, item.getAsnId()));
//                if (Objects.isNull(order)) {
//                    throw new CoolException("数据错误: 单据不存在!!");
//                }
                taskItem.setTaskId(task.getId())
                        .setOrderType(OrderType.ORDER_IN.type)
                        .setSource(item.getId())
                        .setTrackCode(item.getTrackCode())
                        .setPlatItemId(item.getPlatItemId())
                        .setPlatOrderCode(item.getPlatOrderCode())
                        .setPlatWorkCode(item.getPlatWorkCode())
                        .setProjectCode(item.getProjectCode())
                        .setCreateBy(loginUserId)
                        .setUpdateBy(loginUserId)
                        .setExtendFields(item.getExtendFields())
                        .setOrderId(item.getAsnId())
                        .setOrderItemId(item.getAsnItemId());
                taskItems.add(taskItem);
            });
            if (!taskItemService.saveBatch(taskItems)) {
                throw new CoolException("任务明细保存失败!!");
            }
            waitPakinItems.forEach(item -> {
                if (!waitPakinItemService.update(new LambdaUpdateWrapper<WaitPakinItem>()
                        .set(WaitPakinItem::getWorkQty, item.getAnfme())
                        .eq(WaitPakinItem::getId, item.getId()))) {
                    throw new CoolException("组托明细修执行数量修改失败!!");
                }
            });
        });
 
        if (!waitPakinService.update(new LambdaUpdateWrapper<WaitPakin>()
                .in(WaitPakin::getId, ids)
                .set(WaitPakin::getUpdateBy, loginUserId)
                .set(WaitPakin::getCreateBy, loginUserId)
                .set(WaitPakin::getIoStatus, PakinIOStatus.PAKIN_IO_STATUS_TASK_EXCE.val))) {
            throw new CoolException("组拖状态修改失败!!");
        }
        return R.ok("任务生成完毕!");
    }
 
    /**
     * 完成任务 更新库位明细信息,将单据库存更新到单据库存表
     *
     * @param tasks
     * @throws Exception
     */
    @Synchronized
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void completeTask(List<Task> tasks) throws Exception {
        for (Task task : tasks) {
            //出库任务
            if (task.getTaskType() < TaskType.TASK_TYPE_OUT.type) {
                if (task.getTaskType().equals(TaskType.TASK_TYPE_IN.type)) {
                    //1.入库
                    complateInstock(task);
                } else if (task.getTaskType().equals(TaskType.TASK_TYPE_PICK_IN.type)) {
                    //53.拣料再入库
                    
                }
            } else {
                //出库任务
                if (task.getTaskType().equals(TaskType.TASK_TYPE_OUT.type)) {
                    //全托出库
                    complateOutStock(task);
                } else if (task.getTaskType().equals(TaskType.TASK_TYPE_PICK_AGAIN_IN.type)) {
                    //拣料出库,
                    taskService.pickTask(task.getId());
                }
            }
        }
    }
 
    /**
     * 任务取消
     *
     * @param ids
     * @return
     */
    @Override
    public R removeTask(Long[] ids) {
        List<Short> longs = Arrays.asList(TaskStsType.GENERATE_IN.id, TaskStsType.GENERATE_OUT.id);
        List<Task> tasks = this.list(new LambdaQueryWrapper<Task>().in(Task::getId, ids).in(Task::getTaskStatus, longs));
        if (tasks.isEmpty()) {
            throw new CoolException("任务已处执行状态不可取消!!");
        }
        for (Task task : tasks) {
            //恢复组托状态
            WaitPakin waitPakin = waitPakinService.getOne(new LambdaQueryWrapper<WaitPakin>()
                    .eq(WaitPakin::getBarcode, task.getBarcode())
            );
            if (null != waitPakin) {
                waitPakin.setIoStatus(Short.valueOf(PakinIOStatus.PAKIN_IO_STATUS_DONE.val));
                if (!waitPakinService.updateById(waitPakin)) {
                    throw new CoolException("更新组托状态失败!!");
                }
            }
            Loc loc = locService.getOne(new LambdaQueryWrapper<Loc>().eq(Loc::getCode, task.getTaskType() < TaskStsType.UPDATED_IN.id ? task.getTargLoc() : task.getOrgLoc()));
            if (null != loc
                    && (loc.getUseStatus().equals(LocStsType.LOC_STS_TYPE_S.type)
                    || loc.getUseStatus().equals(LocStsType.LOC_STS_TYPE_R.type))) {
 
                loc.setUseStatus(LocStsType.LOC_STS_TYPE_O.type);
                if (!locService.updateById(loc)) {
                    throw new CoolException("更新库位状态失败!!");
                }
            }
            if (!Objects.isNull(task.getWarehType()) && task.getWarehType().equals(WarehType.WAREHOUSE_TYPE_AGV.id)) {
                BasStation basStation = null;
                if (task.getTaskType().equals(TaskType.TASK_TYPE_IN.type) || task.getTaskType().equals(TaskType.TASK_TYPE_EMPITY_IN.type)) {
                    basStation = basStationService.getOne(new LambdaQueryWrapper<BasStation>()
                            .eq(BasStation::getStationName, task.getOrgSite())
                            .eq(BasStation::getUseStatus, StaUseStatusType.TYPE_R.type)
                    );
                } else if (task.getTaskType().equals(TaskType.TASK_TYPE_OUT.type)
                        || task.getTaskType().equals(TaskType.TASK_TYPE_PICK_AGAIN_IN.type)
                        || task.getTaskType().equals(TaskType.TASK_TYPE_MERGE_OUT.type)
                        || task.getTaskType().equals(TaskType.TASK_TYPE_CHECK_OUT.type)
                        || task.getTaskType().equals(TaskType.TASK_TYPE_EMPITY_OUT.type)
                ) {
                    basStation = basStationService.getOne(new LambdaQueryWrapper<BasStation>()
                            .eq(BasStation::getStationName, task.getTargLoc())
                            .eq(BasStation::getUseStatus, StaUseStatusType.TYPE_R.type)
                    );
                }
                if (null == basStation) {
                    throw new CoolException("站点状态错误!!");
                }
                basStation.setUseStatus(StaUseStatusType.TYPE_F.type);
                if (!basStationService.updateById(basStation)) {
                    throw new CoolException("更新站点状态失败!!");
                }
            }
        }
        if (!this.removeByIds(Arrays.asList(ids))) {
            throw new CoolException("Delete Fail");
        }
 
        return R.ok("取消完成");
    }
 
    /**
     * 拣料出库
     *
     * @param id
     * @return
     */
    @Override
    public R pickTask(Long id) {
        Task task = this.getById(id);
        if (Objects.isNull(task)) {
            throw new CoolException("当前任务不存在!!");
        }
        if (!task.getTaskType().equals(TaskType.TASK_TYPE_PICK_AGAIN_IN.type)) {
            throw new CoolException("非拣料出库 ,不可执行此操作!!");
        }
 
        Loc loc = locService.getOne(new LambdaQueryWrapper<Loc>()
                .eq(Loc::getCode, task.getOrgLoc()));
        if (Objects.isNull(loc)) {
            throw new CoolException("没有空库位!!");
        }
 
        String ruleCode = SerialRuleUtils.generateRuleCode(SerialRuleCode.SYS_TASK_CODE, task);
        //更新任务主单
        task.setTaskCode(ruleCode)
                .setTaskType(TaskType.TASK_TYPE_PICK_IN.type)
                .setTargLoc(task.getOrgLoc()) //出库源库位变入库目标库位
                .setTaskStatus(TaskStsType.GENERATE_IN.id);
 
        if (!this.updateById(task)) {
            throw new CoolException("任务状态更新失败!!");
        }
 
        //修改库位状态 预约出库.R==>预约入库.S
        loc.setUseStatus(StaUseStatusType.TYPE_S.type);
 
        if (!locService.updateById(loc)) {
            throw new CoolException("库位状态更新失败!!");
        }
 
        return R.ok("拣货成功!!");
    }
 
    /**
     * @author Ryan
     * @date 2025/5/20
     * @description: 完成出库任务,更新出库库存信息
     * @version 1.0
     */
    @Transactional(rollbackFor = Exception.class)
    public synchronized void complateOutStock(Task task) {
        if (Objects.isNull(task)) {
            throw new CoolException("参数不能为空!!");
        }
        Loc loc = locService.getOne(new LambdaQueryWrapper<Loc>().eq(Loc::getCode, task.getOrgLoc()));
        if (Objects.isNull(loc)) {
            throw new CoolException("库位不存在!!");
        }
        if (!loc.getUseStatus().equals(LocStsType.LOC_STS_TYPE_R.type)) {
            throw new CoolException("库位状态不处理于R.出库预约!!");
        }
 
        List<TaskItem> taskItems = taskItemService.list(new LambdaQueryWrapper<TaskItem>().eq(TaskItem::getTaskId, task.getId()));
        if (taskItems.isEmpty()) {
            throw new CoolException("任务明细不存在!!");
        }
        try {
            //更新库位明细
            subtractLocItem(taskItems, loc);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
 
        //添加出入库记录信息
        Map<Short, List<TaskItem>> listMap = taskItems.stream().collect(Collectors.groupingBy(TaskItem::getWkType));
        /***获取库存出库值,如果为空表示正常单据出库,非空表明是库存出库
         * 1. 库存出库没有单据信息,单据信息默认为空
         * 2. 单据库存需通过波次查询原始单据信息,将单据信息填入stock中
         * */
        List<TaskItem> list = listMap.get(Short.parseShort(OrderWorkType.ORDER_WORK_TYPE_STOCK_OUT.type));
        if (Objects.isNull(list) || list.isEmpty()) {
            Map<Long, List<TaskItem>> maps = taskItems.stream().collect(Collectors.groupingBy(TaskItem::getSource));
            maps.keySet().forEach(key -> {
                WaveItem waveItem = waveItemService.getById(key);
                if (Objects.isNull(waveItem)) {
                    throw new CoolException("波次明细不存在!!");
                }
                try {
                    saveOutStockItem(maps.get(key), waveItem);
                } catch (Exception e) {
                    throw new CoolException(e.getMessage());
                }
            });
        } else {
            try {
                saveOutStockItem(taskItems, null);
            } catch (Exception e) {
                throw new CoolException(e.getMessage());
            }
        }
 
        /**修改为库位状态为O.空库*/
        if (!locService.update(new LambdaUpdateWrapper<Loc>().set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_O.type).eq(Loc::getCode, loc.getId()))) {
            throw new CoolException("库位状态修改失败!!");
        }
        if (!this.update(new LambdaUpdateWrapper<Task>().eq(Task::getId, task.getId()).set(Task::getTaskStatus, TaskStsType.UPDATED_OUT.id))) {
            throw new CoolException("任务状态修改失败!!");
        }
    }
 
    /**
     * @author Ryan
     * @date 2025/5/20
     * @description: 出库信息保存至库存明细表
     * @version 1.0
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveOutStockItem(List<TaskItem> taskItems, WaveItem waveItem) throws Exception {
        Stock stock = new Stock();
        String ruleCode = SerialRuleUtils.generateRuleCode(SerialRuleCode.SYS_STOCK_CODE, null);
        if (StringUtils.isBlank(ruleCode)) {
            throw new CoolException("当前业务:" + SerialRuleCode.SYS_STOCK_CODE + ",编码规则不存在!!");
        }
        Double sum = taskItems.stream().mapToDouble(TaskItem::getAnfme).sum();
        stock.setCode(ruleCode)
                .setAnfme(sum);
        if (Objects.isNull(waveItem)) {
            stock.setWkType(Short.parseShort(OrderWorkType.ORDER_WORK_TYPE_STOCK_OUT.type))
                    .setMemo("出库单出库,无单据信息!!")
                    .setType(OrderType.ORDER_OUT.type);
        } else {
            //TODO 生成波次时需要将波次号写入单据,通过物料,批次,动态字段等唯一值反查单据信息
            stock.setSourceId(waveItem.getId()).setType(OrderType.ORDER_OUT.type);
        }
        if (!stockService.save(stock)) {
            throw new CoolException("库存保存失败!!");
        }
        List<StockItem> stockItems = new ArrayList<>();
        for (TaskItem item : taskItems) {
            /**通过任务明细中的taskId查询,获取TASK的目标库位信息*/
            StockItem stockItem = new StockItem();
            BeanUtils.copyProperties(item, stockItem);
            stockItem.setSourceItemId(item.getOrderItemId())
                    .setStockCode(stock.getCode())
                    .setId(null)
                    .setStockId(stock.getId());
            stockItems.add(stockItem);
        }
        if (!stockItemService.saveBatch(stockItems)) {
            throw new CoolException("库存修改架失败!!");
        }
 
    }
 
    /**
     * @author Ryan
     * @date 2025/5/20
     * @description: 扣减库存明细
     * @version 1.0
     */
    @Transactional(rollbackFor = Exception.class)
    public void subtractLocItem(List<TaskItem> items, Loc loc) throws Exception {
        if (!locItemService.remove(new LambdaQueryWrapper<LocItem>().eq(LocItem::getLocId, loc.getId()))) {
            throw new CoolException("库存明细删除失败!!");
        }
    }
 
    /**
     * @author Ryan
     * @date 2025/5/20
     * @description: 完成入库任务
     * @version 1.0
     */
    @Transactional(rollbackFor = Exception.class)
    public void complateInstock(Task task) {
        if (Objects.isNull(task)) {
            return;
        }
        List<TaskItem> taskItems = taskItemService.list(new LambdaQueryWrapper<TaskItem>().eq(TaskItem::getTaskId, task.getId()));
        if (taskItems.isEmpty()) {
            throw new CoolException("任务明细不存在!!");
        }
        try {
            //更新库位明细
            saveLocItem(taskItems, task.getId());
        } catch (Exception e) {
            throw new CoolException("库位明细更新失败!!");
        }
 
        /**对任务明细按组拖明细进行分组*/
        Map<Long, List<TaskItem>> orderMap = taskItems.stream().collect(Collectors.groupingBy(TaskItem::getSource));
        orderMap.keySet().forEach(key -> {
            WaitPakinItem pakinItem = waitPakinItemService.getById(key);
            if (Objects.isNull(pakinItem)) {
                throw new CoolException("数据错误:组拖数据不存在,请联系管理员!!");
            }
            List<TaskItem> items = orderMap.get(key);
            try {
                //保存库存明细
                saveStockItems(items, pakinItem);
                //移出收货区库存, 修改组托状态
                removeReceiptStock(pakinItem);
            } catch (Exception e) {
                throw new CoolException(e.getMessage());
            }
        });
        /**修改库位状态为F.在库*/
        if (!locService.update(new LambdaUpdateWrapper<Loc>().set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_F.type).eq(Loc::getCode, task.getTargLoc()))) {
            throw new CoolException("库位状态修改失败!!");
        }
        if (!this.update(new LambdaUpdateWrapper<Task>().eq(Task::getId, task.getId()).set(Task::getTaskStatus, TaskStsType.UPDATED_IN.id))) {
            throw new CoolException("任务状态修改失败!!");
        }
    }
 
    /**
     * @param
     * @return
     * @author Ryan
     * @description 移除收货区库存
     * @time 2025/4/30 16:32
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeReceiptStock(WaitPakinItem pakinItem) {
        WarehouseAreasItem itemServiceOne = warehouseAreasItemService.getOne(new LambdaQueryWrapper<WarehouseAreasItem>()
                .eq(WarehouseAreasItem::getId, pakinItem.getSource()));
        if (Objects.isNull(itemServiceOne)) {
            throw new CoolException("数据错误:请查看请货区库存是否存在!!");
        }
        Double workQty = itemServiceOne.getWorkQty() - pakinItem.getAnfme();
        Double qty = itemServiceOne.getQty() + pakinItem.getAnfme();
        itemServiceOne.setWorkQty(workQty).setQty(qty);
 
        if (!waitPakinService.update(new LambdaUpdateWrapper<WaitPakin>()
                .set(WaitPakin::getIoStatus, PakinIOStatus.PAKIN_IO_STATUS_TASK_DONE.val)
                .eq(WaitPakin::getId, pakinItem.getPakinId()))) {
            throw new CoolException("组拖状态修改失败!!");
        }
 
        if (qty.compareTo(itemServiceOne.getAnfme()) == 0.00) {
            if (!warehouseAreasItemService.removeById(itemServiceOne.getId())) {
                throw new CoolException("收货区物料删除失败!!");
            }
        } else {
            if (!warehouseAreasItemService.updateById(itemServiceOne)) {
                throw new CoolException("收货区库完成数量修改失败!!");
            }
        }
    }
 
    /**
     * @param
     * @return
     * @author Ryan
     * @description 更新库位明细
     * @time 2025/4/15 15:28
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveLocItem(List<TaskItem> items, Long taskId) throws Exception {
        Task task = this.getById(taskId);
        if (Objects.isNull(task)) {
            throw new CoolException("任务不存在!!");
        }
        List<LocItem> locItems = new ArrayList<>();
        items.forEach(taskItem -> {
            Loc loc = locService.getOne(new LambdaQueryWrapper<Loc>().eq(Loc::getCode, task.getTargLoc()), false);
            LocItem item = new LocItem();
            BeanUtils.copyProperties(taskItem, item);
            item.setLocCode(loc.getCode()).setId(null)
                    .setLocId(loc.getId())
                    .setWkType(taskItem.getWkType())
                    .setType(taskItem.getOrderType());
            locItems.add(item);
        });
        if (!locItemService.saveBatch(locItems)) {
            throw new CoolException("库位明细更新失败!!");
        }
    }
 
    /**
     * 生成入库库存明细
     *
     * @param items
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveStockItems(List<TaskItem> items, WaitPakinItem order) throws Exception {
        Stock stock = new Stock();
        String ruleCode = SerialRuleUtils.generateRuleCode(SerialRuleCode.SYS_STOCK_CODE, null);
        if (StringUtils.isBlank(ruleCode)) {
            throw new CoolException("当前业务:" + SerialRuleCode.SYS_STOCK_CODE + ",编码规则不存在!!");
        }
        double sum = items.stream().mapToDouble(TaskItem::getAnfme).sum();
        stock.setSourceId(order.getId())
                .setCode(ruleCode)
                .setSourceCode(order.getAsnCode())
                .setAnfme(sum)
                .setWkType(order.getWkType())
                .setType(order.getType());
        if (!stockService.save(stock)) {
            throw new CoolException("库存保存失败!!");
        }
 
        List<StockItem> stockItems = new ArrayList<>();
        for (TaskItem item : items) {
            /**通过任务明细中的taskId查询,获取TASK的目标库位信息*/
            StockItem stockItem = new StockItem();
            BeanUtils.copyProperties(item, stockItem);
            stockItem.setSourceItemId(item.getOrderItemId())
                    .setStockCode(stock.getCode())
                    .setSourceItemId(item.getOrderItemId())
                    .setId(null)
                    .setStockId(stock.getId());
            stockItems.add(stockItem);
        }
        if (!stockItemService.saveBatch(stockItems)) {
            throw new CoolException("库存修改架失败!!");
        }
    }
}