李林
2023-10-07 658d4927d468c47208fd012d9128b09249c07eff
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
package com.chinaztt.mes.service.impl;
 
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chinaztt.mes.basic.dto.ParamDTO;
import com.chinaztt.mes.basic.entity.*;
import com.chinaztt.mes.basic.mapper.*;
import com.chinaztt.mes.basic.util.DictUtils;
import com.chinaztt.mes.common.numgen.NumberGenerator;
import com.chinaztt.mes.dto.ParamReveiveDTO;
import com.chinaztt.mes.dto.ProductTreeDTO;
import com.chinaztt.mes.dto.StructureDTO;
import com.chinaztt.mes.mapper.PocMapper;
import com.chinaztt.mes.plan.dto.CustomerOrderDTO;
import com.chinaztt.mes.plan.dto.ManufacturingOrderDTO;
import com.chinaztt.mes.plan.dto.MasterProductionScheduleTheoryQuantityDTO;
import com.chinaztt.mes.plan.entity.Customer;
import com.chinaztt.mes.plan.entity.CustomerOrder;
import com.chinaztt.mes.plan.entity.JoinModelCustomer;
import com.chinaztt.mes.plan.entity.MasterProductionSchedule;
import com.chinaztt.mes.plan.mapper.*;
import com.chinaztt.mes.plan.service.CustomerOrderService;
import com.chinaztt.mes.plan.service.CustomerService;
import com.chinaztt.mes.plan.service.ManufacturingOrderService;
import com.chinaztt.mes.plan.service.MasterProductionScheduleService;
import com.chinaztt.mes.plan.state.auditstate.constant.AuditStateStringValues;
import com.chinaztt.mes.plan.state.orderstate.constant.CustomerOrderStateStringValues;
import com.chinaztt.mes.production.dto.OperationTaskDTO;
import com.chinaztt.mes.production.entity.OperationTask;
import com.chinaztt.mes.production.mapper.OperationTaskMapper;
import com.chinaztt.mes.production.service.OperationTaskService;
import com.chinaztt.mes.service.PocService;
import com.chinaztt.mes.technology.dto.BomDTO;
import com.chinaztt.mes.technology.dto.RoutingDTO;
import com.chinaztt.mes.technology.dto.StructureTree;
import com.chinaztt.mes.technology.entity.*;
import com.chinaztt.mes.technology.mapper.*;
import com.chinaztt.mes.technology.service.BomService;
import com.chinaztt.mes.technology.service.DocumentService;
import com.chinaztt.mes.technology.service.RoutingService;
import com.chinaztt.mes.technology.state.bom.constant.BomStates;
import com.chinaztt.mes.technology.state.document.constant.DocumentStateStringValues;
import com.chinaztt.mes.technology.state.routing.constant.RoutingStates;
import com.chinaztt.ztt.admin.api.entity.SysDictItem;
import com.sun.corba.se.spi.orbutil.threadpool.Work;
import lombok.AllArgsConstructor;
import lombok.CustomLog;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.print.Doc;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
 
/**
 * @author xucg
 * @date 2023-08-17
 * @apiNote
 */
@Service
@AllArgsConstructor
@Transactional
public class PocServiceImpl implements PocService {
 
    private BomMapper bomMapper;
    private BomService bomService;
    private BasicParamTemplateMapper basicParamTemplateMapper;
    private CustomerMapper customerMapper;
    private CustomerOrderMapper customerOrderMapper;
    private CustomerOrderService customerOrderService;
    private CustomerService customerService;
    private DocumentService documentService;
    private MasterProductionScheduleTheoryQuantityMapper masterProductionScheduleTheoryQuantityMapper;
    private MasterProductionScheduleMapper masterProductionScheduleMapper;
    private ManufacturingOrderService manufacturingOrderService;
    private OperationMapper operationMapper;
    private OperationTaskMapper operationTaskMapper;
    private OperationJoinTemplateMapper operationJoinTemplateMapper;
    private OperationTaskService operationTaskService;
    private PartMapper partMapper;
    private ParamMapper paramMapper;
    private PocMapper pocMapper;
    private ParamJoinTemplateMapper paramJoinTemplateMapper;
    private RoutingMapper routingMapper;
    private RoutingService routingService;
    private RoutingOperationMapper routingOperationMapper;
    private StructureMapper structureMapper;
    private StructureComponentMapper structureComponentMapper;
    private LocationMapper locationMapper;
    private NumberGenerator<Bom> bomNumberGenerator;
    private NumberGenerator<Document> documentNumberGenerator;
    private NumberGenerator<MasterProductionSchedule> masterProductionScheduleNumberGenerator;
    private NumberGenerator<Routing> routingNumberGenerator;
    private NumberGenerator<Template> templateNumberGenerator;
    private JoinModelCustomerMapper joinModelCustomerMapper;
    private WorkstationMapper workstationMapper;
 
