lyh
2025-02-28 1becd6d46123723bd2b898fd565b4331fb2cb2d8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
package org.jeecg.modules.flow.service.impl;
 
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.IdWorker;
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.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.flow.entity.ToEquipmentTask;
import org.jeecg.modules.flow.service.IActivitiDefinitionService;
import org.jeecg.modules.flow.service.IAssignFileStreamService;
import org.jeecg.modules.flow.service.IToEquipmentTaskService;
import org.jeecg.modules.flow.entity.AssignFileStream;
import org.jeecg.modules.flow.ext.AssignFileStreamExt;
import org.jeecg.modules.flow.mapper.AssignFileStreamMapper;
import org.jeecg.modules.flow.request.ApproveBatchRequest;
import org.jeecg.modules.flow.request.AssignFileRequest;
import org.jeecg.modules.flow.request.AssignFileStreamQueryRequest;
import org.jeecg.modules.flow.request.TaskRequest;
import org.jeecg.modules.dnc.entity.*;
import org.jeecg.modules.dnc.exception.ExceptionCast;
import org.jeecg.modules.dnc.ext.NcTxtFilePathInfo;
import org.jeecg.modules.dnc.response.*;
import org.jeecg.modules.dnc.service.*;
import org.jeecg.modules.dnc.utils.ValidateUtil;
import org.jeecg.modules.dnc.utils.date.DateUtil;
import org.jeecg.modules.dnc.utils.file.FileUtilS;
import org.jeecg.modules.flow.vo.AssignFlowTaskVo;
import org.jeecg.modules.flowable.apithird.business.entity.FlowMyBusiness;
import org.jeecg.modules.flowable.apithird.service.FlowCallBackServiceI;
import org.jeecg.modules.flowable.apithird.service.FlowCommonService;
import org.jeecg.modules.flowable.domain.vo.FlowTaskVo;
import org.jeecg.modules.flowable.service.IFlowDefinitionService;
import org.jeecg.modules.flowable.service.IFlowTaskService;
import org.jeecg.modules.mdc.entity.MdcEquipment;
import org.jeecg.modules.mdc.service.IMdcEquipmentService;
import org.jeecg.modules.system.entity.MdcProduction;
import org.jeecg.modules.system.service.IMdcProductionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
 
@Service("IAssignFileStreamService")
public class AssignFileStreamServiceImpl extends ServiceImpl<AssignFileStreamMapper, AssignFileStream> implements IAssignFileStreamService , FlowCallBackServiceI {
    private static final String PROCESS_KEY = "assign_nc_to_device";
    private static final String APPLY_VARIABLE = "apply_user";
    private static final String APPROVE_VARIABLE = "approve_users";
    private static final String SEND_CODE = "SEND";
 
    @Value("${flowable.enable}")
    private Boolean flowableEnable;
 
    @Autowired
    private IDocInfoService docInfoService;
    @Autowired
    private IProcessStreamService processStreamService;
    @Autowired
    private IWorkStepService workStepService;
    @Autowired
    private IPermissionStreamService permissionStreamService;
    @Autowired
    private IDocClassificationService classificationService;
    @Autowired
    private IToEquipmentTaskService equipmentTaskService;
    @Autowired
    private IDeviceInfoService deviceInfoService;
    @Autowired
    private IDocFileService docFileService;
    @Autowired
    private IActivitiDefinitionService definitionService;
    @Autowired
    private IDocRelativeService docRelativeService;
    @Autowired
    private ISynchronizedFlagService synchronizedFlagService;
    @Autowired
    private IDeviceGroupService deviceGroupService;
    @Autowired
    private IDncPassLogService dncPassLogService;
    @Autowired
    private IDeviceCharactersService iDeviceCharactersService;
    @Autowired
    private IMdcEquipmentService iMdcEquipmentService;
    @Autowired
    private IMdcProductionService iMdcProductionService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private TaskService taskService;
    @Resource
    private FlowCommonService flowCommonService;
    @Resource
    private IFlowDefinitionService flowDefinitionService;
    @Autowired
    private IFlowTaskService flowTaskService;
 
    @Value("${securedoc.serverIp}")
    private String serverIp;
    @Value("${securedoc.serverPort}")
    private int serverPort;
    @Value("${securedoc.whether}")
    private String whether;
    @Value("${securedoc.localFilePath}")
    private String localFilePath;
 
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result applyAssignFile(AssignFileStream stream) {
        synchronized (this){
            //判断设备特殊字符
            String specialChar = getDeviceSpecialChar(stream.getDeviceId(),stream.getFileId());
            if (StrUtil.isNotEmpty(specialChar)){
                //抛出特殊字符异常
                return Result.error("文件名称存在设备特殊字符");
            }
            if(flowableEnable) {
                return applyAssignFileActive(stream);
            }else {
                return applyAssignFileNonActive(stream);
            }
        }
    }
 
