1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
package org.jeecg.modules.dnc.service.impl;
 
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.dnc.constant.DocAttributionTypeEnum;
import org.jeecg.modules.dnc.dto.ComponentExt;
import org.jeecg.modules.dnc.entity.*;
import org.jeecg.modules.dnc.exception.ExceptionCast;
import org.jeecg.modules.dnc.mapper.ComponentInfoMapper;
import org.jeecg.modules.dnc.mapper.ProductInfoMapper;
import org.jeecg.modules.dnc.request.DocInfoQueryRequest;
import org.jeecg.modules.dnc.request.TreeInfoRequest;
import org.jeecg.modules.dnc.response.CommonCode;
import org.jeecg.modules.dnc.response.ComponentInfoCode;
import org.jeecg.modules.dnc.response.ProductInfoCode;
import org.jeecg.modules.dnc.response.UcenterCode;
import org.jeecg.modules.dnc.service.*;
import org.jeecg.modules.dnc.utils.ValidateUtil;
import org.jeecg.modules.system.entity.MdcProduction;
import org.jeecg.modules.system.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.*;
import java.util.stream.Collectors;
 
@Service
public class ComponentInfoSeServiceImpl extends ServiceImpl<ComponentInfoMapper, ComponentInfo> implements IComponentInfoService {
    @Autowired
    private IComponentPermissionService componentPermissionService;
    @Autowired
    public ProductInfoMapper productInfoMapper;
    @Autowired
    private IPermissionStreamNewService permissionStreamNewService;
    @Autowired
    private IComponentDepartmentService componentDepartmentService;
    @Autowired
    @Lazy
    private IPartsInfoService partsInfoService;
    @Autowired
    private IProcessSpecVersionService processSpecVersionService;
    @Autowired
    private IProcessStreamService processStreamService;
    @Autowired
    private IWorkStepService workStepService;
    @Autowired
    private IProductMixService productMixService;
    @Autowired
    private IDocRelativeService iDocRelativeService;
    @Autowired
    private IProductPermissionService productPermissionService;
    @Autowired
    @Lazy
    private IDocInfoService docInfoService;
    @Autowired
    private IDocRelativeService docRelativeService;
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean addComponentInfo(ComponentInfo componentInfo) {
        if(componentInfo == null)
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        if(!ValidateUtil.validateString(componentInfo.getComponentName()))
            ExceptionCast.cast(ComponentInfoCode.COMPONENT_NAME_NONE);
        if(!ValidateUtil.validateString(componentInfo.getProductId()))
            ExceptionCast.cast(ComponentInfoCode.COMPONENT_PRODUCT_NONE);
        if(!ValidateUtil.validateString(componentInfo.getComponentCode()))
            ExceptionCast.cast(ComponentInfoCode.COMPONENT_CODE_NONE);
        ComponentInfo en = getByCode(componentInfo.getComponentCode());
        if(en != null&&componentInfo.getBorrowId()==null)
            ExceptionCast.cast(ComponentInfoCode.COMPONENT_IS_EXIST);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = user.getId();
        if(!ValidateUtil.validateString(userId))
            ExceptionCast.cast(UcenterCode.UCENTER_ACCOUNT_NOT_EXIST);
        List<PermissionStreamNew> oldPermissionList;
        ProductInfo productInfo = productInfoMapper.selectById(componentInfo.getProductId());
        if(productInfo == null)
            ExceptionCast.cast(ComponentInfoCode.COMPONENT_PRODUCT_NONE);
        if (ValidateUtil.validateString(componentInfo.getParentId())) {
            en = super.getById(componentInfo.getParentId());
            if(en == null) {
                ExceptionCast.cast(ComponentInfoCode.COMPONENT_PARENT_NOT_EXIST);
            }
            oldPermissionList = permissionStreamNewService.loadPermissionStreamNewByBusinessId(en.getComponentId(),DocAttributionTypeEnum.COMPONENT.getCode().toString(),"1");
            componentInfo.setRankLevel(en.getRankLevel() + 1);
        } else {
            oldPermissionList = permissionStreamNewService.loadPermissionStreamNewByBusinessId(productInfo.getProductId(),DocAttributionTypeEnum.PRODUCT.getCode().toString(),"1");
            componentInfo.setParentId(null);
            componentInfo.setRankLevel(1);
        }
 
        componentInfo.setComponentStatus(1);
        boolean b = super.save(componentInfo);
        if(!b)
            ExceptionCast.cast(CommonCode.FAIL);
        //部门权限
        List<ComponentDepartment> componentDepartmentList = new ArrayList<>();
        List<PermissionStreamNew> componentDepartPermList = new ArrayList<>();
        if(oldPermissionList != null && !oldPermissionList.isEmpty()) {
            oldPermissionList.forEach(item -> {
                ComponentDepartment componentDepartment = new ComponentDepartment();
                componentDepartment.setComponentId(componentInfo.getComponentId());
                componentDepartment.setDepartId(item.getDepartId());
                componentDepartmentList.add(componentDepartment);
                PermissionStreamNew permissionStream = new PermissionStreamNew();
                permissionStream.setBusinessId(componentInfo.getComponentId());
                permissionStream.setDepartId(item.getDepartId());
                permissionStream.setBusinessType(DocAttributionTypeEnum.COMPONENT.getCode().toString());
                componentDepartPermList.add(permissionStream);
            });
        }
        if(!componentDepartmentList.isEmpty()) {
            b = componentDepartmentService.saveBatch(componentDepartmentList);
            if(!b)
                ExceptionCast.cast(CommonCode.FAIL);
        }
        if(!componentDepartPermList.isEmpty()) {
            b = permissionStreamNewService.saveBatch(componentDepartPermList);
            if(!b)
                ExceptionCast.cast(CommonCode.FAIL);
        }
        b = productPermissionService.add(componentInfo.getComponentId(), userId,DocAttributionTypeEnum.COMPONENT.getCode().toString());
        if (!b) {
            ExceptionCast.cast(ProductInfoCode.PRODUCT_SAVE_ERROR);
        }
        //添加结构树
        ProductMix productMix=null;
        if (componentInfo.getParentId() != null) {
            //子部件
            productMix = new ProductMix(Long.parseLong(componentInfo.getComponentId()),Long.parseLong(componentInfo.getParentId())
                    ,componentInfo.getComponentName(),componentInfo.getComponentCode(),2,new Date());
        }else {
            productMix = new ProductMix(Long.parseLong(componentInfo.getComponentId()),Long.parseLong(productInfo.getProductId())
                    ,componentInfo.getComponentName(),componentInfo.getComponentCode(),2,new Date());
        }
        productMixService.save(productMix);
        if (StrUtil.isNotEmpty(componentInfo.getBorrowId())){
            //借用部件,同步添加文件
            List<DocRelative> docRelativeList=docRelativeService.
                    list(new QueryWrapper<DocRelative>().eq("attribution_type",DocAttributionTypeEnum.COMPONENT.getCode().toString()).eq("attribution_id",componentInfo.getBorrowId()));
            if (!docRelativeList.isEmpty()){
                docRelativeList.forEach(item -> {
                    DocRelative docRelative = new DocRelative();
                    BeanUtil.copyProperties(item,docRelative);
                    docRelative.setId(null);
                    docRelative.setAttributionId(componentInfo.getComponentId());
                    docRelativeService.save(docRelative);
                });
            }
        }
        //添加权限
        PermissionStreamNew stream = new PermissionStreamNew();
        stream.setUserId(userId);
        stream.setBusinessId(componentInfo.getComponentId());
        stream.setBusinessType(DocAttributionTypeEnum.COMPONENT.getCode().toString());
        return permissionStreamNewService.addPermissionStreamNew(stream);
    }
 
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean editComponentInfo(String id, ComponentInfo componentInfo) {
        if(!ValidateUtil.validateString(id) || componentInfo == null)
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = user.getId();
        if(!ValidateUtil.validateString(userId))
            ExceptionCast.cast(UcenterCode.UCENTER_ACCOUNT_NOT_EXIST);
        ComponentInfo en = super.getById(id);
        if(en == null) {
            ExceptionCast.cast(ComponentInfoCode.COMPONENT_NOT_EXIST);
        }
        componentInfo.setComponentId(id);
        //设置为空 则不会更新
        componentInfo.setParentId(null);
        componentInfo.setComponentStatus(null);
        componentInfo.setRankLevel(null);
        componentInfo.setProductId(null);
        boolean b = super.updateById(componentInfo);
        //同步修改结构树
        ProductMix productMix = productMixService.getById(Long.parseLong(id));
        productMix.setName(componentInfo.getComponentName());
        productMix.setCode(componentInfo.getComponentCode());
        productMixService.updateById(productMix);
        if(!b)
            return false;
        ComponentPermission permission = componentPermissionService.getByComponentIdAndUserId(id, userId);
        if(permission == null) {
            permission = new ComponentPermission();
            permission.setComponentId(id);
            permission.setUserId(userId);
            b = componentPermissionService.save(permission);
            if(!b)
                return false;
        }
        PermissionStreamNew stream = permissionStreamNewService.loadPermissionStreamNewByBusinessIdAndUserId(id, userId,DocAttributionTypeEnum.COMPONENT.getCode().toString());
        if(stream == null) {
            stream = new PermissionStreamNew();
            stream.setUserId(userId);
            stream.setBusinessId(id);
            stream.setBusinessType(DocAttributionTypeEnum.COMPONENT.getCode().toString());
            return permissionStreamNewService.save(stream);
        }
        List<ComponentInfo> list = super.lambdaQuery().eq(ComponentInfo::getBorrowId,id).list();
        if (list != null && !list.isEmpty()) {
            list.forEach(item -> editComponentInfo(item.getComponentId(),componentInfo));
        }
        return true;
    }
 