    /**
     * 生产bom 添加零件 添加工序的混合个功能
     *
     * @param productTreeDTO 传入的零件参数
     */
    @Override
    public void fullSave(ProductTreeDTO productTreeDTO) {
        //新增的产品结构 用于等会生成bom
        List<StructureDTO> newStructureList = new ArrayList<>();
        //零件,工序,产品结构的自动添加
        Part partRoot = fullSave(new Part(), newStructureList, null, productTreeDTO, null, null);
        //生成BOM
        saveBomByStructure(newStructureList);
        //生成工艺文件
        Document document = documentSave(partRoot);
        //生成销售订单
        saveCustomer(partRoot, document);
 
    }
 
    /**
     * 生产bom 添加零件 添加工序的混合个功能
     *
     * @param partRoot         根零件
     * @param newStructureList 保存新增的产品结构 用于新增BOM
     * @param structureFather  父零件的产品结构
     * @param productTreeDTO   传入的零件参数
     * @param ct               时间
     * @param le               层级
     */
    private Part fullSave(Part partRoot, List<StructureDTO> newStructureList, StructureDTO structureFather, ProductTreeDTO productTreeDTO, LocalDateTime ct, Integer le) {
        //零件名称识别
        le = le == null ? 1 : le + 1;
        List<String> partNameList = new ArrayList<>();
        if (partNameList.contains(productTreeDTO.getPartName())) {
            productTreeDTO.setPartName(productTreeDTO.getPartName() + "-" + le);
        }
        //用来创建零件编号 因为系统零件编号是手动填入的 所以需要系统生成一个
        ct = ct == null ? LocalDateTime.now() : ct;
        //零件
        Part part = partSave(ct, productTreeDTO, le);
        //如果有子节点就创建个产品结构主表
        if (null != structureFather) {
            strcutureChildSave(structureFather, productTreeDTO, part);
        }
        //定义一个产品结构
        StructureDTO structure = null;
        //如果有子节点就生成一个新的产品结构
        if (CollectionUtils.isNotEmpty(productTreeDTO.getChildren())) {
            structure = strcutureSave(part);
            //看是不是最后一道工序如果 le == 1 就是最后一道工序
            if (le == 1) {
                //需要将根零件返回出来
                partRoot = part;
                structure.setIsLast(true);
            }
            //设置执行的次数
            structure.setLe(le);
            //将新增的产品结构添加到list中
            newStructureList.add(structure);
            //产出工序当前工序
            Operation operation = operationSave(ct, productTreeDTO, le);
            //这边转一下
            if (CollectionUtils.isNotEmpty(productTreeDTO.getParamList())) {
                productTreeDTO.setOperationParams(productTreeDTO.getParamList().stream().map(ParamReveiveDTO::getName).collect(Collectors.toList()));
            }
            //将参数传到后面去
            structure.setOperationParams(productTreeDTO.getOperationParams());
            //填入产出工序
            structure.setChildComOp(operation);
        }
        //递归执行当前方法
        if (null != productTreeDTO.getChildren()) {
            for (ProductTreeDTO childPart : productTreeDTO.getChildren()) {
                fullSave(partRoot, newStructureList, structure, childPart, ct, le);
            }
        }
        return partRoot;
    }
 