    /**
     * 判断设备特殊字符
     * @param deviceId,fileId
     * 设备ID,文件ID
     */
    public String getDeviceSpecialChar(String deviceId, String fileId){
        //替换为mdc设备表
//        DeviceInfo deviceInfo = deviceInfoService.getById(deviceId);
        MdcEquipment mdcEquipment = iMdcEquipmentService.getById(deviceId);
        if(mdcEquipment == null)
            ExceptionCast.cast(ActivitiCode.ACT_ASSIGN_DEVICE_NONE);
//        DocFile docFile = docFileService.getById(fileId);
        DocInfo docInfo = docInfoService.getOne(new QueryWrapper<DocInfo>().eq("publish_file_id",fileId));
        if(docInfo == null)
            ExceptionCast.cast(ActivitiCode.ACT_FILE_ERROR);
        List<DeviceCharacters> deviceCharactersList=iDeviceCharactersService.list(
                new LambdaQueryWrapper<DeviceCharacters>().eq(DeviceCharacters::getDeviceNo,mdcEquipment.getEquipmentId()));
        if (deviceCharactersList.isEmpty()){
            return "";
        }else {
            List<String> specialCharList=deviceCharactersList.stream().map(DeviceCharacters::getCharacters).collect(Collectors.toList());
            if(!specialCharList.isEmpty()){
                //对比文件名是否包含特殊字符
                String fileName=docInfo.getDocName();
                for(String specialChar:specialCharList){
                    if (fileName.contains(specialChar)){
                        return specialChar;
                    }
                }
            }else {
                return "";
            }
        }
        return "";
    }
 
    private ResponseResult createSpecialCharErrorResponse(String specialChar) {
        return new ResponseResult(new ResultCode() {
            @Override
            public boolean success() {
                return false;
            }
            @Override
            public int code() {
                return 88881;
            }
            @Override
            public String message() {
                return "文件名称存在设备特殊字符" + specialChar;
            }
        });
    }
 
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result<?> applyAssignFileActive(AssignFileStream stream) {
        validateParams(stream);
        DocInfo docInfo = getDocInfo(stream);
        MdcEquipment mdcEquipment = getMdcEquipment(stream);
        DocFile docFile = docFileService.getById(stream.getFileId());
        DocInfo deviceDoc = docInfoService.getByDocAttrAndDocId(stream.getDocId(), 4, stream.getDeviceId());
        if (deviceDoc != null) {
            handleExistingDeviceDoc(docFile, mdcEquipment, stream.getDeviceId());
        }
        deviceDoc = docInfoService.findByAttrAndDocName(docInfo.getDocName(), 4, stream.getDeviceId());
        if (deviceDoc != null) {
            handleExistingDeviceDoc(docFile, mdcEquipment, stream.getDeviceId());
        }
        List<PermissionStream> permissionStreams = getPermissionStreams(stream);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = user.getId();
        saveBusinessObject(stream, userId);
        System.out.println("指派NC文档到设备流程:" + stream.getDocId());
        flowCommonService.initActBusiness("指派NC文档到设备流程:" +docInfo.getDocName()+"."+docInfo.getDocSuffix()+"到设备->"+mdcEquipment.getEquipmentName() ,
                stream.getStreamId(), "IAssignFileStreamService", "assign_nc_to_device", null);
        Map<String, Object> variables = new HashMap<>();
        variables.put("dataId", stream.getStreamId());
        variables.put("organization", stream.getApplyReason());
        return flowDefinitionService.startProcessInstanceByKey("assign_nc_to_device", variables);
    }
 
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result<?> applyAssignFileNonActive(AssignFileStream stream) {
        //权限校验
        validateParams(stream);
        DocInfo docInfo = getDocInfo(stream);
        MdcEquipment mdcEquipment = getMdcEquipment(stream);
        DocFile docFile = getDocFile(stream);
        DocInfo deviceDoc = docInfoService.getByDocAttrAndDocId(stream.getDocId(), 4, stream.getDeviceId());
        if(deviceDoc != null) {
            // 删除 备份  覆盖 原有的
            List<String> strings=iMdcProductionService.findListParentTreeAll(mdcEquipment.getId());
            if (strings != null && !strings.isEmpty()) {
                String path = StringUtils.join(strings.toArray(), "/");
                boolean copyFileNc = FileUtilS.copyFileNcToBak(path + "/"+ mdcEquipment.getEquipmentId(),
                        docFile.getFileName(), docFile.getFileSuffix());
            }
        }
        /*deviceDoc = docInfoService.findByAttrAndDocName(docInfo.getDocName(), 4, stream.getDeviceId());
        if(deviceDoc != null) {
            // 删除 备份  覆盖 原有的
            List<String> strings =  deviceGroupService.findListParentTreeAll(deviceInfo.getGroupId());
            if (strings != null && !strings.isEmpty()) {
                String path = StringUtils.join(strings.toArray(), "/");
                boolean copyFileNc = FileUtilS.copyFileNcToBak(path + "/"+ deviceInfo.getDeviceNo(),
                        docFile.getFileName(), docFile.getFileSuffix());
            }
        }*/
        getPermissionStreams(stream);
        //插入文档到设备发送文档
        if(deviceDoc == null) {
            DocClassification classification = classificationService.getByCode(SEND_CODE);
            if(classification == null)
                ExceptionCast.cast(DocumentCode.DOC_CLASS_ERROR);
            DocRelative docRelative = new DocRelative();
            docRelative.setDocId(docInfo.getDocId());
            docRelative.setClassificationId(classification.getClassificationId());
            docRelative.setAttributionType(4);
            docRelative.setAttributionId(stream.getDeviceId());
            boolean b = docRelativeService.save(docRelative);
            if(!b) {
                ExceptionCast.cast(ActivitiCode.ACT_APPROVE_ERROR);
            }
 
        }
        handleFileTransfer(mdcEquipment, docFile);
        handleFileProcessing(docFile, mdcEquipment, whether, localFilePath);
        synchronizedFlagService.updateFlag(2);
        return Result.OK("操作成功");
    }
 