    @Override
    public List<ComponentExt> findExtAll() {
        return super.getBaseMapper().findExtAll();
    }
 
    @Override
    public List<ComponentExt> getByUserPerms(String userId) {
        if(!ValidateUtil.validateString(userId))
            return Collections.emptyList();
        return super.getBaseMapper().getByUserPerms(userId);
    }
 
    @Override
    public List<ComponentInfo> getByUserPerms(String userId, String queryParam) {
        if(!ValidateUtil.validateString(userId))
            return Collections.emptyList();
        //去除权限  TODO
        LambdaQueryWrapper<ComponentInfo> queryWrapper = Wrappers.lambdaQuery();
        if(ValidateUtil.validateString(queryParam)) {
            queryWrapper.and(wrapper->wrapper.like(ComponentInfo::getComponentCode, queryParam)
                    .or()
                    .like(ComponentInfo::getComponentName, queryParam));
        }
        return super.list(queryWrapper);
    }
 
    @Override
    public List<ComponentExt> getByUserPermsAs(String userId) {
        if(!ValidateUtil.validateString(userId))
            return Collections.emptyList();
        return super.getBaseMapper().getByUserPermsAs(userId);
    }
 
    @Override
    public List<ComponentInfo> getByProductId(String productId) {
        if(!ValidateUtil.validateString(productId))
            return null;
        return super.lambdaQuery().eq(ComponentInfo::getProductId, productId).list();
    }
 
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean deleteCollections(List<ComponentInfo> componentInfoList) {
        componentInfoList.forEach(item -> {
            boolean b = componentPermissionService.deleteByComponentId(item.getComponentId());
            if(!b)
                ExceptionCast.cast(ComponentInfoCode.COMPONENT_DELETE_PERM_NONE);
            b = componentDepartmentService.deleteByComponentId(item.getComponentId());
            if(!b)
                ExceptionCast.cast(ComponentInfoCode.COMPONENT_DELETE_PERM_NONE);
            b = permissionStreamNewService.deletePermissionStreamNewByBusinessId(item.getComponentId(),DocAttributionTypeEnum.COMPONENT.getCode().toString(),"0");
            if(!b)
                ExceptionCast.cast(ComponentInfoCode.COMPONENT_DELETE_PERM_NONE);
            b = permissionStreamNewService.deletePermissionStreamNewByBusinessId(item.getComponentId(),DocAttributionTypeEnum.COMPONENT.getCode().toString(),"1");
            if(!b)
                ExceptionCast.cast(ComponentInfoCode.COMPONENT_DELETE_PERM_NONE);
            b = super.removeById(item.getComponentId());
            if(!b)
                ExceptionCast.cast(ComponentInfoCode.COMPONENT_DELETE_PERM_NONE);
        });
        return true;
    }
 
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean deleteComponentInfo(String id) {
        if(!ValidateUtil.validateString(id))
            ExceptionCast.cast(ComponentInfoCode.COMPONENT_DELETE_ERROR);
        ComponentInfo componentInfo = super.getById(id);
        if(componentInfo == null)
            ExceptionCast.cast(ComponentInfoCode.COMPONENT_DELETE_ERROR);
        List<ComponentInfo> childrenList = getByParentId(id);
        if(childrenList != null && !childrenList.isEmpty()) {
            ExceptionCast.cast(ComponentInfoCode.COMPONENT_CHILD_EXIST);
        }
        //验证部件下是否有零件
        List<PartsInfo> partsInfoList = partsInfoService.getByComponentId(componentInfo.getProductId(), componentInfo.getComponentId());
        if(partsInfoList != null && !partsInfoList.isEmpty()) {
            ExceptionCast.cast(ComponentInfoCode.COMPONENT_PARTS_EXIST);
        }
        //验证部件下是否有工序信息
        List<ProcessStream> processStreamList = processStreamService.findByComponentId(id);
        if(processStreamList != null && !processStreamList.isEmpty()) {
            ExceptionCast.cast(ComponentInfoCode.COMPONENT_PROCESS_EXIST);
        }
        //验证部件是否被借用
        List<ComponentInfo> list = super.lambdaQuery().eq(ComponentInfo::getBorrowId,id).list();
        if (list != null && !list.isEmpty()) {
            ExceptionCast.cast(ComponentInfoCode.COMPONENT_BORROW_EXIST);
        }
        boolean b;
        //验证是否存在文档
        List<DocRelative> docRelativeList=iDocRelativeService.list(new QueryWrapper<DocRelative>().eq("attribution_type",DocAttributionTypeEnum.COMPONENT.getCode().toString()).eq("attribution_id",id));
        if (!docRelativeList.isEmpty()){
            ExceptionCast.cast(ComponentInfoCode.COMPONENT_DOC_EXIST);
        }
        b = componentPermissionService.deleteByComponentId(id);
        if(!b)
            ExceptionCast.cast(CommonCode.FAIL);
        b = componentDepartmentService.deleteByComponentId(id);
        if(!b)
            ExceptionCast.cast(CommonCode.FAIL);
        b = permissionStreamNewService.deletePermissionStreamNewByBusinessId(componentInfo.getComponentId(),DocAttributionTypeEnum.COMPONENT.getCode().toString(),"0");
        if(!b)
            ExceptionCast.cast(CommonCode.FAIL);
        b = permissionStreamNewService.deletePermissionStreamNewByBusinessId(componentInfo.getComponentId(),DocAttributionTypeEnum.COMPONENT.getCode().toString(),"1");
        if(!b)
            ExceptionCast.cast(CommonCode.FAIL);
        b = productMixService.removeById(id);
        if (!b)
            ExceptionCast.cast(CommonCode.FAIL);
        return super.removeById(id);
    }
 
