cuilei
2025-05-30 4cd4e691d4f959d71bf118f7006de0fc0e2b95e4
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
package org.jeecg.modules.tms.service.impl;
 
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.flowable.apithird.business.entity.FlowMyBusiness;
import org.jeecg.modules.flowable.apithird.business.service.IFlowMyBusinessService;
import org.jeecg.modules.flowable.apithird.service.FlowCallBackServiceI;
import org.jeecg.modules.flowable.apithird.service.FlowCommonService;
import org.jeecg.modules.flowable.service.IFlowDefinitionService;
import org.jeecg.modules.flowable.service.IFlowTaskService;
import org.jeecg.modules.system.service.ISysBusinessCodeRuleService;
import org.jeecg.modules.tms.entity.*;
import org.jeecg.modules.tms.entity.dto.OutBoundAddDto;
import org.jeecg.modules.tms.entity.dto.OutBoundOrderFlowDto;
import org.jeecg.modules.tms.entity.dto.OutBoundRequestDto;
import org.jeecg.modules.tms.entity.dto.OutboundOrderAndDetailDto;
import org.jeecg.modules.tms.enums.OutBillStatus;
import org.jeecg.modules.tms.enums.OutBoundStatusEnum;
import org.jeecg.modules.tms.enums.OutStorehouseType;
import org.jeecg.modules.tms.enums.ToolCirculationStatus;
import org.jeecg.modules.tms.mapper.OutboundDetailMapper;
import org.jeecg.modules.tms.convert.OutboundOrderConvert;
import org.jeecg.modules.tms.mapper.OutboundOrderMapper;
import org.jeecg.modules.tms.service.*;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * @Description: tms_outbound_order
 * @Author: jeecg-boot
 * @Date:   2025-05-16
 * @Version: V1.0
 */
@Slf4j
@Service
public class OutboundOrderServiceImpl extends ServiceImpl<OutboundOrderMapper, OutboundOrder> implements IOutboundOrderService, FlowCallBackServiceI {
 
