Fixiaobai
2023-11-07 940f06f6d8e5508f39bd7f8ce7791d60bfc0686c
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
/*
 *    Copyright (c) 2018-2025, ztt All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: ztt
 */
package com.chinaztt.mes.technology.service.impl;
 
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinaztt.mes.basic.entity.Part;
import com.chinaztt.mes.basic.mapper.PartMapper;
import com.chinaztt.mes.common.handler.StateMachineHandler;
import com.chinaztt.mes.common.numgen.NumberGenerator;
import com.chinaztt.mes.common.util.StateResult;
import com.chinaztt.mes.technology.dto.BomDTO;
import com.chinaztt.mes.technology.dto.StructureTree;
import com.chinaztt.mes.technology.entity.*;
import com.chinaztt.mes.technology.excel.BomData;
import com.chinaztt.mes.technology.mapper.*;
import com.chinaztt.mes.technology.service.BomService;
import com.chinaztt.mes.technology.state.bom.BomStateMachineConfig;
import com.chinaztt.mes.technology.state.bom.constant.BomEvents;
import com.chinaztt.mes.technology.state.bom.constant.BomStateStringValues;
import com.chinaztt.mes.technology.state.bom.constant.BomStates;
import com.chinaztt.ztt.common.core.util.R;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.config.StateMachineFactory;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
 
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
 
/**
 * 完整bom树
 *
 * @author zhangxy
 * @date 2021-05-07 15:08:17
 */