    @Override
    public AssignFileStreamExt getAssignFileStreamDetail(String streamId) {
        if(!ValidateUtil.validateString(streamId))
            return null;
        return super.getBaseMapper().getAssignFileStreamDetail(streamId);
    }
 
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean approveAssignFile(AssignFlowTaskVo assignFlowTaskVo) {
        if(!ValidateUtil.validateString(assignFlowTaskVo.getTaskId()) || !ValidateUtil.validateString(assignFlowTaskVo.getDataId()) || assignFlowTaskVo == 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);
        if(!ValidateUtil.validateInteger(assignFlowTaskVo.getStatus()))
            ExceptionCast.cast(ActivitiCode.ACT_STATUS_ERROR);
        AssignFileStream en = super.getById(assignFlowTaskVo.getDataId());
        if(en == null)
            ExceptionCast.cast(ActivitiCode.ACT_BUSINESS_DETAIL_ERROR);
        //flowable处理
        FlowTaskVo flowTaskVo = new FlowTaskVo();
        BeanUtils.copyProperties(assignFlowTaskVo, flowTaskVo);
        flowTaskService.complete(flowTaskVo);
        //更新对象封装
        AssignFileStream up = new AssignFileStream();
        up.setApproveContent(assignFlowTaskVo.getApproveContent());
        up.setStatus(assignFlowTaskVo.getStatus());
        up.setApproveUserId(userId);
        up.setApproveTime(DateUtil.getNow());
        up.setStreamId(assignFlowTaskVo.getDataId());
        boolean b = super.updateById(up);
        if(!b)
            ExceptionCast.cast(ActivitiCode.ACT_APPROVE_ERROR);
        if(up.getStatus() == 2) {
            DocInfo docInfo;
            //同意操作
            if (StrUtil.isNotEmpty(en.getStepId())){
                //工步指派
                docInfo = docInfoService.getByDocAttrAndDocId(en.getDocId(), 6, en.getStepId());
            }else {
                docInfo = docInfoService.getByDocAttrAndDocId(en.getDocId(), 5, en.getProcessId());
            }
            if(docInfo == null || docInfo.getDocStatus() == 3)
                ExceptionCast.cast(ActivitiCode.ACT_DOC_ERROR);
            MdcEquipment mdcEquipment = iMdcEquipmentService.getById(en.getDeviceId());
            if(mdcEquipment == null)
                ExceptionCast.cast(ActivitiCode.ACT_ASSIGN_DEVICE_NONE);
            DocFile docFile = docFileService.getById(en.getFileId());
            if(docFile == null)
                ExceptionCast.cast(ActivitiCode.ACT_FILE_ERROR);
            DocInfo deviceDoc = docInfoService.getByDocAttrAndDocId(en.getDocId(),4, en.getDeviceId());
            if(deviceDoc != null) {
                // 删除 备份  覆盖 原有的
                List<String> strings =  iMdcProductionService.findListParentTreeAll(mdcEquipment.getId());
                if (strings != null && !strings.isEmpty()) {
                    String path = StringUtils.join(strings.toArray(), "/");
                    boolean copyFileNc = FileUtilS.copyFileNcToBak(path + "/"+ mdcEquipment.getEquipmentId(),
                            docFile.getFileName(), docFile.getFileSuffix());
                  /*  //docInfoService.getBaseMapper().deleteById(deviceDoc.getDocId());
                    boolean doc = docRelativeService.deleteCopyDocByAttrNext(deviceDoc.getDocId(),4,stream.getDeviceId());
                    if (!doc) {
                        ExceptionCast.cast(ActivitiCode.ACT_DOC_ERROR_DELEVE);
                    }*/
                }
            } else {
                //插入文档到设备发送文档
                DocClassification classification = classificationService.getByCode(SEND_CODE);
                if(classification == null)
                    ExceptionCast.cast(DocumentCode.DOC_CLASS_ERROR);
 
                DocRelative docRelative = new DocRelative();
                docRelative.setDocId(docInfo.getDocId());
                docRelative.setClassificationId(classification.getClassificationId());
                docRelative.setAttributionType(4);
                docRelative.setAttributionId(en.getDeviceId());
                b = docRelativeService.save(docRelative);
            }
            if(!b)
                ExceptionCast.cast(ActivitiCode.ACT_APPROVE_ERROR);
            if (mdcEquipment != null) {
                List<String> strings =  iMdcProductionService.findListParentTreeAll(mdcEquipment.getId());
                if (strings != null && !strings.isEmpty()) {
                    String path = StringUtils.join(strings.toArray(), "/");
                    boolean copyFileNc = FileUtilS.copyFileNc(docFile.getFilePath(),path + "/"+ mdcEquipment.getEquipmentId(),
                            docFile.getFileEncodeName(),
                            docFile.getFileName(),docFile.getFileSuffix());
                    if (!copyFileNc) {
                        ExceptionCast.cast(ActivitiCode.ACT_FILE_ERROR);
                    } else {
                        FileUtilS.deleteZipFromToSend(path + "/"+ mdcEquipment.getEquipmentId(),
                                docFile.getFileName(),docFile.getFileSuffix());
                    }
                }
            }
            return synchronizedFlagService.updateFlag(1);
        }else if(up.getStatus() == 3) {
            //拒绝操作 什么也不做
            return true;
        }else {
            ExceptionCast.cast(ActivitiCode.ACT_APPROVE_ERROR);
        }
        return false;
    }
 
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean applyBatchAssignFile(AssignFileRequest assignFileRequest) {
        if(assignFileRequest == null)
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        String[] deviceIds = assignFileRequest.getDeviceIds();
        if(deviceIds == null || deviceIds.length < 1)
            ExceptionCast.cast(ActivitiCode.ACT_ASSIGN_DEVICE_NONE);
        AssignFileStream stream;
        for(String id : deviceIds) {
            stream = new AssignFileStream();
            stream.setProcessId(assignFileRequest.getProcessId());
            stream.setStepId(assignFileRequest.getStepId());
            stream.setDocId(assignFileRequest.getDocId());
            stream.setFileId(assignFileRequest.getFileId());
            stream.setApplyReason(assignFileRequest.getApplyReason());
            stream.setDeviceId(id);
            Result b = applyAssignFile(stream);
            if(!b.isSuccess())
                ExceptionCast.cast(ActivitiCode.ACT_APPLY_ERROR);
        }
        return true;
    }
 
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean approveBatchAssignFile(ApproveBatchRequest approveBatchRequest) {
        if(approveBatchRequest == null)
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        List<TaskRequest> list = approveBatchRequest.getTaskArr();
        if(list == null || list.isEmpty())
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
//        list.forEach(item -> {
//            AssignFileStream stream = new AssignFileStream();
//            stream.setApproveContent(approveBatchRequest.getApproveContent());
//            stream.setStatus(approveBatchRequest.getStatus());
//            boolean b = approveAssignFile(item.getId(), item.getBusinessKey(), stream);
//            if(!b)
//                ExceptionCast.cast(ActivitiCode.ACT_APPROVE_ERROR);
//        });
        return synchronizedFlagService.updateFlag(1);
    }
 