    @Override
    public List<ComponentInfo> getByParentId(String componentId) {
        List<ComponentExt> componentExtList = super.getBaseMapper().findByParentId(componentId);
        if(componentExtList == null || componentExtList.isEmpty())
            return null;
        List<ComponentInfo> list = new ArrayList<>();
        componentExtList.forEach(item -> {
            item.getAllChildren(list);
        });
        return list;
    }
 
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean assignAddUser(ComponentInfo componentInfo, Collection<SysUser> userList) {
        if(componentInfo == null || userList == null || userList.isEmpty())
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        List<ComponentPermission> permissionList = new ArrayList<>();
        List<PermissionStreamNew> permissionStreamList = new ArrayList<>();
        userList.forEach(item -> {
            ComponentPermission en = componentPermissionService.getByComponentIdAndUserId(componentInfo.getComponentId(), item.getId());
            if(en == null) {
                en = new ComponentPermission();
                en.setUserId(item.getId());
                en.setComponentId(componentInfo.getComponentId());
                permissionList.add(en);
            }
            PermissionStreamNew stream = permissionStreamNewService.loadPermissionStreamNewByBusinessIdAndDepartId(componentInfo.getComponentId(), item.getId(), "2 ");
            if(stream == null) {
                stream = new PermissionStreamNew();
                stream.setUserId(item.getId());
                stream.setBusinessId(componentInfo.getComponentId());
                stream.setBusinessType(DocAttributionTypeEnum.COMPONENT.getCode().toString());
                permissionStreamList.add(stream);
            }
        });
        if(!permissionList.isEmpty()) {
            boolean b = componentPermissionService.saveBatch(permissionList);
            if(!b) {
                ExceptionCast.cast(ProductInfoCode.PRODUCT_USER_PERM_ERROR);
            }
        }
        if(!permissionStreamList.isEmpty()) {
            boolean b = permissionStreamNewService.saveBatch(permissionStreamList);
            if(!b) {
                ExceptionCast.cast(ProductInfoCode.PRODUCT_USER_PERM_ERROR);
            }
        }
        return true;
    }
 
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean assignRemoveUser(ComponentInfo componentInfo, Collection<SysUser> userList) {
        if(componentInfo == null || userList == null || userList.isEmpty())
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        List<ComponentPermission> permissionList = new ArrayList<>();
        List<PermissionStreamNew> permissionStreamList = new ArrayList<>();
        userList.forEach(item -> {
            ComponentPermission en = componentPermissionService.getByComponentIdAndUserId(componentInfo.getComponentId(), item.getId());
            if(en != null) {
                permissionList.add(en);
            }
            PermissionStreamNew stream = permissionStreamNewService.loadPermissionStreamNewByBusinessIdAndDepartId(componentInfo.getComponentId(), item.getId(), "2 ");
            if(stream != null) {
                permissionStreamList.add(stream);
            }
        });
        //校验部件用户权限清空操作
        List<ComponentPermission> existList = componentPermissionService.getByComponentId(componentInfo.getComponentId());
        if(existList.size() <= permissionList.size())
            ExceptionCast.cast(ComponentInfoCode.COMPONENT_USER_NONE);
        if(!permissionList.isEmpty()) {
            boolean b = componentPermissionService.removeByCollection(permissionList);
            if(!b) {
                ExceptionCast.cast(ProductInfoCode.PRODUCT_USER_PERM_ERROR);
            }
        }
        if(!permissionStreamList.isEmpty()) {
            boolean b = permissionStreamNewService.deletePermissionStreamNewByList(permissionStreamList);
            if(!b) {
                ExceptionCast.cast(ProductInfoCode.PRODUCT_USER_PERM_ERROR);
            }
        }
        return true;
    }
 
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean assignAddDepart(ComponentInfo componentInfo, Collection<MdcProduction> departmentList) {
        if(componentInfo == null || departmentList == null || departmentList.isEmpty())
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        List<ComponentDepartment> componentDepartments = new ArrayList<>();
        List<PermissionStreamNew> permissionStreamList = new ArrayList<>();
        departmentList.forEach(item -> {
            ComponentDepartment en = componentDepartmentService.getByComponentIdAndDepartId(componentInfo.getComponentId(), item.getId());
            if(en == null) {
                en = new ComponentDepartment();
                en.setDepartId(item.getId());
                en.setComponentId(componentInfo.getComponentId());
                componentDepartments.add(en);
            }
            PermissionStreamNew stream = permissionStreamNewService.loadPermissionStreamNewByBusinessIdAndDepartId(componentInfo.getComponentId(), item.getId(),DocAttributionTypeEnum.COMPONENT.getCode().toString());
            if(stream == null) {
                stream = new PermissionStreamNew();
                stream.setDepartId(item.getId());
                stream.setBusinessId(componentInfo.getComponentId());
                stream.setBusinessType(DocAttributionTypeEnum.COMPONENT.getCode().toString());
                permissionStreamList.add(stream);
            }
        });
        if(!componentDepartments.isEmpty()) {
            boolean b = componentDepartmentService.saveBatch(componentDepartments);
            if(!b) {
                ExceptionCast.cast(ProductInfoCode.PRODUCT_USER_PERM_ERROR);
            }
        }
        if(!permissionStreamList.isEmpty()) {
            boolean b = permissionStreamNewService.saveBatch(permissionStreamList);
            if(!b) {
                ExceptionCast.cast(ProductInfoCode.PRODUCT_USER_PERM_ERROR);
            }
        }
        return true;
    }
 
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean assignRemoveDepart(ComponentInfo componentInfo, Collection<MdcProduction> departmentList) {
        if(componentInfo == null || departmentList == null || departmentList.isEmpty())
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        List<ComponentDepartment> componentDepartments = new ArrayList<>();
        List<PermissionStreamNew> permissionStreamList = new ArrayList<>();
        departmentList.forEach(item -> {
            ComponentDepartment en = componentDepartmentService.getByComponentIdAndDepartId(componentInfo.getComponentId(), item.getId());
            if(en != null) {
                componentDepartments.add(en);
            }
            PermissionStreamNew stream = permissionStreamNewService.loadPermissionStreamNewByBusinessIdAndDepartId(componentInfo.getComponentId(), item.getId(),DocAttributionTypeEnum.COMPONENT.getCode().toString());
            if(stream != null) {
                permissionStreamList.add(stream);
            }
        });
        if(!componentDepartments.isEmpty()) {
            boolean b = componentDepartmentService.removeByCollection(componentDepartments);
            if(!b) {
                ExceptionCast.cast(ProductInfoCode.PRODUCT_USER_PERM_ERROR);
            }
        }
        if(!permissionStreamList.isEmpty()) {
            boolean b = permissionStreamNewService.deletePermissionStreamNewByList(permissionStreamList);
            if(!b) {
                ExceptionCast.cast(ProductInfoCode.PRODUCT_USER_PERM_ERROR);
            }
        }
        return true;
    }
 