    /**
     * 编号构造 根据时间
     *
     * @param localDateTime 时间
     * @param sign          标识
     * @return
     */
    private String noMake(LocalDateTime localDateTime, String sign) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        return sign + formatter.format(localDateTime);
    }
 
    /**
     * 新增零件
     *
     * @param ct             调用方法的时间
     * @param productTreeDTO 传参的零件节点
     * @param le             递归次数
     * @return
     */
    private Part partSave(LocalDateTime ct, ProductTreeDTO productTreeDTO, Integer le) {
        Part part = new Part();
        part.setPartNo(noMake(ct, "PA") + le);
        part.setPartName(productTreeDTO.getPartName());
        part.setSpecs(productTreeDTO.getPartName());
        part.setPartModel(productTreeDTO.getPartName());
        part.setUnit(productTreeDTO.getUnit());
        part.setLotTrackingIfs(false);
        part.setEngChgLevel("1");
        part.setPlanningMethod("A");
        //层级是1 就是成品 零件属性 1 原材料  2 半成品 3 成品  零件类型 1
        //零件类型   1 已制造 2 制造配方 3 已采购(原材料) 4 已采购  6 费用
        if (le == 1) {
            part.setMaterialType("1");
            part.setMaterialAttribute("3");
        }
        //层级>1 没有子节点就是原材料
        if (le > 1 && CollectionUtils.isEmpty(productTreeDTO.getChildren())) {
            part.setMaterialType("3");
            part.setMaterialAttribute("1");
        }
        //其他就是半成品了
        if (le > 1 && CollectionUtils.isNotEmpty(productTreeDTO.getChildren())) {
            part.setMaterialType("1");
            part.setMaterialAttribute("2");
        }
        partMapper.insert(part);
        return part;
    }
 
    /**
     * 新增工序
     *
     * @param ct             调用方法的时间
     * @param productTreeDTO 传参的零件节点
     * @param le             递归次数
     * @return
     */
    private Operation operationSave(LocalDateTime ct, ProductTreeDTO productTreeDTO, Integer le) {
        Operation operation = new Operation();
        operation.setOperationNo(noMake(ct, "OP") + le);
        operation.setName(productTreeDTO.getOperationName());
        operation.setProductionCounting(true);
        operation.setDaq(false);
        operation.setInspection(true);
        operation.setAutoInspection(true);
        operation.setMachRunFactor(BigDecimal.ZERO);
        operation.setMachSetupTime(BigDecimal.ZERO);
        operation.setLaborRunFactor(BigDecimal.ZERO);
        operation.setLaborSetupTime(BigDecimal.ZERO);
        operation.setMaterialCost(false);
        operation.setRunTimeCodeDb("1");
        operation.setCrewSize(BigDecimal.ONE);
        operationMapper.insert(operation);
        return operation;
    }
 
    /**
     * 保存产品结构主表
     *
     * @param partParent 父零件
     * @return
     */
    private StructureDTO strcutureSave(Part partParent) {
        StructureDTO structure = new StructureDTO();
        structure.setPartId(partParent.getId());
        structure.setVersion(partParent.getEngChgLevel());
        structure.setBomTypeDb("M");
        structure.setAlternativeNo("*");
        structure.setIfsSync(true);
        structureMapper.insert(structure);
        return structure;
    }
 
    /**
     * 保存产品结构明细
     *
     * @param structure      产品结构主表
     * @param productTreeDTO 导入bom的数据
     * @param partChild      子零件
     * @return
     */
    private void strcutureChildSave(StructureDTO structure, ProductTreeDTO productTreeDTO, Part partChild) {
        StructureComponent structureComponent = new StructureComponent();
        structureComponent.setPartId(partChild.getId());
        structureComponent.setStructureId(structure.getId());
        structureComponent.setOperationId(structure.getChildComOp().getId());
        structureComponent.setPlanningMethod(partChild.getPlanningMethod());
        structureComponent.setQpa(productTreeDTO.getQty());
        structureComponentMapper.insert(structureComponent);
    }
 
    /**
     * 生成BOM
     *
     * @param structurelist 产品结构的list
     */
    private void saveBomByStructure(List<StructureDTO> structurelist) {
        structurelist = structurelist.stream().sorted(Comparator.comparing(StructureDTO::getLe).reversed()).collect(Collectors.toList());
        for (StructureDTO structure : structurelist) {
            //新增工序参数
            Template template = basicParamSave(structure.getOperationParams(), structure.getChildComOp());
            Bom bom = new Bom();
            bom.setPartId(structure.getPartId());
            bom.setBomTypeDb(structure.getBomTypeDb());
            bom.setVersion(structure.getVersion());
            bom.setAlternativeNo(structure.getAlternativeNo());
            bom.setAlternativeDesc(structure.getAlternativeDesc());
            bom.setState(BomStates.ACCEPTED.getValue());
            bom.setNumber(bomNumberGenerator.generateNumberWithPrefix(Bom.DIGIT, Bom.PREFIX, Bom::getNumber));
            StructureTree tree = bomService.getAllBomExt(bom, 998);
            BomDTO bomDTO = new BomDTO();
            BeanUtils.copyProperties(bom, bomDTO);
            bomDTO.setTree(tree);
            //创建BOM
            bomMapper.insert(bom);
            routingSave(bom, structure.getChildComOp(), structure.getIsLast(), (structurelist.indexOf(structure) + 1), template);
            bomService.saveBomComp(bomDTO.getTree(), bom);
        }
    }
 
    /**
     * 基础参数设置
     *
     * @param params    参数list
     * @param operation 工序
     * @return 基础参数模板集
     */
    private Template basicParamSave(List<String> params, Operation operation) {
        //新增基础模板
        Template template = new Template();
        template.setTemplateNo(templateNumberGenerator.generateNumberWithPrefix(Template.DIGIT, Template.PREFIX, Template::getTemplateNo));
        template.setDataType("生产要求");
        template.setTemplateType("生产要求");
        template.setTemplateName(operation.getName() + "的生产要求");
        basicParamTemplateMapper.insert(template);
        long i = 0;
        //新增参数和参数模板关联关系
        for (String name : params) {
            i++;
            Param param = new Param();
            param.setCode(UUID.randomUUID().toString().replace("-", ""));
            param.setParameterItem(name);
            param.setType("1");
            param.setUnit("/");
            paramMapper.insert(param);
            ParamJoinTemplate paramJoinTemplate = new ParamJoinTemplate();
            paramJoinTemplate.setSort(i);
            paramJoinTemplate.setTechnologyOperationTemplateId(template.getId());
            paramJoinTemplate.setTechnologyOperationParamId(param.getId());
            paramJoinTemplateMapper.insert(paramJoinTemplate);
        }
        //新增工序参数关联关系
        OperationJoinTemplate operationJoinTemplate = new OperationJoinTemplate();
        operationJoinTemplate.setTechnologyOperationId(operation.getId());
        operationJoinTemplate.setTechnologyTemplateId(template.getId());
        operationJoinTemplateMapper.insert(operationJoinTemplate);
        return template;
    }
 
    /**
     * 检测标准
     */
    private void testStandardSave() {
 
    }
 
    /**
     * @param bom            BOM
     * @param operation      工序
     * @param isLast         是否最后工序
     * @param operationOrder 工序序号
     * @param template       参数模板
     */
    private void routingSave(Bom bom, Operation operation, boolean isLast, int operationOrder, Template template) {
        Routing routing = new Routing();
        routing.setRoutingNo(routingNumberGenerator.generateNumberWithPrefix(Routing.DIGIT, Routing.PREFIX, Routing::getRoutingNo));
        routing.setPartId(bom.getPartId());
        routing.setState(RoutingStates.ACCEPTED.getValue());
        routing.setMaster(false);
        routing.setVersion(bom.getVersion());
        routing.setBomTypeDb(bom.getBomTypeDb());
        routing.setBomId(bom.getId());
        routing.setAlternativeNo(bom.getAlternativeNo());
        routing.setAlternativeDesc(bom.getAlternativeDesc());
        routing.setIfsSync(true);
        routing.setPhaseInDate(LocalDateTime.now());
        routingMapper.insert(routing);
        saveRoutingOperation(routing, operation, isLast, operationOrder, template);
    }
 
    /**
     * 添加工艺路线工序
     *
     * @param routing        工艺路线主表
     * @param operation      工序
     * @param isLast         是否最后一道工序
     * @param operationOrder 工序序号
     * @param template       参数模板
     */
    private void saveRoutingOperation(Routing routing, Operation operation, boolean isLast, int operationOrder, Template template) {
        RoutingOperation routingOperation = new RoutingOperation();
        routingOperation.setRoutingId(routing.getId());
        routingOperation.setOperationId(operation.getId());
        routingOperation.setPartId(routing.getPartId());
        routingOperation.setOperationOrder(operationOrder * 10);
        routingOperation.setProductionCounting(operation.getProductionCounting());
        routingOperation.setDaq(operation.getDaq());
        routingOperation.setSemiFinished(operation.getSemiFinished());
        routingOperation.setInspection(operation.getInspection());
        routingOperation.setAutoInspection(operation.getAutoInspection());
        routingOperation.setMaterialCost(operation.getMaterialCost());
        routingOperation.setWorkCenter(operation.getWorkCenter());
        routingOperation.setMachRunFactor(operation.getMachRunFactor());
        routingOperation.setMachSetupTime(operation.getMachSetupTime());
        routingOperation.setLaborClassNo(operation.getLaborClassNo());
        routingOperation.setLaborRunFactor(operation.getLaborRunFactor());
        routingOperation.setLaborSetupTime(operation.getLaborSetupTime());
        routingOperation.setRunTimeCodeDb(operation.getRunTimeCodeDb());
        routingOperation.setCrewSize(operation.getCrewSize());
        routingOperation.setIsLast(isLast);
        routingOperation.setOutsideOpItem(operation.getOutsideOpItem());
        routingOperationMapper.insert(routingOperation);
        addOperationTemplate(routingOperation, template);
    }
 
    /**
     * 设置工艺路线参数模板集
     *
     * @param routingOperation
     * @param template
     */
    private void addOperationTemplate(RoutingOperation routingOperation, Template template) {
        List<Template> templateList = new ArrayList<>();
        templateList.add(template);
        //工艺路线新增参数模板集
        RoutingDTO routingDTO = new RoutingDTO();
        routingDTO.setRoutingOperationId(routingOperation.getId());
        routingDTO.setRoutingOperationTemplateList(templateList);
        routingService.addOperationTemplate(routingDTO);
    }
 
    /**
     * 工艺文件的生成
     *
     * @param part 成品零件
     */
    private Document documentSave(Part part) {
        Document document = new Document();
        document.setNumber(documentNumberGenerator.generateNumberWithPrefix(Document.DIGIT, Document.PREFIX, Document::getNumber));
        document.setName(part.getPartName());
        document.setState(DocumentStateStringValues.ACCEPTED);
        document.setVersion(part.getEngChgLevel());
        document.setPartId(part.getId());
        document.setPartName(part.getPartName());
        document.setPartNo(part.getPartNo());
        document.setDocType("M");
        return (Document) documentService.fullSave(document).getData();
    }
 
    /**
     * 创建销售订单主表
     *
     * @param part
     * @param document
     */
    private void saveCustomer(Part part, Document document) {
        Customer customer = new Customer();
        customer.setContractNo(customerService.contractNoMake());
        customer.setCustomerContractNo("ZTHLASUN");
        customer.setCustomerNo("ZTHLCAIZEA");
        customer.setCustomerName("蔡泽军工");
        customer.setEntityName("蔡泽台海战争一期");
        customer.setSalesDepartment("市场部");
        customer.setProvince("江苏省");
        customer.setSalesMan("shz");
        customer.setSalerWorkCode("ZT-038169");
        customerMapper.insert(customer);
        saveCustomerOrder(customer, part, document);
    }
 
    /**
     * 创建销售订单明细
     *
     * @param customer
     * @param part
     * @param document
     */
    private void saveCustomerOrder(Customer customer, Part part, Document document) {
        CustomerOrder customerOrder = new CustomerOrder();
        customerOrder.setCustomerOrderNo(customer.getContractNo());
        customerOrder.setCustomerNo(customer.getCustomerNo());
        customerOrder.setCustomerName(customer.getCustomerName());
        customerOrder.setCustomerId(customer.getId());
        customerOrder.setOtcPartSync(true);
        customerOrder.setCoState("03plan");
        customerOrder.setBuyQtyDue(new BigDecimal(10));
        customerOrder.setReservedQuantity(BigDecimal.ZERO);
        customerOrder.setDeliveryQuantity(BigDecimal.ZERO);
        customerOrder.setProductName(part.getPartName());
        customerOrder.setIsDocument(true);
        customerOrder.setTechnologyDocumentId(document.getId());
        customerOrder.setIsAudit("03accepted");
//        customerOrder.setOtcLineNo();
        customerOrder.setSalesPartNo(part.getPartNo());
        customerOrder.setSalesPartName(part.getPartName());
        customerOrder.setPartNo(part.getPartNo());
        customerOrder.setOtcQuantity(new BigDecimal(10));
        customerOrder.setOtcUnit(part.getUnit());
        customerOrder.setVersion(1);
        customerOrder.setWantedDeliveryDate(LocalDateTime.now().plusDays(30));
        customerOrder.setManufactureAttr("N");
        customerOrder.setIsSend(false);
        customerOrderMapper.insert(customerOrder);
        masterSchduleSave(customerOrder, part, document);
    }
 
    /**
     * 创建主计划
     *
     * @param customerOrder
     * @param part
     * @param document
     */
    private void masterSchduleSave(CustomerOrder customerOrder, Part part, Document document) {
        CustomerOrderDTO customerOrderDTO = new CustomerOrderDTO();
        customerOrderDTO.setId(customerOrder.getId());
        customerOrderDTO.setCoState(customerOrder.getCoState());
        customerOrderDTO.setBuyQtyDue(customerOrder.getBuyQtyDue());
        customerOrderDTO.setCustomerId(customerOrder.getCustomerId());
        customerOrderDTO.setManufactureAttr(customerOrder.getManufactureAttr());
        customerOrderDTO.setRequireNumber(customerOrder.getBuyQtyDue());
        customerOrderDTO.setTechnologyDocumentId(customerOrder.getTechnologyDocumentId());
        customerOrderDTO.setQtyPlaned(customerOrder.getBuyQtyDue());
        customerOrderDTO.setWantedDeliveryDate(customerOrder.getWantedDeliveryDate());
        customerOrderDTO.setPartId(part.getId());
        customerOrderDTO.setIsAudit(customerOrder.getIsAudit());
        customerOrderDTO.setDocNumber(document.getNumber());
        MasterProductionSchedule masterProductionSchedule = createMasterProductionSchedule(customerOrderDTO);
        ManufacturingOrderSave(masterProductionSchedule);
    }
 
    /**
     * 创建主计划
     *
     * @param customerOrderDTO
     * @return
     */
    private MasterProductionSchedule createMasterProductionSchedule(CustomerOrderDTO customerOrderDTO) {
        BigDecimal qta = customerOrderDTO.getQtyPlaned();
        //保存主生产计划
        MasterProductionSchedule masterProductionSchedule = new MasterProductionSchedule();
        masterProductionSchedule.setMpsNo(masterProductionScheduleNumberGenerator.generateNumberWithPrefix(MasterProductionSchedule.DIGIT, MasterProductionSchedule.PREFIX, MasterProductionSchedule::getMpsNo));
        masterProductionSchedule.setPartId(customerOrderDTO.getPartId());
        //将审核状态和工艺文件的id同步给生产计划
        masterProductionSchedule.setIsAudit(customerOrderDTO.getIsAudit());
        masterProductionSchedule.setTechnologyDocumentId(customerOrderDTO.getTechnologyDocumentId());
        masterProductionSchedule.setManufactureAttr(customerOrderDTO.getManufactureAttr());
        masterProductionSchedule.setDocNumber(customerOrderDTO.getDocNumber());
        masterProductionSchedule.setQtyRequired(qta);
        masterProductionSchedule.setRequiredDate(customerOrderDTO.getWantedDeliveryDate());
        masterProductionSchedule.setRemark(customerOrderDTO.getRemark());
        masterProductionSchedule.setSource("销售订单");
        masterProductionScheduleMapper.insert(masterProductionSchedule);
        //更新客户订单的下发数量
        customerOrderDTO.setRequireNumber(customerOrderDTO.getRequireNumber().add(customerOrderDTO.getQtyPlaned()));
        if (customerOrderDTO.getRequireNumber().compareTo(customerOrderDTO.getBuyQtyDue()) >= 0) {//已下发数量等于销售数量(小于销售数量不能更改状态),状态应该更新为已计划。目前状态依旧为待计划。
            customerOrderDTO.setCoState(CustomerOrderStateStringValues.PLANED);
        }
        customerOrderMapper.updateById(customerOrderDTO);
        //计算半成品用量
        customerOrderService.calPlanTheory(masterProductionSchedule);
        //保存主计划与客户订单的关系
        JoinModelCustomer joinModelCustomer = new JoinModelCustomer();
        joinModelCustomer.setCustomerOrderId(customerOrderDTO.getId());
        joinModelCustomer.setModel("plan_master_production_schedule");
        joinModelCustomer.setModelId(masterProductionSchedule.getId());
        joinModelCustomerMapper.insert(joinModelCustomer);
        return masterProductionSchedule;
    }
 
    /**
     * 创建车间订单
     *
     * @param masterProductionSchedule
     */
    private void ManufacturingOrderSave(MasterProductionSchedule masterProductionSchedule) {
        List<MasterProductionScheduleTheoryQuantityDTO> masterProductionScheduleTheoryQuantityDTOList = masterProductionScheduleTheoryQuantityMapper.getTheoryQuantity(masterProductionSchedule.getId());
        List<ManufacturingOrderDTO> manufacturingOrderDTOS = new ArrayList<>();
        for (MasterProductionScheduleTheoryQuantityDTO dto : masterProductionScheduleTheoryQuantityDTOList) {
            ManufacturingOrderDTO manufacturingOrderDTO = new ManufacturingOrderDTO();
            manufacturingOrderDTO.setMpsId(dto.getMid());
            manufacturingOrderDTO.setPartId(dto.getPartId());
            manufacturingOrderDTO.setPartNo(dto.getPartNo());
            manufacturingOrderDTO.setPartName(dto.getPartName());
            manufacturingOrderDTO.setTechnologyRoutingId(dto.getRoutingId());
            manufacturingOrderDTO.setBomId(dto.getBomId());
            manufacturingOrderDTO.setQtyRequired(dto.getQuantity());
            manufacturingOrderDTO.setWorkshopTypeCode("M");
            manufacturingOrderDTO.setRequiredDate(masterProductionSchedule.getRequiredDate());
            manufacturingOrderDTO.setWorkShop(workShopSave());
            manufacturingOrderDTO.setScheduleTheoryQuantityId(dto.getId());
            manufacturingOrderDTO.setManufactureAttr(masterProductionSchedule.getManufactureAttr());
            manufacturingOrderDTO.setIsReportOperation(true);
            manufacturingOrderDTOS.add(manufacturingOrderDTO);
        }
        try {
            List<ManufacturingOrderDTO> moRetrunList = manufacturingOrderService.addAll(manufacturingOrderDTOS);
            operationTaskSave(moRetrunList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
 
    /**
     * 工单新增
     *
     * @param moRetrunList
     */
    private void operationTaskSave(List<ManufacturingOrderDTO> moRetrunList) {
        int i = 0;
        List<OperationTaskDTO> saveList = new ArrayList<>();
        for (ManufacturingOrderDTO manufacturingOrderDTO : moRetrunList) {
            List<OperationTaskDTO> operationTaskDTOList = operationTaskMapper.getFromMoOptionByMoId(manufacturingOrderDTO.getId());
            for (OperationTaskDTO operationTaskDTO : operationTaskDTOList) {
                i++;
                operationTaskDTO.setWorkCenter(workCenterSave());
                Workstation workstation = workStationSave(i, workCenterSave());
                operationTaskDTO.setWorkstationId(workstation.getId());
                Location location = LocationSave(i);
                operationTaskDTO.setLocationId(location.getId());
                operationTaskDTO.setReelSpec("载具规格111");
                operationTaskDTO.setDiscNum(new Long(1));
                operationTaskDTO.setPlannedStartDate(LocalDateTime.now());
                operationTaskDTO.setPlannedFinishDate(LocalDateTime.now().plusDays(30));
                saveList.add(operationTaskDTO);
            }
        }
        operationTaskService.batchFullSave(saveList);
    }
 
    /**
     * @param i
     * @param workCenter
     * @return
     */
    private Workstation workStationSave(int i, String workCenter) {
        Workstation workstation = new Workstation();
        workstation.setName("测试设备" + i);
        workstation.setWorkstationNo(UUID.randomUUID().toString().replace("-", ""));
        workstation.setWorkCenter(workCenter);
        workstation.setType("物理设备");
        workstationMapper.insert(workstation);
        return workstation;
    }
 
    /**
     * @param i
     * @return
     */
    private Location LocationSave(int i) {
        Location location = new Location();
        location.setLocNo(UUID.randomUUID().toString().replace("-", ""));
        location.setLocName("测试产出合格库位" + i);
        location.setLocType("2");
        location.setLocStatus(1);
        locationMapper.insert(location);
        return location;
    }
 
    /**
     * @return
     */
    private String workShopSave() {
        List<String> workshops = pocMapper.getDicItem("work_shop");
        if (CollectionUtils.isEmpty(workshops)) {
            return "测试车间";
        } else {
            return workshops.get(0);
        }
    }
 
    /**
     * @return
     */
    private String workCenterSave() {
        List<String> workshops = pocMapper.getDicItem("work_center_type");
        if (CollectionUtils.isEmpty(workshops)) {
            return "测试工作中心";
        } else {
            return workshops.get(0);
        }
    }
}