@Service
@AllArgsConstructor
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class BomServiceImpl extends ServiceImpl<BomMapper, Bom> implements BomService {
 
    private NumberGenerator<Bom> numberGenerator;
 
    /**
     * 随机ID,前端用
     */
    public volatile static long RANDOM_ID = 0;
 
    /**
     * 循环层级,最多10层防止出现死循环
     */
    public static final int CYCLE_DEEP = 10;
 
    private PartMapper partMapper;
 
    private OperationMapper operationMapper;
 
    private StructureMapper structureMapper;
 
    private BomComponentMapper bomComponentMapper;
 
    private StructureComponentMapper structureComponentMapper;
 
    private StateMachineFactory<BomStates, BomEvents> bomStateMachineFactory;
 
    private StateMachinePersister<BomStates, BomEvents, Bom> persister;
 
 
    @Override
    public void importExcel(List<BomData> list) {
        if (CollectionUtil.isEmpty(list)) {
            return;
        }
        for (BomData data : list) {
            Bom bom = new Bom();
            bom.setInsulationColor(data.getInsulationColor());
            bom.setSheathColor(data.getSheathColor());
            bom.setCharacteristicOne(data.getCharacteristicOne());
            String partNo = data.getPartNo();
            if (StringUtils.isBlank(data.getPartNo()) || StringUtils.isBlank(data.getVersion())) {
                log.error("bom导入:" + data + "零件号为空");
                continue;
            }
            //零件号和版本号查询唯一
            Part part = partMapper.selectOne(Wrappers.<Part>lambdaQuery()
                    .eq(Part::getPartNo, partNo).eq(Part::getEngChgLevel, data.getVersion()));
            if (null == part) {
                log.error("bom导入 :" + data + "零件不存在");
                continue;
            }
            bom.setPartId(part.getId());
            bom.setVersion(data.getVersion());
            bom.setNumber(numberGenerator.generateNumberWithPrefix(Bom.DIGIT, Bom.PREFIX, Bom::getNumber));
            bom.setState(BomStateStringValues.DRAFT);
            baseMapper.insert(bom);
            //查询构建树数据
            saveBomComp(getAllBomExt(bom, 999), bom);
        }
    }
 
 
    @Override
    public IPage<List<BomDTO>> getPage(Page page, QueryWrapper<BomDTO> ew) {
        return baseMapper.getBomPage(page, ew);
    }
 
    @Override
    public R<BomDTO> saveBom(BomDTO bomDTO) {
        Bom bom = new Bom();
        BeanUtils.copyProperties(bomDTO, bom);
        if (StringUtils.isBlank(bom.getNumber())) {
            bom.setNumber(numberGenerator.generateNumberWithPrefix(Bom.DIGIT, Bom.PREFIX, Bom::getNumber));
        }
        bom.setState(BomStateStringValues.DRAFT);
        baseMapper.insert(bom);
        saveBomComp(bomDTO.getTree(), bom);
        return R.ok(getBomDtoById(bom.getId()));
    }
 
    /**
     * @Author: Hans
     * @Description: 根据产品结构保存所有BOM
     * @Date: 2022-06-01
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public R<Boolean> saveALLBom(List<Structure> structures) {
        structures.forEach(structure -> {
//            Structure structure = structures.get(i);
            Bom bom = new Bom();
            bom.setPartId(structure.getPartId());
            bom.setBomTypeDb(structure.getBomTypeDb());
            bom.setVersion(structure.getVersion());
            bom.setAlternativeNo(structure.getAlternativeNo());
            bom.setAlternativeDesc(structure.getAlternativeDesc());
            //log.info("第一层========================》"+bom);
            StructureTree tree = getAllBomExt(bom, 999);
            BomDTO bomDTO = new BomDTO();
            BeanUtils.copyProperties(bom, bomDTO);
            bomDTO.setTree(tree);
            //BomDTO bomDTO = getBomDtoById(structure.getPartId());
            log.info("bomDto============>"+bomDTO);
            saveBom(bomDTO);
        });
        return R.ok();
    }
 
    //插入头BomComp
    @Override
    public void saveBomComp(StructureTree structureTree, Bom bom) {
        BomComponent bomComp = new BomComponent();
        bomComp.setParentStructureId(structureTree.getStructureId());
        bomComp.setQpa(structureTree.getQpa());
        bomComp.setOriginalQpa(structureTree.getOriginalQpa());
        bomComp.setUnit(structureTree.getUnit());
        bomComp.setPartId(structureTree.getPartId());
        bomComp.setBomId(bom.getId());
        bomComp.setPlanningMethod(structureTree.getPlanningMethod());
        bomComp.setColor(structureTree.getColor());
        bomComp.setOperationId(structureTree.getOperationId());
 
        bomComp.setSharpenerNo(structureTree.getSharpenerNo());
        bomComp.setCaveNum(structureTree.getCaveNum());
        bomComp.setGramWeight(structureTree.getGramWeight());
        bomComp.setGateGramWeight(structureTree.getGateGramWeight());
        bomComp.setMoldingCycle(structureTree.getMoldingCycle());
        bomComp.setMachine(structureTree.getMachine());
        bomComp.setScale(structureTree.getScale());
        bomComp.setDryingTime(structureTree.getDryingTime());
        bomComp.setDryingTemperature(structureTree.getDryingTemperature());
        bomComp.setPackingInfo(structureTree.getPackingInfo());
 
        bomComponentMapper.insert(bomComp);
        saveChildren(structureTree.getChildren(), bomComp.getId(), bom, structureTree.getPartId());
    }
 
    @Override
    public R<Boolean> updateBom(BomDTO bomDTO) {
        Bom bom = new Bom();
        BeanUtils.copyProperties(bomDTO, bom);
        baseMapper.updateById(bom);
        bomComponentMapper.delete(Wrappers.<BomComponent>lambdaQuery().eq(BomComponent::getBomId, bomDTO.getId()));
        saveBomComp(bomDTO.getTree(), bom);
        return R.ok();
    }
 
    /**
     * @param children     子节点list
     * @param parentId     父节点id
     * @param bom          根BOM
     * @param parentPartId 父节点的零件号
     */
    private void saveChildren(List<StructureTree> children, Long parentId, Bom bom, Long parentPartId) {
        if (CollectionUtil.isEmpty(children)) {
            return;
        }
        Part parentPart = partMapper.selectById(parentPartId);
        log.error("parentId=======>"+parentPartId);
        log.error("bomParentId====>"+bom);
        ////"P" 虚拟件的意思 在一个BOM中,除根节点外,其余节点若不是虚拟件(零件【计划方法】不为P 和 K),则禁止为其增加子件。
        //if (!bom.getPartId().equals(parentPartId)) {
        //    if (!"P".equals(parentPart.getPlanningMethod()) && !"K".equals(parentPart.getPlanningMethod())) {
        //        throw new RuntimeException(parentPart.getPartNo() + parentPart.getPartName() + "为非虚拟件,不可添加子件");
        //    }
        //}
        for (StructureTree child : children) {
            BomComponent bomComp = new BomComponent();
            bomComp.setQpa(child.getQpa());
            bomComp.setParentStructureId(child.getStructureId());
            bomComp.setOriginalQpa(child.getOriginalQpa());
            bomComp.setUnit(child.getUnit());
            bomComp.setPartId(child.getPartId());
            bomComp.setParent(parentId);
            bomComp.setBomId(bom.getId());
            bomComp.setOperationId(child.getOperationId());
            bomComp.setPlanningMethod(child.getPlanningMethod());
            bomComp.setDiscNum(child.getDiscNum());
 
            bomComp.setSharpenerNo(child.getSharpenerNo());
            bomComp.setCaveNum(child.getCaveNum());
            bomComp.setGramWeight(child.getGramWeight());
            bomComp.setGateGramWeight(child.getGateGramWeight());
            bomComp.setMoldingCycle(child.getMoldingCycle());
            bomComp.setMachine(child.getMachine());
            bomComp.setScale(child.getScale());
            bomComp.setDryingTime(child.getDryingTime());
            bomComp.setDryingTemperature(child.getDryingTemperature());
            bomComp.setPackingInfo(child.getPackingInfo());
 
            bomComponentMapper.insert(bomComp);
            saveChildren(child.getChildren(), bomComp.getId(), bom, child.getPartId());
        }
    }
 
    /**
     * @author hans
     * @date 2022-5-24
     * 添加bomLayers,设置BOM默认递归查询层数
     */
    @Override
    public StructureTree getAllBomExt(Bom bom, int bomLayers) {
        log.info("生成树=======》");
        Long partId = bom.getPartId();
        String version = bom.getVersion();
        String alternativeNo = bom.getAlternativeNo();
        String bomType = bom.getBomTypeDb();
        // 判断获取BOM的三个关键字段是否为空
        if (null == partId || version == null || alternativeNo == null) {
            return null;
        }
        if (RANDOM_ID >= Integer.MAX_VALUE) {
            RANDOM_ID = 0;
        }
        // 获取BOM根节点
        StructureTree root = getRootNode(partId);
        //通过产品结构查工序
        Map<Long, Integer> cache = new HashMap<>(80);
        getStructureByPartId(root, partId, cache, version, alternativeNo, bomType, bomLayers);
        return root;
    }
 
    /**
     * @Author: Hans
     * @Description: 获取BOM根节点
     * @Date: 2022-06-01
     */
    private StructureTree getRootNode(Long partId) {
        log.info("获取bom根节点====》"+partId);
        Part part = partMapper.selectById(partId);
        log.info("父级零件====》"+part);
        StructureTree root = new StructureTree();
        root.setPartName(part.getPartName());
        root.setPlanningMethod(part.getPlanningMethod());
        root.setPartId(part.getId());
        root.setQpa(BigDecimal.ONE);
        root.setOriginalQpa(BigDecimal.ONE);
        root.setId(++RANDOM_ID);
        root.setParentId(0L);
        root.setExpand(true);
        root.setStructureId(0L);
        root.setUnit(part.getUnit());
        root.setChecked(false);
 
        return root;
    }
 
    /**
     * @Author: Hans
     * @Description: 通过零件ID查询所有版本和替代的BOM
     * @Date: 2022-06-02
     */
    @Override
    public StructureTree getAllBomByPartId(Long partId) {
        if (RANDOM_ID >= Integer.MAX_VALUE) {
            RANDOM_ID = 0;
        }
        Part part = partMapper.selectById(partId);
        StructureTree root = new StructureTree();
        root.setPartName(part.getPartName());
        root.setPartId(part.getId());
        root.setPartNo(part.getPartNo());
        root.setQpa(BigDecimal.ONE);
        root.setOriginalQpa(BigDecimal.ONE);
        root.setId(++RANDOM_ID);
        root.setParentId(0L);
        root.setExpand(true);
        root.setStructureId(0L);
        root.setUnit(part.getUnit());
        root.setChecked(false);
        //通过产品结构查工序
        Map<Long, Integer> cache = new HashMap<>(80);
        // 版本version为ALL:查询所有版本的产品结构,替代为ALL:查询所有替代的产品结构
        getStructureByPartId(root, partId, cache, "ALL", "ALL", null, 999);
        return root;
    }
 
    public Bom copyBom(Long id) {
        Bom bom = baseMapper.selectById(id);
        bom.setNumber(numberGenerator.generateNumberWithPrefix(Bom.DIGIT, Bom.PREFIX, Bom::getNumber));
        List<BomComponent> bomCompList = bomComponentMapper.selectList(Wrappers.<BomComponent>lambdaQuery().eq(BomComponent::getBomId, id));
        baseMapper.insert(bom);
        if (CollectionUtil.isNotEmpty(bomCompList)) {
            for (BomComponent bomComponent : bomCompList) {
                bomComponent.setBomId(bom.getId());
                bomComponentMapper.insert(bomComponent);
            }
        }
        return bom;
    }
 
    @Override
    public BomDTO getBomDtoById(Long id) {
        Bom bom = baseMapper.selectById(id);
        log.info("getBomDtoById=>>>"+bom);
        //如果存在未绑定工序的 工艺路线 则会为空
        List<StructureTree> nodes = baseMapper.getBomComponents4Tree(id);
        if (CollectionUtil.isEmpty(nodes)) {
            return null;
        }
        StructureTree root = nodes.stream().filter(e -> e.getParentId() == null || e.getParentId() == 0).findFirst().get();
        log.info("root=======>"+root);
        setChildren(root, nodes);
        log.info("setChildren后========》"+root);
        Part part = partMapper.selectById(bom.getPartId());
        BomDTO bomDto = new BomDTO();
        BeanUtils.copyProperties(bom, bomDto);
        bomDto.setTree(root);
        bomDto.setPartName(part.getPartName());
        bomDto.setPartNo(part.getPartNo());
        return bomDto;
    }
 
 
    private void setChildren(StructureTree node, List<StructureTree> list) {
        List<StructureTree> children = list.stream().filter(e -> e.getParentId() != null && e.getParentId().equals(node.getId())).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(children)) {
            return;
        }
        node.setChildren(children);
        children.forEach(e -> {
            setChildren(e, list);
        });
    }
 
    @Override
    public R<Boolean> delete(List<Long> ids) {
        for (Long id : ids) {
            bomComponentMapper.delete(Wrappers.<BomComponent>lambdaQuery().eq(BomComponent::getBomId, id));
        }
        baseMapper.deleteBatchIds(ids);
        return R.ok();
    }
 
    @Override
    public List<BomComponent> getComponentsById(Long bomId) {
        return bomComponentMapper.selectList(Wrappers.<BomComponent>lambdaQuery().eq(BomComponent::getBomId, bomId));
    }
 
    @Override
    public boolean changeState(List<Long> ids, String event) {
        for (Long id : ids) {
            Bom bom = baseMapper.selectById(id);
            Message<BomEvents> message = MessageBuilder.withPayload(BomEvents.valueOf(event)).setHeader("bom", bom).build();
            StateMachineHandler handler = new StateMachineHandler(bomStateMachineFactory, persister, BomStateMachineConfig.MACHINE_ID, bom);
            StateResult res = handler.sendEvent(message, bom.getId());
            if (!res.isSuccess()) {
                throw new RuntimeException(res.getMsg());
            }
        }
        return true;
    }
 
    /*private void getStructureByPartId(StructureTree parent, Long partId, Map<Long, Integer> cache, int bomLayers) {
        Integer cycleCount = cache.get(partId) == null ? 0 : cache.get(partId);
        if (cycleCount >= CYCLE_DEEP) {
            return;
        } else {
            cache.put(partId, cycleCount + 1);
        }
        //根据零件找到结构主表
        List<Structure> structures = structureMapper.selectList(Wrappers.<Structure>lambdaQuery().eq(Structure::getPartId, partId));
        if (CollectionUtil.isNotEmpty(structures)) {
            for (Structure s : structures) {
                List<StructureComponent> components = structureComponentMapper.selectList(Wrappers.<StructureComponent>lambdaQuery().eq(StructureComponent::getStructureId, s.getId())
                        .orderByAsc(StructureComponent::getId));
                if (CollectionUtil.isEmpty(components)) {
                    return;
                }
                BigDecimal parentQpa = parent.getQpa();
                List<StructureTree> children = parent.getChildren() == null ? new ArrayList<>() : parent.getChildren();
 
                // 遍历一层减少一层
                bomLayers--;
                for (StructureComponent c : components) {
                    Part part = partMapper.selectById(c.getPartId());
                    Operation operation = operationMapper.selectById(c.getOperationId());
                    if (part == null) {
                        continue;
                    }
                    StructureTree child = new StructureTree();
                    child.setId(++RANDOM_ID);
                    child.setParentId(parent.getId());
                    child.setCompId(c.getId());
                    child.setStructureId(s.getId());
                    child.setPartId(c.getPartId());
                    child.setPartNo(part.getPartNo());
                    child.setPartName(part.getPartName());
                    child.setExpand(true);
                    child.setUnit(part.getUnit());
                    child.setChecked(false);
                    child.setQpa(c.getQpa().multiply(parentQpa).setScale(8, BigDecimal.ROUND_HALF_UP));
                    child.setOriginalQpa(c.getQpa());
                    child.setDiscNum(null == c.getDiscNum() ? null : c.getDiscNum());
                    if (null != operation) {
                        child.setOperationId(operation.getId());
                        child.setOperationNo(operation.getOperationNo());
                        child.setOperationName(operation.getName());
                    }
                    // 判断到第几层了
                    if (bomLayers > 0)
                        getStructureByPartId(child, c.getPartId(), cache, bomLayers);
                    children.add(child);
                }
                parent.setChildren(children);
            }
        }
    }*/
 
    /**
     * @Author: Hans
     * @Description: 查询root节点
     * @Date: 2022-06-02
     */
    private List<Structure> getRootNodes(Long partId, String version, String alternativeNo, String bomType) {
        List<Structure> structures = null;
        if (version.equals("ALL") && alternativeNo.equals("ALL")) {
            // 根据零件号查询
            structures = structureMapper.selectList(Wrappers.<Structure>lambdaQuery().eq(Structure::getPartId,
                    partId).eq(StringUtils.isNotBlank(bomType), Structure::getBomTypeDb, bomType));
        } else if (alternativeNo.equals("ALL")) {
            // 根据零件号、版本号查询
            structures = structureMapper.selectList(Wrappers.<Structure>lambdaQuery().eq(Structure::getPartId, partId).
                    eq(Structure::getVersion, version).eq(StringUtils.isNotBlank(bomType), Structure::getBomTypeDb,
                    bomType));
        } else if (version.equals("ALL")) {
            // 根据零件号、替代号查询
            structures = structureMapper.selectList(Wrappers.<Structure>lambdaQuery().eq(Structure::getPartId, partId).
                    eq(Structure::getAlternativeNo, alternativeNo).eq(StringUtils.isNotBlank(bomType),
                    Structure::getBomTypeDb, bomType));
        } else {
            // 根据零件号、版本号、替代号查询
            structures = structureMapper.selectList(Wrappers.<Structure>lambdaQuery()
                    .eq(Structure::getPartId, partId)
                    .eq(Structure::getVersion, version)
                    .eq(Structure::getAlternativeNo, alternativeNo)
                    .eq(StringUtils.isNotBlank(bomType), Structure::getBomTypeDb, bomType));
        }
        return structures;
    }
 
    /**
     * @Author: Hans
     * @Description: 填充BOM树
     * @Date: 2022-06-02
     */
    private void fillBomTree() {
 
    }
 
    /**
     * @Author: Hans
     * @Description: 填充child节点数据
     * @Date: 2022-06-02
     */
    private StructureTree fillChildNode(StructureTree parent, StructureComponent component, Structure structure, Part part) {
        StructureTree child = new StructureTree();
        Operation operation = operationMapper.selectById(component.getOperationId());
        BigDecimal parentQpa = parent.getQpa();
        child.setId(++RANDOM_ID);
        child.setParentId(parent.getId());
        child.setCompId(component.getId());
        child.setStructureId(structure.getId());
        child.setPartId(component.getPartId());
        child.setColor(component.getColor());
 
        child.setSharpenerNo(component.getSharpenerNo());
        child.setCaveNum(component.getCaveNum());
        child.setGramWeight(component.getGramWeight());
        child.setGateGramWeight(component.getGateGramWeight());
        child.setMoldingCycle(component.getMoldingCycle());
        child.setMachine(component.getMachine());
        child.setScale(component.getScale());
        child.setDryingTime(component.getDryingTime());
        child.setDryingTemperature(component.getDryingTemperature());
        child.setPackingInfo(component.getPackingInfo());
 
        child.setPartNo(part.getPartNo());
        child.setPartName(part.getPartName());
        child.setExpand(true);
        child.setUnit(part.getUnit());
        child.setPlanningMethod(component.getPlanningMethod());
        child.setChecked(false);
        child.setQpa(component.getQpa().multiply(parentQpa).setScale(8, BigDecimal.ROUND_HALF_UP));
        child.setOriginalQpa(component.getQpa());
        child.setDiscNum(null == component.getDiscNum() ? null : component.getDiscNum());
        if (null != operation) {
            child.setOperationId(operation.getId());
            child.setOperationNo(operation.getOperationNo());
            child.setOperationName(operation.getName());
        }
 
        return child;
    }
 
    /**
     * @Author: Hans
     * @Description: 重写获取产品结构方法
     * @Date: 2022-06-02
     */
    private void getStructureByPartId(StructureTree parent, Long partId, Map<Long, Integer> cache, String version,
                                      String alternativeNo, String bomType, int bomLayers) {
        log.info("每层树===================》"+parent);
        Integer cycleCount = cache.get(partId) == null ? 0 : cache.get(partId);
        if (cycleCount >= CYCLE_DEEP) {
            return;
        } else {
            cache.put(partId, cycleCount + 1);
        }
        //根据零件找到结构主表
        List<Structure> structures = getRootNodes(partId, version, alternativeNo, bomType);
        log.info("得到结构=========》"+structures);
        if (CollectionUtil.isNotEmpty(structures)) {
            for (Structure structure : structures) {
 
                parent.setSharpenerNo(structure.getSharpenerNo());
                parent.setCaveNum(structure.getCaveNum());
                parent.setGramWeight(structure.getGramWeight());
                parent.setGateGramWeight(structure.getGateGramWeight());
                parent.setMoldingCycle(structure.getMoldingCycle());
                parent.setMachine(structure.getMachine());
                parent.setScale(structure.getScale());
                parent.setDryingTime(structure.getDryingTime());
                parent.setDryingTemperature(structure.getDryingTemperature());
                parent.setPackingInfo(structure.getPackingInfo());
 
                // 查询BOM子节点
                List<StructureComponent> components = structureComponentMapper.selectList(Wrappers.<StructureComponent>lambdaQuery().
                        eq(StructureComponent::getStructureId, structure.getId())
                        .orderByAsc(StructureComponent::getId));
                if (CollectionUtil.isEmpty(components)) {
                    return;
                }
                List<StructureTree> children = parent.getChildren() == null ? new ArrayList<>() : parent.getChildren();
                // 遍历一层减少一层,999代表不做限制可以一直递归
                if (bomLayers < 999) {
                    bomLayers--;
                }
                for (StructureComponent component : components) {
                    Part part = partMapper.selectById(component.getPartId());
                    if (part == null) {
                        continue;
                    }
                    // 填充child节点数据
                    StructureTree child = fillChildNode(parent, component, structure, part);
                    log.info("节点数据====================》"+child);
                    if (bomLayers == 999) {
                        getStructureByPartId(child, component.getPartId(), cache, "ALL", "ALL", bomType, bomLayers);
                        // 判断到第几层了,制造类型为1-已制造,计划方法为P-虚拟件
                    } else if (bomLayers > 0 && (part.getMaterialType().equals("1") && !part.getPlanningMethod().equals(
                            "A"))) {
                        getStructureByPartId(child, component.getPartId(), cache, "ALL", "ALL", bomType, bomLayers);
                    }
                    children.add(child);
                }
                parent.setChildren(children);
            }
        }
    }
}