    @Override
    public Result<?> findPageList(int page, int size, AssignFileStreamQueryRequest request) {
        if(page < 1 || size < 1) {
            ExceptionCast.cast(CommonCode.INVALID_PAGE);
        }
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = user.getId();
        if(!ValidateUtil.validateString(userId))
            ExceptionCast.cast(UcenterCode.UCENTER_ACCOUNT_NOT_EXIST);
        LambdaQueryWrapper<AssignFileStreamExt> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(AssignFileStreamExt::getApproveUserId, userId);
        lambdaQueryWrapper.orderByDesc(AssignFileStreamExt::getApproveTime);
        IPage<AssignFileStreamExt> pageData = new Page<>(page, size);
        if(request != null) {
            if(ValidateUtil.validateString(request.getAscStr())) {
                String[] ascArr = request.getAscStr().split(",");
//                ((Page<AssignFileStreamExt>) pageData).setAsc(ascArr);
            }
            if(ValidateUtil.validateString(request.getDescStr())) {
                String[] descStr = request.getDescStr().split(",");
//                ((Page<AssignFileStreamExt>) pageData).setDesc(descStr);
            }
        }
        IPage<AssignFileStreamExt> streamExtIPage = super.getBaseMapper().findByPage(pageData, lambdaQueryWrapper);
        return Result.ok(streamExtIPage);
    }
 