    @Autowired
    private IOutboundDetailService outboundDetailService;
    @Autowired
    private IToolLedgerService toolLedgerService;
    @Autowired
    private IToolLedgerDetailService toolLedgerDetailService;
    @Autowired
    private IOutStoreDetailService outStoreDetailService;
    @Autowired
    private IBaseToolsService baseToolsService;
    @Autowired
    private ISysBusinessCodeRuleService businessCodeRuleService;
    @Autowired
    private IFlowDefinitionService flowDefinitionService;
    @Autowired
    private IFlowMyBusinessService flowMyBusinessService;
    @Autowired
    private IFlowTaskService flowTaskService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private FlowCommonService flowCommonService;
    @Autowired
    private OutboundOrderMapper outboundOrderMapper;
    @Autowired
    private OutboundDetailMapper outboundDetailMapper;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delMain(String id) {
        outboundDetailMapper.deleteByMainId(id);
        outboundOrderMapper.deleteById(id);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for(Serializable id:idList) {
            outboundDetailMapper.deleteByMainId(id.toString());
            outboundOrderMapper.deleteById(id);
        }
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addTotal(OutboundOrderAndDetailDto outboundOrder) {
        OutboundOrder order = OutboundOrderConvert.INSTANCE.convert(outboundOrder);
        order.setHandler(Objects.requireNonNull(getCurrentUser()).getId());
        order.setOutNum(businessCodeRuleService.generateBusinessCodeSeq("outBoundOrder"));
        order.setOrderStatus(OutBillStatus.DRAFT.getValue());
        save(order);
        List<OutboundDetail> detailList = CollectionUtil.newArrayList();
        outboundOrder.getOutboundDetailList().forEach(item->{
            item.setId(null);
            item.setOutStorehouseId(order.getId());
            detailList.add(item);
        });
        outboundDetailService.saveBatch(detailList);
    }
 
    @Override
    public IPage<OutboundOrder> queryPageList(Page<OutboundOrder> page, Map<String, String[]> parameterMap) {
        QueryWrapper<OutboundOrder> queryWrapper = Wrappers.query();
        String[] outNums = parameterMap.get("outNum");
        if (outNums != null && outNums.length > 0) {
            queryWrapper.like("t.out_num", outNums[0]);
        }
        String[] outStorehouseTypes = parameterMap.get("outStorehouseType");
        if (outStorehouseTypes != null && outStorehouseTypes.length > 0) {
            queryWrapper.eq("t.out_storehouse_type", outStorehouseTypes[0]);
        }
        String[] orderStatuses = parameterMap.get("orderStatus");
        if (orderStatuses != null && orderStatuses.length > 0) {
            queryWrapper.eq("t.order_status", orderStatuses[0]);
        }
        String[] outStatuses = parameterMap.get("outStatus");
        if (outStatuses != null && outStatuses.length > 0) {
            queryWrapper.eq("t.out_status", outStatuses[0]);
        }
        String[] startTimes = parameterMap.get("startTime");
        if (startTimes != null && startTimes.length > 0) {
            queryWrapper.ge("t.create_time", startTimes[0]);
        }
        String[] endTimes = parameterMap.get("endTime");
        if (endTimes != null && endTimes.length > 0) {
            queryWrapper.le("t.create_time", endTimes[0]);
        }
        queryWrapper.orderByDesc("t.create_time");
        return this.baseMapper.queryPageList(page, queryWrapper);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editTotal(OutboundOrderAndDetailDto outboundOrder) {
        //删除所有明细
        outboundDetailService.remove(new LambdaQueryWrapper<OutboundDetail>()
                .eq(OutboundDetail::getOutStorehouseId, outboundOrder.getId()));
        OutboundOrder outboundOrderUpdate = BeanUtil.copyProperties(outboundOrder, OutboundOrder.class);
        outboundOrderMapper.updateById(outboundOrderUpdate);
        List<OutboundDetail> detailList = CollectionUtil.newArrayList();
        outboundOrder.getOutboundDetailList().forEach(item->{
            item.setOutStorehouseId(outboundOrderUpdate.getId());
            detailList.add(item);
        });
        outboundDetailService.saveBatch(detailList);
    }
 
    @Override
    public void submit(String id) {
        OutboundOrder outboundOrder = getById(id);
        if (outboundOrder == null) {
            throw new JeecgBootException("出库单申请单不存在,无法提交!");
        }
        if (!Objects.equals(outboundOrder.getOrderStatus(), OutBillStatus.DRAFT.getValue())) {
            throw new JeecgBootException("无法提交非草稿状态的出库申请单!");
        }
        //启动流程
        if (triggerProcess(outboundOrder)) {
            outboundOrder.setOrderStatus(OutBillStatus.SUBMITTED.getValue());
        }
        updateById(outboundOrder);
    }
 
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approvalProcess(OutBoundOrderFlowDto outBoundOrderFlowDto) {
        if (StrUtil.isBlank(outBoundOrderFlowDto.getTaskId()) || StrUtil.isBlank(outBoundOrderFlowDto.getDataId())) {
            throw new JeecgBootException("非法参数!");
        }
 
        // 获取当前登录用户
        LoginUser user = getCurrentUser();
        if (user == null || StrUtil.isBlank(user.getId())) {
            throw new JeecgBootException("账号不存在");
        }
 
        //获取出库申请单信息
        OutboundOrder outboundOrder = getById(outBoundOrderFlowDto.getDataId());
        if (outboundOrder == null) {
            throw new JeecgBootException("未找到对应的出库申请单!");
        }
 
        //获取流程业务记录
        FlowMyBusiness flowMyBusiness = getFlowMyBusiness(outBoundOrderFlowDto.getInstanceId());
        if (flowMyBusiness == null) {
            throw new JeecgBootException("流程记录不存在");
        }
 
        // 检查用户是否有权限操作任务
        if (!isUserAuthorized(flowMyBusiness, user)) {
            throw new JeecgBootException("用户无权操作此任务");
        }
 
        // 认领任务
        if (!claimTask(flowMyBusiness.getTaskId(), user)) {
            throw new JeecgBootException("任务不存在、已完成或已被他人认领");
        }
 
        //设置流程变量
        setupProcessVariables(outBoundOrderFlowDto, outboundOrder, user);
 
        //完成流程任务
        Result result = flowTaskService.complete(outBoundOrderFlowDto);
 
        //根据任务完成结果更新申请单状态
        if (result.isSuccess()) {
            if (OutBillStatus.APPROVED.getValue().equals(outBoundOrderFlowDto.getStatus())) {
                outboundOrder.setOutStatus(OutBoundStatusEnum.NOT_OUTBOUND.getValue());
                outboundOrder.setOrderStatus(OutBillStatus.APPROVED.getValue());
                //初始化申请明细信息的出库状态/实际出库数量字段
                outboundDetailService.update(new LambdaUpdateWrapper<OutboundDetail>()
                        .eq(OutboundDetail::getOutStorehouseId, outboundOrder.getId())
                        .set(OutboundDetail::getStatus, OutBoundStatusEnum.NOT_OUTBOUND.getValue())
                        .set(OutboundDetail::getOutActualCount, BigDecimal.ZERO));
            }
            if (OutBillStatus.REJECTED.getValue().equals(outBoundOrderFlowDto.getStatus())) {
                //如果驳回,审批单状态回到草稿
                outboundOrder.setOrderStatus(OutBillStatus.DRAFT.getValue());
            }
            outboundOrder.setAuditDate(new Date());
            outboundOrder.setApprovalOpinion(outBoundOrderFlowDto.getApprovalOpinion());
            updateById(outboundOrder);
        }
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void outBoundByApply(List<OutBoundRequestDto> outBoundRequestList) {
        //校验是否来自一个申请单
        if (!fromOneApply(outBoundRequestList)) {
            throw new JeecgBootException("出库明细必须来自同一出库申请单!");
        }
        //是否可出库校验
        if (!readyToOutbound(outBoundRequestList)) {
            throw new JeecgBootException("未经审批通过的申请单不能出库!");
        }
        //开始出库
        OutboundOrder outboundOrder = getById(outBoundRequestList.get(0).getOutBoundOrderId());
        List<String> detailIds = outBoundRequestList.stream().map(OutBoundRequestDto::getOutboundDetailId).collect(Collectors.toList());
        List<OutboundDetail> outboundDetailList = outboundDetailService.listByIds(detailIds);
        List<String> toolIdList = outboundDetailList.stream().map(OutboundDetail::getToolCode).collect(Collectors.toList());
 
        Map<String, BigDecimal> outBoundRequestMap = outBoundRequestList.stream()
                .collect(Collectors.toMap(OutBoundRequestDto::getOutboundDetailId, OutBoundRequestDto::getOutboundQuantity));
        //处理库存台账及台账明细
        Map<String, ToolLedger> toolLedgerMap = toolLedgerService.list(new LambdaQueryWrapper<ToolLedger>().in(ToolLedger::getToolId, toolIdList)).stream()
                .collect(Collectors.toMap(ToolLedger::getToolId, item -> item, (k1, k2) -> k1));
 
        LambdaQueryWrapper<ToolLedgerDetail> queryWrapper = new LambdaQueryWrapper<>();
        for (int i = 0; i < outboundDetailList.size(); i++) {
            if (i > 0) {
                queryWrapper.or();
            }
            OutboundDetail detail = outboundDetailList.get(i);
            queryWrapper.or(wrapper ->
                    wrapper.eq(ToolLedgerDetail::getToolCode, detail.getToolCode())
                            .eq(ToolLedgerDetail::getToolId, detail.getToolId()) //如果不管到把,该字段为空
            );
        }
        List<ToolLedgerDetail> toolLedgerDetailList = toolLedgerDetailService.list(queryWrapper);
        List<ToolLedger> toolLedgerUpdateList = CollectionUtil.newArrayList();
        List<ToolLedgerDetail> toolLedgerDetailUpdateList = CollectionUtil.newArrayList();
        List<OutStoreDetail> outStoreAddList = CollectionUtil.newArrayList();
        List<OutboundDetail> outboundDetailUpdateList = CollectionUtil.newArrayList();
 
        for (OutboundDetail detail : outboundDetailList) {
            //更新库存台账
            ToolLedger toolLedger = toolLedgerMap.get(detail.getToolCode());
            BigDecimal outboundQuantity = outBoundRequestMap.get(detail.getId());
            OutStorehouseType outStorehouseType = OutStorehouseType.getByValue(outboundOrder.getOutStorehouseType());
            switch (outStorehouseType) {
                case TOOL_BORROW:
                    toolLedger.setLendCount(toolLedger.getLendCount().add(outboundQuantity));
                    break;
                case MAINTENANCE_OUTBOUND:
                    toolLedger.setRepairCount(toolLedger.getRepairCount().add(outboundQuantity));
                    break;
                case CALIBRATION_OUTBOUND:
                    toolLedger.setDetectionCount(toolLedger.getDetectionCount().add(outboundQuantity));
                    break;
                case GRINDING_OUTBOUND:
                    toolLedger.setSharpeningCount(toolLedger.getSharpeningCount().add(outboundQuantity));
                    break;
                default:
                    throw new JeecgBootException("未知的出库类型!");
            }
            toolLedgerUpdateList.add(toolLedger);
 
            //更新台账明细
            toolLedgerDetailList.stream().filter(item -> item.getToolCode().equals(detail.getToolCode()) && item.getToolId().equals(detail.getToolId()))
                    .findFirst().ifPresent(item -> {
                        if (StrUtil.isNotBlank(item.getToolId())) {
                            item.setQuantity(BigDecimal.ZERO);
                            switch (outStorehouseType) {
                                case TOOL_BORROW:
                                    item.setStatus(ToolCirculationStatus.BORROWED.getValue());
                                    break;
                                case MAINTENANCE_OUTBOUND:
                                    item.setStatus(ToolCirculationStatus.REPAIRING.getValue());
                                    break;
                                case CALIBRATION_OUTBOUND:
                                    item.setStatus(ToolCirculationStatus.INSPECTING.getValue());
                                    break;
                                case GRINDING_OUTBOUND:
                                    item.setStatus(ToolCirculationStatus.GRINDING.getValue());
                                    break;
                                default:
                                    throw new JeecgBootException("未知的出库类型!");
                            }
                        } else {
                            item.setQuantity(item.getQuantity().subtract(outboundQuantity));
                        }
                        toolLedgerDetailUpdateList.add(item);
                    });
 
            //记录出库流水
            OutStoreDetail outStoreDetail = new OutStoreDetail()
                    .setToolCode(detail.getToolCode())
                    .setToolId(detail.getToolId())
                    .setOutStorehouseType(outboundOrder.getOutStorehouseType())
                    .setGoodsShelvesCode(detail.getOutboundLocation())
                    .setOutNumber(outboundQuantity)
                    .setOutStorehouseId(outboundOrder.getId())
                    .setOperateType("1");//1:按申请单
            outStoreAddList.add(outStoreDetail);
 
            //更新申请单明细
            detail.setOutActualCount(detail.getOutActualCount().add(outboundQuantity));
            detail.setOutboundTime(new Date());
            if (detail.getOutActualCount().compareTo(detail.getOutboundQuantity()) == 0) {
                detail.setStatus(OutBoundStatusEnum.COMPLETED.getValue());
            } else {
                detail.setStatus(OutBoundStatusEnum.PARTIAL_OUTBOUND.getValue());
            }
            outboundDetailUpdateList.add(detail);
        }
        toolLedgerService.updateBatchById(toolLedgerUpdateList);
        toolLedgerDetailService.updateBatchById(toolLedgerDetailUpdateList);
        outStoreDetailService.saveBatch(outStoreAddList);
        outboundDetailService.updateBatchById(outboundDetailUpdateList);
 
        //更新申请单
        boolean allMatch = outboundDetailService.list(new LambdaQueryWrapper<OutboundDetail>()
                        .eq(OutboundDetail::getOutStorehouseId, outboundOrder.getId()))
                .stream().filter(i -> !detailIds.contains(i.getId()))
                .allMatch(i -> i.getStatus().equals(OutBoundStatusEnum.COMPLETED.getValue()));
        List<OutboundDetail> partialOutboundList = outboundDetailUpdateList.stream()
                .filter(i -> !i.getStatus().equals(OutBoundStatusEnum.COMPLETED.getValue())).collect(Collectors.toList());
        if (allMatch && partialOutboundList.isEmpty()) {
            outboundOrder.setOutStatus(OutBoundStatusEnum.COMPLETED.getValue());
        } else {
            outboundOrder.setOutStatus(OutBoundStatusEnum.PARTIAL_OUTBOUND.getValue());
        }
        outboundOrder.setOutboundTime(new Date());
        updateById(outboundOrder);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void outBoundByAdd(List<OutBoundAddDto> boundAddList) {
        //校验台账主表库存数量
        Map<String, BigDecimal> toolBoundQuantityMap = boundAddList.stream()
                .collect(Collectors.groupingBy(OutBoundAddDto::getToolCode,
                        Collectors.mapping(OutBoundAddDto::getOutboundQuantity, Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));
        Map<String, ToolLedger> toolLedgerMap = toolLedgerService.list(new LambdaQueryWrapper<ToolLedger>().in(ToolLedger::getToolId, toolBoundQuantityMap.keySet()))
                .stream().collect(Collectors.toMap(ToolLedger::getToolId, item -> item, (k1, k2) -> k1));
        List<ToolLedger> toolLedgerUpdateList = CollectionUtil.newArrayList();
        for (String toolCode : toolBoundQuantityMap.keySet()) {
            ToolLedger toolLedger = toolLedgerMap.get(toolCode);
            BigDecimal outBoundQuantity = toolBoundQuantityMap.get(toolCode);
            if (Objects.isNull(toolLedger) || toolLedger.getAvailableCount().compareTo(outBoundQuantity) < 0) {
                BaseTools tools = baseToolsService.getById(toolCode);
                throw new JeecgBootException("编码为【" + tools.getToolCode() + "】的工具,库存不足!");
            } else {
                OutStorehouseType outStorehouseType = OutStorehouseType.getByValue(boundAddList.get(0).getOutStorehouseType());
                switch (outStorehouseType) {
                    case TOOL_BORROW:
                        toolLedger.setLendCount(toolLedger.getLendCount().add(outBoundQuantity));
                        break;
                    case MAINTENANCE_OUTBOUND:
                        toolLedger.setRepairCount(toolLedger.getRepairCount().add(outBoundQuantity));
                        break;
                    case CALIBRATION_OUTBOUND:
                        toolLedger.setDetectionCount(toolLedger.getDetectionCount().add(outBoundQuantity));
                        break;
                    case GRINDING_OUTBOUND:
                        toolLedger.setSharpeningCount(toolLedger.getSharpeningCount().add(outBoundQuantity));
                        break;
                    default:
                        throw new JeecgBootException("未知的出库类型!");
                }
                //扣减台账主表可用库存
                toolLedger.setAvailableCount(toolLedger.getAvailableCount().subtract(outBoundQuantity));
                toolLedgerUpdateList.add(toolLedger);
            }
        }
        //校验台账明细库存数量
        Map<String, OutBoundAddDto> boundAddDtoMap = boundAddList.stream().collect(Collectors
                .toMap(OutBoundAddDto::getToolLedgerDetailId, item -> item, (k1, k2) -> k1));
        Map<String, ToolLedgerDetail> toolLedgerDetailMap = toolLedgerDetailService.listByIds(boundAddDtoMap.keySet()).stream()
                .collect(Collectors.toMap(ToolLedgerDetail::getId, item -> item, (k1, k2) -> k1));
        List<ToolLedgerDetail> toolLedgerDetailUpdateList = CollectionUtil.newArrayList();
        for (String toolLedgerDetailId : boundAddDtoMap.keySet()) {
            OutBoundAddDto outBoundAddDto = boundAddDtoMap.get(toolLedgerDetailId);
            BigDecimal outboundQuantity = outBoundAddDto.getOutboundQuantity();
            ToolLedgerDetail toolLedgerDetail = toolLedgerDetailMap.get(toolLedgerDetailId);
            if (Objects.isNull(toolLedgerDetail) || toolLedgerDetail.getQuantity().compareTo(outboundQuantity) < 0) {
                BaseTools tools = baseToolsService.getById(outBoundAddDto.getToolCode());
                throw new JeecgBootException("编码为【" + tools.getToolCode() + "】的工具,库存不足!");
            } else {
                //扣减台账明细库存
                if (StrUtil.isBlank(toolLedgerDetail.getToolId())) {
                    //没有唯一编码,不管到把的
                    toolLedgerDetail.setQuantity(toolLedgerDetail.getQuantity().subtract(outboundQuantity));
                } else {
                    //有唯一编码,管道把的
                    toolLedgerDetail.setQuantity(BigDecimal.ZERO);//数量只会是0和1
                    OutStorehouseType outStorehouseType = OutStorehouseType.getByValue(boundAddList.get(0).getOutStorehouseType());
                    switch (outStorehouseType) {
                        case TOOL_BORROW:
                            toolLedgerDetail.setStatus(ToolCirculationStatus.BORROWED.getValue());
                            break;
                        case MAINTENANCE_OUTBOUND:
                            toolLedgerDetail.setStatus(ToolCirculationStatus.REPAIRING.getValue());
                            break;
                        case CALIBRATION_OUTBOUND:
                            toolLedgerDetail.setStatus(ToolCirculationStatus.INSPECTING.getValue());
                            break;
                        case GRINDING_OUTBOUND:
                            toolLedgerDetail.setStatus(ToolCirculationStatus.GRINDING.getValue());
                            break;
                        default:
                            throw new JeecgBootException("未知的出库类型!");
                    }
                }
                toolLedgerDetailUpdateList.add(toolLedgerDetail);
            }
        }
        toolLedgerService.updateBatchById(toolLedgerUpdateList);
        toolLedgerDetailService.updateBatchById(toolLedgerDetailUpdateList);
        //记录出库流水
        List<OutStoreDetail> outStoreAddList = CollectionUtil.newArrayList();
        for (OutBoundAddDto outBoundAddDto : boundAddList) {
            OutStoreDetail outStoreDetail = new OutStoreDetail()
                    .setToolCode(outBoundAddDto.getToolCode())
                    .setToolId(outBoundAddDto.getToolId())
                    .setOutStorehouseType(outBoundAddDto.getOutStorehouseType())
                    .setGoodsShelvesCode(outBoundAddDto.getOutboundLocation())
                    .setOutNumber(outBoundAddDto.getOutboundQuantity())
                    .setOperateType("2");//2:手工操作
            outStoreAddList.add(outStoreDetail);
        }
        outStoreDetailService.saveBatch(outStoreAddList);
    }
 
 
    private boolean fromOneApply(List<OutBoundRequestDto> outBoundRequestList) {
        long count = outBoundRequestList.stream().map(OutBoundRequestDto::getOutBoundOrderId).distinct().count();
        if (count > 1) {
            return false;
        }
        List<String> outDetailIds = outBoundRequestList.stream().map(OutBoundRequestDto::getOutboundDetailId).collect(Collectors.toList());
        String outboundDetailId = outBoundRequestList.get(0).getOutboundDetailId();
        OutboundDetail outboundDetail = outboundDetailService.getById(outboundDetailId);
        List<String> detailIds = outboundDetailService.list(new LambdaQueryWrapper<OutboundDetail>()
                .eq(OutboundDetail::getOutStorehouseId, outboundDetail.getOutStorehouseId())).stream()
                .map(OutboundDetail::getId).collect(Collectors.toList());
        return new HashSet<>(detailIds).containsAll(outDetailIds);
    }
 
    private boolean readyToOutbound(List<OutBoundRequestDto> outBoundRequestList) {
        String outBoundOrderId = outBoundRequestList.get(0).getOutBoundOrderId();
        OutboundOrder outboundOrder = getById(outBoundOrderId);
        return OutBillStatus.APPROVED.getValue().equals(outboundOrder.getOrderStatus());
    }
 
    public boolean triggerProcess(OutboundOrder outboundOrder) {
        flowCommonService.initActBusiness("单号为:" + outboundOrder.getOutNum() + " 的出库申请,开始进行审批",
                outboundOrder.getId(), "outboundOrderServiceImpl", "tool_out_storage", null);
        Map<String, Object> variables = new HashMap<>();
        variables.put("dataId", outboundOrder.getId());
        if (StrUtil.isEmpty(outboundOrder.getRemark())) {
            variables.put("organization", "新增出库申请单默认启动流程");
            variables.put("comment", "新增出库申请单默认启动流程");
        } else {
            variables.put("organization", outboundOrder.getRemark());
            variables.put("comment", outboundOrder.getRemark());
        }
        variables.put("proofreading", true);
        List<String> usernames = new ArrayList<>();
        usernames.add(outboundOrder.getReviewer());
        variables.put("NextAssignee", usernames);
        Result result = flowDefinitionService.startProcessInstanceByKey("tool_out_storage", variables);
        return result.isSuccess();
    }
 
    private LoginUser getCurrentUser() {
        // 获取当前认证的登录用户信息
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser != null && currentUser.isAuthenticated()) {
            Object principal = currentUser.getPrincipal();
            if (principal instanceof LoginUser) {
                return (LoginUser) principal;
            }
        }
        return null;
    }
 
    private FlowMyBusiness getFlowMyBusiness(String instanceId) {
        List<FlowMyBusiness> businessList = flowMyBusinessService.list(
                new LambdaQueryWrapper<FlowMyBusiness>().eq(FlowMyBusiness::getProcessInstanceId, instanceId));
        return businessList.isEmpty() ? null : businessList.get(0);
    }
 
    private boolean isUserAuthorized(FlowMyBusiness flowMyBusiness, LoginUser user) {
        List<String> todoUsers = JSON.parseArray(flowMyBusiness.getTodoUsers(), String.class);
        return todoUsers != null && todoUsers.contains(user.getUsername());
    }
 
    private boolean claimTask(String taskId, LoginUser user) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task == null) {
            return false;
        }
        if (task.getAssignee() != null && !task.getAssignee().equals(user.getUsername())) {
            return false;
        }
        taskService.claim(taskId, user.getUsername());
        return true;
    }
 
    private void setupProcessVariables(OutBoundOrderFlowDto outBoundOrderFlowDto, OutboundOrder outboundOrder, LoginUser user) {
        if (OutBillStatus.SUBMITTED.getValue().equals(outboundOrder.getOrderStatus()) && user.getUsername().equals(outboundOrder.getReviewer())) {
            Map<String, Object> values = new HashMap<>();
            values.put("dataId", outboundOrder.getId());
            values.put("organization", outBoundOrderFlowDto.getApprovalOpinion());
            values.put("comment", outBoundOrderFlowDto.getApprovalOpinion());
            values.put("status", outBoundOrderFlowDto.getStatus());
            values.put("NextAssignee", Collections.singletonList(outboundOrder.getReviewer()));
            outBoundOrderFlowDto.setValues(values);
        }
    }
 
    @Override
    public void afterFlowHandle(FlowMyBusiness business) {
        business.getTaskNameId();//接下来审批的节点
        business.getValues();//前端传进来的参数
        business.getActStatus();
    }
 
    @Override
    public Object getBusinessDataById(String dataId) {
        return this.getById(dataId);
    }
 
    @Override
    public Map<String, Object> flowValuesOfTask(String taskNameId, Map<String, Object> values) {
        return Collections.emptyMap();
    }
 
    @Override
    public List<String> flowCandidateUsernamesOfTask(String taskNameId, Map<String, Object> values) {
        //业务是否干预流程,业务干预,流程干预,指定人员进行处理
        //获取下一步处理人
        Object object = values.get("NextAssignee");
        return (List<String>) object;
    }
}