    @Override
    public ComponentInfo getByCode(String code) {
        if(ValidateUtil.validateString(code)) {
            List<ComponentInfo> list = super.lambdaQuery().eq(ComponentInfo::getComponentCode, code).list();
            if(list == null || list.isEmpty())
                return null;
            return list.get(0);
        }
        return null;
    }
 
    @Override
    public PermissionStream validateComponentOrPartsPnCode(String pnCode) {
        if(!ValidateUtil.validateString(pnCode)) {
            ExceptionCast.cast(ComponentInfoCode.COMPONENT_PN_NOT_VALID);
        }
        PermissionStream stream = new PermissionStream();
        List<ComponentInfo> componentInfos = super.lambdaQuery().eq(ComponentInfo::getComponentCode, pnCode).list();
        if(componentInfos == null || componentInfos.isEmpty()) {
            List<PartsInfo> list = partsInfoService.lambdaQuery().eq(PartsInfo::getPartsCode, pnCode).list();
            if(list == null || list.isEmpty()) {
                ExceptionCast.cast(ComponentInfoCode.COMPONENT_PN_NOT_EXIST);
            }else if(list.size() != 1) {
                ExceptionCast.cast(ComponentInfoCode.COMPONENT_PN_NOT_ONLY);
            }else {
                PartsInfo partsInfo = list.get(0);
                stream.setProductId(partsInfo.getProductId());
                stream.setComponentId(partsInfo.getComponentId());
                stream.setPartsId(partsInfo.getPartsId());
                return stream;
            }
        }else if(componentInfos.size() != 1){
            ExceptionCast.cast(ComponentInfoCode.COMPONENT_PN_NOT_ONLY);
        }else {
            List<PartsInfo> list = partsInfoService.lambdaQuery().eq(PartsInfo::getPartsCode, pnCode).list();
            if(list != null && list.size() > 0) {
                ExceptionCast.cast(ComponentInfoCode.COMPONENT_PN_NOT_ONLY);
            }
            ComponentInfo componentInfo = componentInfos.get(0);
            stream.setProductId(componentInfo.getProductId());
            stream.setComponentId(componentInfo.getComponentId());
            return stream;
        }
        return null;
    }
 