    @Override
    public QueryPageResponseResult<AssignFileStreamExt> findPageListByDocId(int page, int size, String docId) {
        if(page < 1 || size < 1) {
            ExceptionCast.cast(CommonCode.INVALID_PAGE);
        }
        if(!ValidateUtil.validateString(docId))
            ExceptionCast.cast(ActivitiCode.ACT_DOC_ID_NONE);
        QueryWrapper<AssignFileStreamExt> queryWrapper =  Wrappers.query();
        queryWrapper.eq("a.doc_id", docId);
        queryWrapper.orderByDesc("approve_time");
        IPage<AssignFileStreamExt> pageData = new Page<>(page, size);
        IPage<AssignFileStreamExt> streamExtIPage = super.getBaseMapper().findByPage(pageData, queryWrapper);
        return new QueryPageResponseResult<>(CommonCode.SUCCESS, streamExtIPage);
    }
 
    @Override
    public Boolean getFlowableEnable(){
        if(flowableEnable != null) {
            return flowableEnable;
        }
        return false;
    }
 
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean transferDocFile(String pnCode, String deviceNo) {
        List<ProcessStream> streams = processStreamService.validateDeviceProcessInfo(pnCode, deviceNo);
        DeviceInfo deviceInfo = deviceInfoService.getByDeviceNo(deviceNo);
        if(deviceInfo == null)
            ExceptionCast.cast(DeviceCode.DEVICE_NOT_EXIST);
        //删除原来设备下的所有文档
        docRelativeService.deleteByDocAttr(4, deviceInfo.getDeviceId());
        List<DocInfo> docInfoList = docInfoService.getByProcessIds(streams);
        if(docInfoList == null || docInfoList.isEmpty())
            ExceptionCast.cast(DocumentCode.DOC_NOT_EXIST);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = user.getId();
        if(!ValidateUtil.validateString(userId))
            ExceptionCast.cast(UcenterCode.UCENTER_ACCOUNT_NOT_EXIST);
        for(DocInfo docInfo : docInfoList) {
            DocFile docFile = docFileService.getById(docInfo.getPublishFileId());
            if(docFile == null)
                ExceptionCast.cast(ActivitiCode.ACT_FILE_ERROR);
            //插入文档到设备发送文档
            DocClassification classification = classificationService.getByCode(SEND_CODE);
            if(classification == null)
                ExceptionCast.cast(DocumentCode.DOC_CLASS_ERROR);
            DocRelative docRelative = new DocRelative();
            docRelative.setDocId(docInfo.getDocId());
            docRelative.setClassificationId(classification.getClassificationId());
            docRelative.setAttributionType(4);
            docRelative.setAttributionId(deviceInfo.getDeviceId());
            boolean b = docRelativeService.save(docRelative);
            if(!b)
                ExceptionCast.cast(ActivitiCode.ACT_APPROVE_ERROR);
            //插入文件传输任务表
            ToEquipmentTask equipmentTask = new ToEquipmentTask();
            //不能直接从doc中拿fileId 和version  可能会存在斌更
            //equipmentTask.setFileId(docInfo.getPublishFileId());
            //equipmentTask.setDocVersion(docInfo.getPublishVersion());
            equipmentTask.setDocId(docInfo.getDocId());
            equipmentTask.setSyncFlag(1);
            equipmentTask.setDeviceNo(deviceInfo.getDeviceNo());
            equipmentTask.setDeviceId(deviceInfo.getDeviceId());
            equipmentTask.setDepartId(deviceInfo.getDepartId());
            //文件相关信息
            equipmentTask.setFileId(docFile.getFileId());
            equipmentTask.setDocVersion(docFile.getDocVersion());
            equipmentTask.setFileName(docInfo.getDocName());
            equipmentTask.setFileEncodeName(docFile.getFileEncodeName());
            equipmentTask.setFilePath(docFile.getFilePath());
            equipmentTask.setFileSuffix(docFile.getFileSuffix());
            equipmentTask.setFileSize(docFile.getFileSize());
            b = equipmentTaskService.save(equipmentTask);
            if(!b) {
                ExceptionCast.cast(ActivitiCode.ACT_APPROVE_ERROR);
            }
        }
        return synchronizedFlagService.updateFlag(1);
    }
 