    @Override
    public List<ComponentInfo> getByProductIdAndUserId(String productId, String userId) {
        //去除权限  TODO
        //return super.getBaseMapper().selectByProductIdAndUserId(productId, userId);
        LambdaQueryWrapper<ComponentInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ComponentInfo::getProductId, productId);
        queryWrapper.eq(ComponentInfo::getRankLevel, 1);
        queryWrapper.orderByAsc(ComponentInfo::getCreateTime);
        return super.list(queryWrapper);
    }
 
    @Override
    public List<ComponentInfo> getByParentIdAndUserId(String parentId, String userId) {
        //去除权限  TODO
        //return super.getBaseMapper().selectByParentIdAndUserId(parentId, userId);
        LambdaQueryWrapper<ComponentInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ComponentInfo::getParentId, parentId);
        queryWrapper.orderByAsc(ComponentInfo::getCreateTime);
        return super.list(queryWrapper);
    }
 
    /**
     * 通过零件号、材质等查询对应电子样板
     * @param treeInfoRequest
     * @return
     */
    @Override
    public List<DocInfo> getByComponentInfo(TreeInfoRequest treeInfoRequest){
        LambdaQueryWrapper<ComponentInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (treeInfoRequest.getProductIds() != null && !treeInfoRequest.getProductIds().isEmpty()) {
            queryWrapper.in(ComponentInfo::getProductId, treeInfoRequest.getProductIds());
        }
        if (treeInfoRequest.getAttributionType()==2){
            queryWrapper.eq(StrUtil.isNotEmpty(treeInfoRequest.getAttributionId()),ComponentInfo::getComponentId,treeInfoRequest.getAttributionId());
        }
 
        queryWrapper.like(StrUtil.isNotEmpty(treeInfoRequest.getTreeCode()),ComponentInfo::getComponentCode, treeInfoRequest.getTreeCode());
        queryWrapper.like(StrUtil.isNotEmpty(treeInfoRequest.getTreeName()),ComponentInfo::getComponentName, treeInfoRequest.getTreeName());
        queryWrapper.like(StrUtil.isNotEmpty(treeInfoRequest.getStructureType()),ComponentInfo::getStructureType, treeInfoRequest.getStructureType());
        queryWrapper.orderByDesc(ComponentInfo::getCreateTime);
        List<ComponentInfo> list = super.list(queryWrapper);
        List<DocInfo> docInfos = new ArrayList<>();
        if (list != null && !list.isEmpty()) {
            String ids=list.stream().map(ComponentInfo::getComponentId).collect(Collectors.joining(","));
            DocInfoQueryRequest docQuery = new DocInfoQueryRequest();
            BeanUtil.copyProperties(treeInfoRequest,docQuery);
            docQuery.setAttributionIds(ids);
            docQuery.setDocClassCode("OTHER");
            docQuery.setAttributionType(2);
            docInfos=docInfoService.findListByDocQuery(docQuery);
        }
        if (treeInfoRequest.getAttributionType()==2){
            List<String> id =new ArrayList<>();
            id.add(treeInfoRequest.getAttributionId());
            treeInfoRequest.setComponentIds(id);
            //零件
            List<DocInfo> partsInfos = partsInfoService.getByPartsInfo(treeInfoRequest);
            docInfos.addAll(partsInfos);
            //工艺规程版本
            List<DocInfo> processSpecVersions = processSpecVersionService.getByProcessSpecVersion(treeInfoRequest);
            docInfos.addAll(processSpecVersions);
            //工序
            List<DocInfo> processStreams = processStreamService.getByProcessStreamOtherFile(treeInfoRequest);
            docInfos.addAll(processStreams);
            //工步
            List<DocInfo> workSteps = workStepService.getByWorkStepOtherFile(treeInfoRequest);
            docInfos.addAll(workSteps);
        }
        return docInfos;
    }
 
    /**
     * 查询可以被引用的部件
     * @param componentInfo
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public IPage<ComponentInfo> getByComponentId(ComponentInfo componentInfo, Integer pageNo, Integer pageSize){
        //权限排除,不能引用自己上下级部件
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String productIds = loginUser.getProductionIds();
        ComponentInfo oldComponentInfo = super.getById(componentInfo.getComponentId());
        IPage<ComponentInfo> page = new Page<>(pageNo, pageSize);
        if (productIds != null && !productIds.isEmpty()) {
            List<String> productIdList = Arrays.asList(productIds.split(","));
            List<ProductMix> productMixList = permissionStreamNewService.
                    loadProductMixByBusinessIdAndBusinessType(loginUser.getId(),productIdList,componentInfo.getComponentId(),DocAttributionTypeEnum.COMPONENT.getCode().toString());
            List<Long> ids = productMixList.stream().map(ProductMix::getId).collect(Collectors.toList());
            //获取已经自身被借用的部件
            LambdaQueryWrapper<ComponentInfo> borrowQueryWrapper = new LambdaQueryWrapper<>();
            borrowQueryWrapper.in(ComponentInfo::getBorrowId,ids);
            borrowQueryWrapper.eq(ComponentInfo::getParentId,componentInfo.getComponentId());
            List<String> borrowIds= super.list(borrowQueryWrapper).stream().map(ComponentInfo::getBorrowId).collect(Collectors.toList());
            LambdaQueryWrapper<ComponentInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(StrUtil.isNotEmpty(componentInfo.getComponentName()),ComponentInfo::getComponentName, componentInfo.getComponentName());
            queryWrapper.like(StrUtil.isNotEmpty(componentInfo.getComponentCode()),ComponentInfo::getComponentCode, componentInfo.getComponentCode());
            queryWrapper.isNull(ComponentInfo::getBorrowId);
            queryWrapper.in(ComponentInfo::getComponentId,ids);
            queryWrapper.ne(StrUtil.isNotEmpty(oldComponentInfo.getBorrowId()),ComponentInfo::getComponentId,oldComponentInfo.getBorrowId());
            if (!borrowIds.isEmpty()) {
                queryWrapper.notIn(ComponentInfo::getComponentId,borrowIds);
            }
            queryWrapper.orderByDesc(ComponentInfo::getCreateTime);
            page = super.page(page, queryWrapper);
        }
        return page;
    }
 
    /**
     * 借用部件(可批量) - 原有部件id,新部件ids
     * @param oldId,newIds
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> borrowComponent(String oldId, String newIds){
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ComponentInfo componentInfo = super.getById(oldId);
        if(componentInfo == null) {
            return Result.error("部件不存在");
        }
        List<String> productIdList = Arrays.asList(loginUser.getProductionIds().split(","));
        //获取可以借用的部件
        List<ProductMix> productMixList = permissionStreamNewService.
                loadProductMixByBusinessIdAndBusinessType(loginUser.getId(),productIdList,componentInfo.getComponentId(),DocAttributionTypeEnum.COMPONENT.getCode().toString());
        Set<Long> allowedIds = productMixList.stream()
                .map(ProductMix::getId)
                .collect(Collectors.toCollection(HashSet::new));
        List<String> newIdList = Arrays.asList(newIds.split(","));
        boolean allAllowed = newIdList.parallelStream()
                .map(Long::parseLong)
                .allMatch(allowedIds::contains);
        if (!allAllowed) {
            return Result.error("存在未授权的部件借用");
        }
        //获取已经被借用的部件
        LambdaQueryWrapper<ComponentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ComponentInfo::getBorrowId,newIdList);
        queryWrapper.eq(ComponentInfo::getParentId,componentInfo.getComponentId());
        List<ComponentInfo> list = super.list(queryWrapper);
        //判断是否已经被当前部件借用
        if(!list.isEmpty()) {
            return Result.error("选择的部件已被当前部件借用");
        }
        List<ComponentInfo> componentInfoList=listByIds(newIdList);
        componentInfoList.forEach(item->{
            //添加部件信息、层级信息、权限信息
            ComponentInfo newComponentInfo=new ComponentInfo();
            BeanUtil.copyProperties(item,newComponentInfo);
            newComponentInfo.setComponentId(null);
            newComponentInfo.setProductId(componentInfo.getProductId());
            newComponentInfo.setParentId(componentInfo.getComponentId());
            newComponentInfo.setBorrowId(item.getComponentId());
            newComponentInfo.setCreateTime(null);
            newComponentInfo.setCreateBy(null);
            newComponentInfo.setUpdateTime(null);
            newComponentInfo.setUpdateBy(null);
            addComponentInfo(newComponentInfo);
        });
        return Result.ok("部件借用成功");
    }
}