    //传参验证
    private void validateParams(AssignFileStream stream) {
        if (stream == null) {
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        if (!ValidateUtil.validateString(stream.getAttributionId()) || !ValidateUtil.validateString(stream.getDocId())
                || !ValidateUtil.validateString(stream.getFileId()) || !ValidateUtil.validateString(stream.getAttributionType())) {
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        if (!ValidateUtil.validateString(stream.getDeviceId())) {
            ExceptionCast.cast(ActivitiCode.ACT_ASSIGN_DEVICE_NONE);
        }
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = user.getId();
        if (!ValidateUtil.validateString(userId)) {
            ExceptionCast.cast(UcenterCode.UCENTER_ACCOUNT_NOT_EXIST);
        }
    }
 
    //获取文件信息
    private DocInfo getDocInfo(AssignFileStream stream) {
        DocInfo docInfo = docInfoService.getByDocAttrAndDocId(stream.getDocId(), Integer.parseInt(stream.getAttributionType()), stream.getAttributionId());
        if (docInfo == null || docInfo.getDocStatus() == 3) {
            ExceptionCast.cast(ActivitiCode.ACT_DOC_ERROR);
        }
        return docInfo;
    }
 
    //获取文件
    private void handleExistingDeviceDoc(DocFile docFile, MdcEquipment mdcEquipment, String deviceId) {
        List<String> strings = iMdcProductionService.findListParentTreeAll(mdcEquipment.getEquipmentId());
        if (strings != null && !strings.isEmpty()) {
            String path = StringUtils.join(strings.toArray(), "/");
            boolean copyFileNc = FileUtilS.copyFileNcToBak(path + "/" + mdcEquipment.getEquipmentId(),
                    docFile.getFileName(), docFile.getFileSuffix());
            if (!copyFileNc) {
                ExceptionCast.cast(ActivitiCode.ACT_FILE_ERROR);
            } else {
                DocInfo deviceDoc = docInfoService.getByDocAttrAndDocId(deviceId, 4, deviceId);
                boolean doc = docRelativeService.deleteDocByAttr(deviceDoc.getDocId(), 4, deviceId);
                if (!doc) {
                    ExceptionCast.cast(ActivitiCode.ACT_DOC_ERROR_DELEVE);
                }
            }
        }
    }
 
    //权限校验
    private List<PermissionStream> getPermissionStreams(AssignFileStream stream) {
        List<PermissionStream> permissionStreams = new ArrayList<>();
        if (stream.getAttributionType().equals("5")) {
            // 工序
            ProcessStream processStream = processStreamService.getById(stream.getAttributionId());
            if (processStream == null) {
                ExceptionCast.cast(CommonCode.INVALID_PARAM);
            }
            stream.setProductId(processStream.getProductId());
            stream.setComponentId(processStream.getComponentId());
            stream.setPartsId(processStream.getPartsId());
            stream.setProcessId(processStream.getProcessId());
            permissionStreams = permissionStreamService
                    .getByProcessId(processStream.getProductId(), processStream.getComponentId(), processStream.getPartsId(), processStream.getProcessId());
        } else {
            // 工步
            WorkStep workStep = workStepService.getById(stream.getAttributionId());
            if (workStep == null) {
                ExceptionCast.cast(CommonCode.INVALID_PARAM);
            }
            stream.setProductId(workStep.getProductId());
            stream.setComponentId(workStep.getComponentId());
            stream.setPartsId(workStep.getPartsId());
            stream.setProcessId(workStep.getProcessId());
            stream.setStepId(workStep.getId());
            permissionStreams = permissionStreamService
                    .getByStepId(workStep.getProductId(), workStep.getComponentId(), workStep.getPartsId(), workStep.getProcessId(), workStep.getId());
        }
        if (permissionStreams == null || permissionStreams.isEmpty()) {
            ExceptionCast.cast(ActivitiCode.ACT_NODE_DEPART_NONE);
        }
        return permissionStreams;
    }
 
    //获取部门信息
    //todo 修改
    private List<String> getDepartIds(List<PermissionStream> permissionStreams, String userId) {
        Map<String, MdcProduction> map = iMdcProductionService.getUserAssignedDepart(userId);
        List<String> departIds = permissionStreams.stream()
                .filter(item -> map.containsKey(item.getDepartId()))
                .map(PermissionStream::getDepartId)
                .collect(Collectors.toList());
        if (departIds.isEmpty()) {
            ExceptionCast.cast(ActivitiCode.ACT_USER_NOT_PERM);
        }
        return departIds;
    }
 
    //获取多个部门的审批人 去重
    private List<String> getUserIdList(List<String> departIds) {
        List<String> userIdList = definitionService.getByDepartIds(departIds);
        if (userIdList == null || userIdList.isEmpty()) {
            ExceptionCast.cast(ActivitiCode.ACT_APPROVE_USERS_NONE);
        }
        return userIdList;
    }
 
    //封装数据
    private void saveBusinessObject(AssignFileStream stream, String userId) {
        String streamId = IdWorker.getIdStr();
        stream.setStreamId(streamId);
        stream.setApplyUserId(userId);
        stream.setApplyTime(DateUtil.getNow());
        stream.setStatus(1);
        boolean b = super.save(stream);
        if (!b) {
            ExceptionCast.cast(ActivitiCode.ACT_BUSINESS_SAVE_ERROR);
        }
    }
 
    //开始工作流
//    private ProcessInstance startProcessInstance(AssignFileStream stream, List<String> userIdList) {
//        String approveUsers = String.join(",", userIdList);
//        Map<String, Object> avariableMap = new HashMap<>();
//        avariableMap.put(APPLY_VARIABLE, stream.getApplyUserId());
//        avariableMap.put(APPROVE_VARIABLE, approveUsers);
//        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(PROCESS_KEY, stream.getStreamId(), avariableMap);
//        if (processInstance == null) {
//            ExceptionCast.cast(ActivitiCode.ACT_APPROVE_USERS_NONE);
//        }
//        return processInstance;
//    }
 
    //拾取任务
    private void completeTask(ProcessInstance processInstance, String userId) {
        Task task = taskService.createTaskQuery().processDefinitionKey(PROCESS_KEY).taskAssignee(userId)
                .processInstanceId(processInstance.getId()).singleResult();
        if (task == null) {
            ExceptionCast.cast(ActivitiCode.ACT_APPROVE_USERS_NONE);
        }
        taskService.complete(task.getId());
    }
 
    //获取设备
    private MdcEquipment getMdcEquipment(AssignFileStream stream) {
        MdcEquipment mdcEquipment = iMdcEquipmentService.getById(stream.getDeviceId());
        if (mdcEquipment == null) {
            ExceptionCast.cast(ActivitiCode.ACT_ASSIGN_DEVICE_NONE);
        }
        return mdcEquipment;
    }
 
    //获取文件
    private DocFile getDocFile(AssignFileStream stream) {
        DocFile docFile = docFileService.getById(stream.getFileId());
        if (docFile == null) {
            ExceptionCast.cast(ActivitiCode.ACT_FILE_ERROR);
        }
        return docFile;
    }
 
    //插入文件传输任务表
    private void handleFileTransfer(MdcEquipment mdcEquipment, DocFile docFile) {
        List<String> strings = iMdcProductionService.findListParentTreeAll(mdcEquipment.getId());
        if (strings != null && !strings.isEmpty()) {
            String path = StringUtils.join(strings.toArray(), "/");
            boolean copyFileNc = FileUtilS.copyFileNc(docFile.getFilePath(), path + "/" + mdcEquipment.getEquipmentId(),
                    docFile.getFileEncodeName(),
                    docFile.getFileName(), docFile.getFileSuffix());
            if (!copyFileNc) {
                ExceptionCast.cast(ActivitiCode.ACT_FILE_ERROR);
            } else {
                FileUtilS.deleteZipFromToSend(path + "/" + mdcEquipment.getEquipmentId(),
                        docFile.getFileName(), docFile.getFileSuffix());
            }
        } else {
            throw new RuntimeException("文件传输路径获取失败");
        }
    }
 
    //封装处理文件
    private void handleFileProcessing(DocFile docFile, MdcEquipment mdcEquipment, String whether, String localFilePath) {
        if (whether.equals("true") && !docFile.getFileSuffix().equals("zip") && !docFile.getFileSuffix().equals("rar")) {
            String size = FileUtilS.fileSizeNC(docFile.getFilePath(), docFile.getFileEncodeName());
            List<String> strings = iMdcProductionService.findListParentTreeAll(mdcEquipment.getId());
            if (strings != null && !strings.isEmpty()) {
                String path = StringUtils.join(strings.toArray(), "/");
                Date dateFirst = DateUtil.getNow();
                DncPassLog passInfoTxt = new DncPassLog();
                passInfoTxt.setDayTime(DateUtil.format(dateFirst, DateUtil.STR_YEARMONTHDAY));
                DncPassLog dncPassLog = dncPassLogService.findDayTime(DateUtil.format(dateFirst, DateUtil.STR_YEARMONTHDAY));
                Integer fileTxt = 0, fileNc = 0;
                if (dncPassLog != null) {
                    fileTxt = dncPassLog.getSequenceNumber() + 1;
                    fileNc = fileTxt + 1;
                } else {
                    fileTxt = 1;
                    fileNc = fileTxt + 1;
                }
                String sequence = String.format("%06d", fileTxt);
                String sequenceNc = String.format("%06d", fileNc);
                passInfoTxt.setSequenceNumber(fileTxt);
                passInfoTxt.setSequenceOrder(sequence);
                passInfoTxt.setCreateTime(dateFirst);
                passInfoTxt.setPassType("02");
                dncPassLogService.save(passInfoTxt);
 
                DncPassLog passInfoNc = new DncPassLog();
                passInfoNc.setSequenceNumber(fileNc);
                passInfoNc.setSequenceOrder(sequenceNc);
                passInfoNc.setDayTime(DateUtil.format(dateFirst, DateUtil.STR_YEARMONTHDAY));
                passInfoNc.setPassType("02");
                passInfoNc.setPassName(docFile.getFileName());
                try {
                    Thread.sleep(1000);
                    Date date = new Date();
                    passInfoNc.setCreateTime(date);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                dncPassLogService.save(passInfoNc);
 
                NcTxtFilePathInfo ncTxt = new NcTxtFilePathInfo();
                ncTxt.setEquipmentId(mdcEquipment.getEquipmentId());
                ncTxt.setFileNcName("02A" + DateUtil.format(dateFirst, DateUtil.STR_YEARMONTHDAY) + sequenceNc);
                ncTxt.setFileTxtName("02A" + DateUtil.format(dateFirst, DateUtil.STR_YEARMONTHDAY) + sequence);
                ncTxt.setFilePath(path + "/" + mdcEquipment.getEquipmentId() + "/");
                ncTxt.setOrigFileName(docFile.getFileName());
                ncTxt.setOrigFileSuffix(docFile.getFileSuffix());
                ncTxt.setFileAddOrDelete(1);
                String loFilePath = localFilePath + ncTxt.getFileTxtName() + ".nc";
                try {
                    String allList = ncTxt.getFileTxtName() + "\n"
                            + ncTxt.getFileNcName() + "\n"
                            + ncTxt.getOrigFileName() + "\n"
                            + ncTxt.getOrigFileSuffix() + "\n"
                            + ncTxt.getFilePath() + "\n"
                            + ncTxt.getEquipmentId() + "\n"
                            + ncTxt.getFileAddOrDelete().toString() + "\n"
                            + size + "\n";
                    FileUtilS.fileWriterSql(loFilePath, allList);
                    boolean copyFileNc = FileUtilS.copyFileUpName(path + "/" + mdcEquipment.getEquipmentId() + "/send/" +
                                    docFile.getFileName(),
                            localFilePath + ncTxt.getFileNcName(),
                            docFile.getFileSuffix(), "NC");
                    if (!copyFileNc) {
                        FileUtilS.deleteNcFile(loFilePath);
                    }
                } catch (IOException e) {
                    throw new RuntimeException("文件处理失败", e);
                }
            }
        }
    }
 
    @Override
    public void afterFlowHandle(FlowMyBusiness business) {
        business.getTaskNameId();//接下来审批的节点
        business.getValues();//前端传进来的参数
        business.getActStatus();
    }
 
    @Override
    public Object getBusinessDataById(String dataId) {
        return this.getById(dataId);
    }
 
    @Override
    public Map<String, Object> flowValuesOfTask(String taskNameId, Map<String, Object> values) {
        return null;
    }
 
    @Override
    public List<String> flowCandidateUsernamesOfTask(String taskNameId, Map<String, Object> values) {
        return Lists.newArrayList("jeecg");
    }
}