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
package com.whyc.service;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whyc.dto.FileDirPath;
import com.whyc.dto.MailDTO;
import com.whyc.dto.MaterialCheckDTO;
import com.whyc.dto.Response;
import com.whyc.mapper.MaterialMapper;
import com.whyc.pojo.*;
import com.whyc.util.DateUtil;
import com.whyc.util.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
 
@Service
public class MaterialService {
    @Autowired(required = false)
    private MaterialMapper mapper;
 
    @Autowired
    private MaterialHistoryService mhService;
 
    @Autowired
    private AttachLockService attachLockService;
 
    @Autowired
    private MailService mailService;
 
    @Autowired
    private MailUserService mailUserService;
 
    //查询所有的散装件信息加设置了替换关系的子件信息
    /*public Response getAllMaterial(String category,String subCode,String subName,String subModel,int pageCurr,int pageSize) {
        PageHelper.startPage(pageCurr,pageSize);
        *//*QueryWrapper wrapper=new QueryWrapper();
        wrapper.orderByAsc("id");
        List<Material> list=mapper.selectList(wrapper);*//*
        List<Material> list=mapper.getAllMaterial(category,subCode,subName,subModel);
        PageInfo pageInfo=new PageInfo(list);
        return new Response().setII(1,list.size()>0,pageInfo,"返回所有的散装件");
    }*/
    //查询所有的散装件信息不分页
    /*public Response getMaterialWithoutSub(String parentModel, String subName,int version) {
        List<Material> list=mapper.getMaterialWithoutSub(parentModel,subName,version);
        return new Response().setII(1,list.size()>0,list,"返回子件没有添加过联系的散装件");
    }*/
    //删除散装件(将散装件标识为不可用)
    /*public Response deleteMaterial(int id) {
        UpdateWrapper wrapper=new UpdateWrapper();
        wrapper.set("status",0);
        wrapper.eq("id",id);
        int bl=mapper.update(null,wrapper);
        return new Response().setII(1,bl>0,bl,"将散装件标识为不可用");
    }*/
 
    public List<Material> getList() {
        return mapper.selectList(null);
    }
 
    public void insertBatch(List<Material> MaterialList) {
        mapper.insertBatchSomeColumn(MaterialList);
    }
 
    /**mybatis-plus逻辑删除*/
    public void deleteBatch(List<Integer> MaterialIdList) {
        mapper.deleteBatchIds(MaterialIdList);
    }
 
    //查询所有物料(分页,模糊查询)
    public Response getMaterialLimit(String subCode, String subName, String subModel, int pageCurr, int pageSize) {
        PageHelper.startPage(pageCurr,pageSize);
        List<Material> list=mapper.getMaterialLimit(subCode,subName,subModel);
        String fileDirName = FileDirPath.getFileDirName();
        int flag=0;
        // 返回是否存在附件
        if(list!=null&&list.size()>0){
            for (Material m:list) {
                if(m.getFileUrl()!=null&&!m.getFileUrl().isEmpty()){
                    File file = new File(fileDirName+File.separator+m.getFileUrl());
                    if(!file.exists()) {
                        flag=0;
                    }else{
                        String[] fileNames = file.list();//获取该文件夹下的所有文件以及目录的名字
                        List attachFileList=new ArrayList();
                        if(fileNames.length>0){
                            flag=1;
                            for (int i=0;i<fileNames.length;i++){
                                if(!fileNames[i].contains("-dwg.pdf")&&!fileNames[i].contains("-doc.pdf"))
                                    attachFileList.add(fileNames[i]);
                            }
                        }else{
                            flag=0;
                        }
                        m.setAttachFileList(attachFileList);
                    }
                }
                m.setHasAttachFlag(flag);
            }
        }
        PageInfo pageInfo=new PageInfo(list);
        return new Response().setII(1,list.size()>0,pageInfo,"查询所有物料(分页,模糊查询)");
    }
    //建立关联时查询所有的物料(不分页)
    public Response getAllMaterialNoLimit() {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.ne("status",0);
        wrapper.orderByAsc("id");
        List<Material> list=mapper.selectList(wrapper);
        return new Response().setII(1,list.size()>0,list,"查询所有物料(不分页)");
    }
 
    public List<String> getListByCodeList(List<String> codeList) {
        return mapper.getListByCodeList(codeList);
    }
 
    public void updateDwgUrl(List<Material> materialDwgUrlNameList) {
        mapper.updateDwgUrl(materialDwgUrlNameList);
    }
 
    @Transactional
    public Response add(List<Material> materialList) {
        String fileUrl = materialList.get(0).getFileUrl();
        //校验物料合理性,非空校验:物料名称/物料编号/物料型号
        for (int i = 0; i < materialList.size(); i++) {
            Material material = materialList.get(i);
            if(material.getSubCode()==null ||material.getSubCode().equals("")
            || material.getSubName()==null ||material.getSubName().equals("")
            || material.getSubModel()==null ||material.getSubModel().equals("")){
                return new Response().set(1,false,"拒绝新增,物料名称/物料编号/物料型号存在空值");
            }
        }
        //检验物料重复性,已存在的物料,拒绝重复提交,判断依据:物料编码+物料型号
        List<Material> existList = getListByCodeAndModelList(materialList);
        if(existList!=null && existList.size()!=0){
            return new Response().setII(1,false,existList,"拒绝新增,物料重复提交");
        }
 
        //获取路径下的所有文件
        List<String> fileUrlList = new LinkedList<>();
        List<String> dwgUrlList = null;
        List<String> picUrlList = null;
        List<String> materialUrlList = new LinkedList<>();
 
        fileUrlList = FileUtil.getStaticFilePath(new File(fileUrl),fileUrlList);
        dwgUrlList = fileUrlList.stream().filter(url->url.contains(".dwg")).collect(Collectors.toList());
        picUrlList = fileUrlList.stream().filter(url->url.contains(".png") || url.contains(".jpeg")).collect(Collectors.toList());
        //图纸的url预设
        dwgUrlList.forEach(dwgUrl-> {
            materialList.forEach(material -> {
                String filename = dwgUrl.substring(dwgUrl.lastIndexOf(File.separator) + 1, dwgUrl.length() - 4);
                String fileFullName = dwgUrl.substring(dwgUrl.lastIndexOf(File.separator) + 1);
                if (material.getSubModel().toUpperCase().equals(filename.toUpperCase())) {
                    materialUrlList.add(dwgUrl);
 
                    material.setDwgUrl("doc_file" + File.separator + "material"
                            + File.separator + fileFullName);
                }
            });
        });
        //图片的url预设
        //一定是有对应物料的,从excel内剥离的
        picUrlList.forEach(picUrl->{
            for (Material material : materialList){
                String filename = picUrl.substring(picUrl.lastIndexOf(File.separator) + 1,picUrl.lastIndexOf("."));
                String fileFullName = picUrl.substring(picUrl.lastIndexOf(File.separator) + 1);
                if(material.getSubModel().toUpperCase().equals(filename.toUpperCase())){
                    material.setPictureUrl("doc_file" + File.separator + "material"
                            + File.separator + fileFullName);
                    break;
                }
            }
        });
        //图纸文件转移到正式文件夹
        String projectDir = CommonUtil.getProjectDir();
        String materialDir = projectDir + File.separator + "doc_file" + File.separator + "material";
        File materialFile = new File(materialDir);
        if(!materialFile.exists()){
            materialFile.mkdirs();
        }
        materialUrlList.forEach(materialUrl->{
            String dwgFullName = materialUrl.substring(materialUrl.lastIndexOf(File.separator) + 1);
            try {
                FileCopyUtils.copy(new File(materialUrl),new File(materialDir + File.separator + dwgFullName));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        picUrlList.forEach(picUrl->{
            String picFullName = picUrl.substring(picUrl.lastIndexOf(File.separator) + 1);
            try {
                FileCopyUtils.copy(new File(picUrl),new File(materialDir+File.separator+picFullName));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
 
        //新增,同时对于物料编码相同,物料型号不同的,禁用旧物料状态
        mapper.disableStatus(materialList);
        materialList.forEach(material -> {
            material.setStatus(1);
            material.setFileUrl(null);
        });
        mapper.insertBatchSomeColumn(materialList);
        return new Response().set(1,true,"新增完成");
    }
 
    private List<Material> getListByCodeAndModelList(List<Material> materialList) {
        return mapper.getListByCodeAndModelList(materialList);
    }
 
    public List<Material> getListByCodeAndModelList2(List<ProductBom> bomList) {
        return mapper.getListByCodeAndModelList2(bomList);
    }
 
    /**
     *
     * @param subCode 物料编码
     * @param subModel 物料型号
     * @param equalSubModel 是否等于物料型号,用于等于物料型号 或者 排除物料型号并且存在附件
     * @return
     */
    public Material getByCodeAndModel(String subCode, String subModel, boolean equalSubModel) {
        QueryWrapper<Material> query = Wrappers.query();
        query.eq("sub_code",subCode);
        if(equalSubModel) {
            query.eq("sub_model", subModel);
        }else{
            query.ne("sub_model", subModel);
            query.isNotNull("file_url");
        }
        query.orderByDesc("id");
        query.last(" limit 1");
        return mapper.selectOne(query);
    }
 
    public Response zipParse(MultipartFile file) throws IOException, InvalidFormatException {
        List<Material> list = new LinkedList<>();
        Response response = new Response();
        //检查是否为zip
        boolean isZip = Zip4jUtil.checkZipFileParam(file);
        if(!isZip){
            return response.set(1,false,"上传的文件格式不是zip");
        }
        //zip存储路径:doc_file/material_submit/${username}/{dateFormat}/${timeStamp}
        String rootFile = CommonUtil.getRootFile();
        DocUser user = ActionUtil.getUser();
        String dateFormat = new SimpleDateFormat("YYYY-MM").format(new Date());
        long timeStamp = System.currentTimeMillis();
        String filePath = rootFile + File.separator + "material_submit" + File.separator + user.getName() + File.separator + dateFormat+ File.separator + timeStamp;
        File parentFile = new File(filePath);
        String originalFilename = file.getOriginalFilename();
        File zipFile = new File(filePath+File.separator+ originalFilename);
        /*if(!zipFile.exists()){
            zipFile.mkdirs();
        }*/
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        file.transferTo(zipFile);
        //解压文件夹
        Zip4jUtil.unPackZip(zipFile,null,filePath);
        //遍历解压后的文件夹路径,解析excel
        System.out.println(filePath);
        List<String> fileList = new ArrayList<>();
        fileList = FileUtil.getStaticFilePath(parentFile,fileList);
        for (int i = 0; i < fileList.size(); i++) {
            String fileTempUrl = fileList.get(i);
            //查询到xls数据
            if(fileTempUrl.contains(".xls")){
                File fileTemp = new File(fileTempUrl);
                Workbook workbook = null;
                workbook = WorkbookFactory.create(fileTemp);
                List<? extends PictureData> allPictures = workbook.getAllPictures();
                //取第一个sheet表
                Sheet sheet = workbook.getSheetAt(0);
                int lastRowNum = sheet.getLastRowNum();
                //取第三行,并以第三行开始
                Row rowTemp = sheet.getRow(1);
                short lastCellNum = rowTemp.getLastCellNum();
                //先单独获取产品型号和版本号/分类
                Row row = sheet.getRow(1);
                String type = row.getCell(1).getStringCellValue();
 
                Row row2 = sheet.getRow(2);
                String productModel = row2.getCell(5).getStringCellValue();
                Row row3 = sheet.getRow(3);
                String productVersion = row3.getCell(5).getStringCellValue();
                for (int l = 8; l < lastRowNum-1; l++) {
                    Cell cellTemp = sheet.getRow(l).getCell(1);
                    cellTemp.setCellType(Cell.CELL_TYPE_STRING);
                    if(cellTemp.getStringCellValue().equals("")){
                        break;
                    }
                    Material material = new Material();
                    material.setCreateDate(new Date());
 
                    for (int m = 2; m < lastCellNum; m++) {
                        row = sheet.getRow(l);
                        Cell cell = row.getCell(m);
                        String cellValue = null;
                        int cellValueInt = 0;
                        Double cellValueDouble = null;
                        if(m == 3 || m==7){
                            //cellValueDouble = cell.getNumericCellValue();
                            //DecimalFormat decimalFormat = new DecimalFormat("0");
                            //cellValue = decimalFormat.format(cellValueDouble);
                            cell.setCellType(Cell.CELL_TYPE_STRING);
                        }
                        cellValue = cell.getStringCellValue();
 
                        switch (m){
                            //case 2:{material.setCategory(cellValue);}break;
                            case 3:{material.setSubCode(cellValue);}break;
                            case 4:{material.setSubName(cellValue);}break;
                            case 5:{material.setSubModel(cellValue);}break;
                            //case 6:{material.setMaterial(cellValue);}break;
                            //case 7:{material.setThickness(cellValue);}break;
                            //case 8:{material.setProducer(cellValue);}break;
                            //case 9:{material.setSurfaceDetail(cellValue);}break;
                            //case 10:{material.setNotes(cellValue);}break;
                            case 11:{
                                //图片从1开始,0是yc logo
                                PictureData pictureData = allPictures.get(l - 7);
                                String suffix = pictureData.suggestFileExtension();
                                String picturePath = filePath + File.separator + material.getSubModel() + "." + suffix;
                                String picturePathFront = "doc_file" + File.separator + "material_submit" + File.separator + user.getName() + File.separator + dateFormat + File.separator + timeStamp + File.separator + material.getSubModel() + "." + suffix;
                                byte[] data = pictureData.getData();
                                FileOutputStream fileOutputStream = null;
                                File pictureFile = new File(picturePath);
                                fileOutputStream = new FileOutputStream(pictureFile);
                                fileOutputStream.write(data);
 
                                material.setPictureUrl(picturePathFront);
                            }break;
                        }
                    }
                    list.add(material);
                }
            }
        }
        for (Material material : list) {
            if(material.getSubName()==null ||material.getSubName().equals("")){
                return response.set(1,false,"拒绝解析,excel文件中记录包含名称为空的记录");
            }
        }
        //追加物料规范校验 暂时去除校验
        /*List<MaterialCheckDTO> checkList = list.stream().map(material -> {
            MaterialCheckDTO dto = new MaterialCheckDTO();
            dto.setNum(material.getId());
            dto.setSubCode(material.getSubCode());
            dto.setSubName(material.getSubName());
            dto.setSubModel(material.getSubModel());
            return dto;
        }).collect(Collectors.toList());
        List<MaterialCheckDTO> irregularList = CommonUtil.checkFormat(checkList);
        if(irregularList.size()>0){
            return new Response().setII(1,false,irregularList,"名称或型号命名不规范");
        }*/
        return response.setII(1,true,list,filePath);
    }
    //根据物料id查询返回附件文件夹下所有的文件列表
    public Response getAttachByMaterialId(int materialId) {
        String fileDirName = FileDirPath.getFileDirName();
        Material material=mapper.getAttachByMaterialId(materialId);
        boolean flag=false;
        List list=new ArrayList();
        if(material.getFileUrl()!=null&&!material.getFileUrl().isEmpty()){
            File file = new File(fileDirName+File.separator+material.getFileUrl());
            if(!file.exists()) {
                flag=false;
            }else{
               String[] fileNames = file.list();//获取该文件夹下的所有文件以及目录的名字
                if(fileNames.length>0){
                    flag=true;
                    for (int i=0;i<fileNames.length;i++){
                        if(!fileNames[i].contains("-dwg.pdf")&&!fileNames[i].contains("-doc.pdf"))
                           list.add(material.getFileUrl()+File.separator+fileNames[i]);
                    }
                }
 
            }
        }
        return new Response().setII(1,flag,list,"文件列表返回");
    }
    //根据物料型号('-','_'之前的部分)查询物料的历史版本
    public Response getMaterialVersion(String subModel) {
        List list=mapper.getMaterialVersion(subModel);
        return new Response().setII(1,list.size()>0,list,"物料历史版本数据返回");
    }
    //根据物料id查询物料信息
    public Response getMaterialById(int materialId) {
        Material material=mapper.getMaterialById(materialId);
        String fileDirName = FileDirPath.getFileDirName();
        List list=new ArrayList();
        if(material.getFileUrl()!=null&&!material.getFileUrl().isEmpty()){
            File file = new File(fileDirName+File.separator+material.getFileUrl());
            if(file.exists()) {
                String[] fileNames = file.list();//获取该文件夹下的所有文件以及目录的名字
                if(fileNames.length>0){
                    for (int i=0;i<fileNames.length;i++){
                        if(!fileNames[i].contains("-dwg.pdf")&&!fileNames[i].contains("-doc.pdf"))
                            list.add(material.getFileUrl()+File.separator+fileNames[i]);
                    }
                }
 
            }
        }
        return new Response().setIII(1,material!=null,material,list,"物料历史版本数据返回");
    }
 
    /**
     * @param multipartFileList 被追加的附件,zip集合
     * @param material
     * @return 返回被追加文件的文件夹路径
     */
    @Transactional
    public Response addAttachment(List<MultipartFile> multipartFileList, Material material) throws IOException {
        List<String> currentFileList = new LinkedList<>();
        List<String> uploadingFileList = new LinkedList<>();
 
        String subModel = material.getSubModel();
        subModel = MaterialSpecialCharUtil.transfer(subModel);
        String dirPathDB = "doc_file" + File.separator + "material" + File.separator + material.getId() + "-"+ material.getSubCode() + "-" + subModel;
        String dirPath = CommonUtil.getRootFile() + "material" + File.separator + material.getId() + "-"+ material.getSubCode() + "-" + subModel;
        File dirFile = new File(dirPath);
 
        Date now = new Date();
        //long timestamp = now.getTime();
        String formattedTimestamp = DateUtil.YYYY_MM_DD_HH_MM_SS_UNION.format(now);
 
        boolean dirFileExist = true;
        if(!dirFile.exists()){
            dirFile.mkdirs();
            dirFileExist = false;
        }
        for (int i = 0; i < multipartFileList.size(); i++) {
            MultipartFile multipartFile = multipartFileList.get(i);
            String originalFilename = multipartFile.getOriginalFilename();
            File zipFile = new File(dirPath + File.separator + originalFilename.substring(0,originalFilename.lastIndexOf(".")) + "_" + formattedTimestamp + originalFilename.substring(originalFilename.lastIndexOf(".")));
            multipartFile.transferTo(zipFile);
        }
        /*//解压文件夹,删除原zip文件
        String unPackageDir = dirPath + File.separator + timestamp;
        Zip4jUtil.unPackZip(zipFile, null, unPackageDir);
        File unPackageFile = new File(unPackageDir);
        File[] unPackageFileList = unPackageFile.listFiles();
        zipFile.delete();
        for (int i = 0; i < unPackageFileList.length; i++) {
            File tempFile = unPackageFileList[i];
            if(tempFile.isDirectory()){
                FileUtil.deleteFile(unPackageFile);
                if(!dirFileExist){
                    FileUtil.deleteFile(dirFile);
                }
                return new Response().set(1,false,"拒绝上传:上传的压缩包存在文件夹");
            }
        }*/
 
        if(!dirFileExist){
            //路径不存在,说明是首次上传,设置物料对应的fileUrl
            Material temp = new Material();
            temp.setId(material.getId());
            temp.setFileUrl(dirPathDB);
            mapper.updateById(temp);
        }/*else{
            //查询路径下现有的所有文件
            String[] fileArr = dirFile.list();
            currentFileList = Arrays.asList(fileArr);
        }*/
 
        /*//查询新上传的文件路径
        String[] unPackageFileArr = unPackageFile.list();
        uploadingFileList = Arrays.asList(unPackageFileArr);
        for (String uploadingFile : uploadingFileList){
            if(currentFileList.contains(uploadingFile)){
                new File(unPackageDir + File.separator + uploadingFile)
                        .renameTo(new File(unPackageDir + File.separator  + uploadingFile.substring(0,uploadingFile.lastIndexOf(".")) + "_" + formattedTimestamp + uploadingFile.substring(uploadingFile.lastIndexOf("."))));
            }
        }
        //上传的文件夹转移到正式路径
        org.aspectj.util.FileUtil.copyDir(unPackageFile,dirFile);
        FileUtil.deleteFile(unPackageFile);*/
        /*0120开头的物料上传后,系统自动发邮件对应人员:吴浚、陈卓、熊家杰、钱镜元、於奇
          0108、0109开头的物料上传后,系统自动发邮件对应人员:喻艳、袁成、熊志平、叶胜蓝 */
        MailDTO mailDTO = new MailDTO();
        DocUser user = ActionUtil.getUser();
        mailDTO.setTitle("【附件更新提醒】");
        if(material.getSubCode().startsWith("0120")){
            List<MailUser> mailUserList = mailUserService.getMailUserList(5);
            mailDTO.setMailList(mailUserList.stream().map(MailUser::getMail).collect(Collectors.toList()));
            mailDTO.setContent(user.getName()+"在文档管理平台上传了0120开头的物料的附件,请知晓");
            mailService.sendMail(mailDTO);
        }else if (material.getSubCode().startsWith("0108")||material.getSubCode().startsWith("0109")){
            List<MailUser> mailUserList = mailUserService.getMailUserList(6);
            mailDTO.setMailList(mailUserList.stream().map(MailUser::getMail).collect(Collectors.toList()));
            mailDTO.setContent(user.getName()+"在文档管理平台上传了0108或0109开头的物料的附件,请知晓");
            mailService.sendMail(mailDTO);
        }
        return new Response().set(1,true,"上传完成");
    }
 
    /**
     * 转移 被复制的附件,到新的物料
     * @param materialDB .fileUrl 被复制的附件路径,例如:doc_file\material\8468-0109000512-SHIDA-2455-OLD-ZX_A01
     * @param material 新的物料
     * @return 返回被追加文件的文件夹路径
     */
    @Transactional
    public Response transferCopiedAttachment(Material materialDB, Material material) throws IOException {
        String fileUrlDir = materialDB.getFileUrl();
        String subModel = material.getSubModel();
        subModel = MaterialSpecialCharUtil.transfer(subModel);
        String dirPathDB = "doc_file" + File.separator + "material" + File.separator + material.getId() + "-"+ material.getSubCode() + "-" + subModel;
        String dirPath = CommonUtil.getRootFile() + "material" + File.separator + material.getId() + "-"+ material.getSubCode() + "-" + subModel;
        File dirFile = new File(dirPath);
 
        if(!dirFile.exists()){
 
            dirFile.mkdirs();
        }
        FileUtil.copyDirectory(new File(CommonUtil.getProjectDir() + File.separator + fileUrlDir),dirFile);
 
        //设置物料对应的fileUrl及物料状态
        Material temp = new Material();
        temp.setId(material.getId());
        temp.setFileUrl(dirPathDB);
        mapper.updateById(temp);
 
        attachLockService.getAndInsert(materialDB.getId(),material.getId());
 
 
        return new Response().set(1,true,"上传完成");
    }
 
    /**
     * @param multipartFile 更新的图纸或图片
     * @param material
     */
    @Transactional
    public Response updatePicOrDwg(MultipartFile multipartFile, Material material) throws IOException {
        List<String> currentFileList = new LinkedList<>();
        List<String> uploadingFileList = new LinkedList<>();
        String subModel = material.getSubModel();
        subModel = MaterialSpecialCharUtil.transfer(subModel);
        String dirPathDB = "doc_file" + File.separator + "material" + File.separator + material.getSubCode() + "-" + subModel;
        String dirPath = CommonUtil.getRootFile() + "material" + File.separator + material.getSubCode() + "-" + subModel;
        File dirFile = new File(dirPath);
 
        Date now = new Date();
        //long timestamp = now.getTime();
        String formattedTimestamp = DateUtil.YYYY_MM_DD_HH_MM_SS_UNION.format(now);
 
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
 
        String originalFilename = multipartFile.getOriginalFilename();
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String fileFullName = File.separator + originalFilename.substring(0, originalFilename.lastIndexOf(".")) + "_" + formattedTimestamp + originalFilename.substring(originalFilename.lastIndexOf("."));
        File zipFile = new File(dirPath + fileFullName);
        multipartFile.transferTo(zipFile);
 
        //路径不存在,说明是首次上传,设置物料对应的fileUrl
        //同时在物料历史里面添加记录
        Material temp = new Material();
        MaterialHistory mh = new MaterialHistory();
 
        temp.setId(material.getId());
        mh.setProductId(-1);
        mh.setMaterialId(material.getId());
        int userId = ActionUtil.getUser().getId().intValue();
        mh.setUpUserId(userId);
        mh.setCreateTime(now);
        if(fileSuffix.equals("dwg")){
            temp.setDwgUrl(dirPathDB + fileFullName);
            mh.setDwgUrl(dirPathDB + fileFullName);
        }else {
            temp.setPictureUrl(dirPathDB + fileFullName);
            mh.setPictureUrl(dirPathDB + fileFullName);
        }
        mapper.updateById(temp);
        mhService.insert(mh);
 
        /*0120开头的物料上传后,系统自动发邮件对应人员:吴浚、陈卓、熊家杰、钱镜元、於奇
          0108、0109开头的物料上传后,系统自动发邮件对应人员:喻艳、袁成、熊志平、叶胜蓝 */
        MailDTO mailDTO = new MailDTO();
        DocUser user = ActionUtil.getUser();
        mailDTO.setTitle("【图纸图片更新提醒】");
        if(material.getSubCode().startsWith("0120")){
            List<MailUser> mailUserList = mailUserService.getMailUserList(5);
            mailDTO.setMailList(mailUserList.stream().map(MailUser::getMail).collect(Collectors.toList()));
            mailDTO.setContent(user.getName()+"在文档管理平台上传了0120开头的物料的图纸或图片,请知晓");
            mailService.sendMail(mailDTO);
        }else if (material.getSubCode().startsWith("0108")||material.getSubCode().startsWith("0109")){
            List<MailUser> mailUserList = mailUserService.getMailUserList(6);
            mailDTO.setMailList(mailUserList.stream().map(MailUser::getMail).collect(Collectors.toList()));
            mailDTO.setContent(user.getName()+"在文档管理平台上传了0108或0109开头的物料的图纸或图片,请知晓");
            mailService.sendMail(mailDTO);
        }
        return new Response().set(1, true, "上传完成");
    }
    public Response dwgCompare(int materialId, int materialId2) throws IOException {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
 
        //获取各自物料的图纸
        String dwgUrl = mapper.selectById(materialId).getDwgUrl();
        String dwgUrl2 = mapper.selectById(materialId2).getDwgUrl();
        if(dwgUrl == null || dwgUrl2 == null){
            return new Response().set(1,false,"无法对比,所选物料至少有1个不存在图纸");
        }
        String dwgFileStr = CommonUtil.getProjectDir() + File.separator + dwgUrl;
        String dwgFileStr2 = CommonUtil.getProjectDir() + File.separator + dwgUrl2;
 
        String absoluteDwgPngPath = dwgFileStr.substring(0,dwgFileStr.lastIndexOf("."))+"-dwg.png";
        String absoluteDwgPngPath2 = dwgFileStr2.substring(0,dwgFileStr2.lastIndexOf("."))+"-dwg.png";
        if(!new File(absoluteDwgPngPath).exists()){
            DwgToPngUtil.dwg2png(new File(dwgFileStr));
        }
        if(!new File(absoluteDwgPngPath2).exists()) {
            DwgToPngUtil.dwg2png(new File(dwgFileStr2));
        }
 
        ByteArrayOutputStream stream = ImageDiff.compareImages(absoluteDwgPngPath, absoluteDwgPngPath2);
        return new Response().setII(1,true, Base64.encodeBase64String(stream.toByteArray()),null);
        //String fileName = "name.png";
        //OutputStream toClient = null;
        //try {
        //    response.setContentType("application/octet-stream");
        //    response.setHeader("Content-Disposition","attachment;filename=" + fileName);
        //    response.addHeader("Pragma", "no-cache");
        //    response.addHeader("Cache-Control", "no-cache");
        //    toClient = response.getOutputStream();
        //    stream.writeTo(toClient);
        //    //toClient.write(stream.toByteArray());
        //    toClient.flush();
        //    toClient.close();
        //} catch (IOException e) {
        //    e.printStackTrace();
        //}
        //
        //
        //return null;
    }
 
    public void updateDwgUrlAndPicUrl(List<Material> materialUpdateList) {
        mapper.updateDwgUrlAndPicUrl(materialUpdateList);
    }
 
    public List<Material> getSameSubCodeAndModel(List<ProductBom> bomList) {
        return mapper.getSameSubCodeAndModel(bomList);
    }
 
    public void checkNaming(InputStream inputStream, HttpServletResponse response) throws IOException, InvalidFormatException {
        List<MaterialCheckDTO> checkList = new LinkedList<>();
        Workbook workbook = null;
        workbook = WorkbookFactory.create(inputStream);
        inputStream.close();
        //取第一个sheet表
        Sheet sheet = workbook.getSheetAt(0);
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 1; i <= lastRowNum; i++) {
            System.out.println(i);
            //从第二行开始
            Row row = sheet.getRow(i);
            Cell cell = row.getCell(0);
            cell.setCellType(CellType.STRING);
            String code = cell.getStringCellValue();
            String name = row.getCell(1).getStringCellValue();
            Cell cell2 = row.getCell(2);
            cell2.setCellType(CellType.STRING);
            String model = cell2.getStringCellValue();
 
            MaterialCheckDTO dto = new MaterialCheckDTO();
            dto.setNum(i);
            dto.setSubName(name);
            dto.setSubCode(code);
            dto.setSubModel(model);
            checkList.add(dto);
        }
        List<MaterialCheckDTO> materialCheckDTOS = CommonUtil.checkFormat(checkList);
        int size = materialCheckDTOS.size();
        //ECR编号,申请日期,申请人,变更描述,变更料号,变更型号,变更所属型号,处理方式,创建时间
        String[] title = new String[]{"序号","物料编码","物料名称","规格型号","不规范原因"};
        String[][] values = new String[size][]; //size行
        for (int i = 0; i < size; i++) {
            values[i] = new String[5];
            MaterialCheckDTO dto = materialCheckDTOS.get(i);
            values[i][0] = dto.getNum().toString();
            values[i][1] = dto.getSubCode();
            values[i][2] = dto.getSubName();
            values[i][3] = dto.getSubModel();
            values[i][4] = dto.getIrregularDesc();
        }
        ExcelUtil.exportExcel("清单","物料",title,values,null,response);
    }
 
    public Material getLastByCode(String code) {
        QueryWrapper<Material> query = Wrappers.query();
        query.eq("sub_code",code).orderByDesc("id").last(" limit 1");
        return mapper.selectOne(query);
    }
    //物料推送弹窗使用
    public Response getMaterialDialog(String subCode, String subName, String subModel) {
        List<Material> list=mapper.getMaterialLimit(subCode,subName,subModel);
        String fileDirName = FileDirPath.getFileDirName();
        int flag=0;
        Material m=new Material();
        // 返回是否存在附件
        if(list!=null&&list.size()>0){
                m=list.get(list.size()-1);
                if(m.getFileUrl()!=null&&!m.getFileUrl().isEmpty()){
                    File file = new File(fileDirName+File.separator+m.getFileUrl());
                    if(!file.exists()) {
                        flag=0;
                    }else{
                        String[] fileNames = file.list();//获取该文件夹下的所有文件以及目录的名字
                        List attachFileList=new ArrayList();
                        if(fileNames.length>0){
                            flag=1;
                            for (int i=0;i<fileNames.length;i++){
                                if(!fileNames[i].contains("-dwg.pdf")&&!fileNames[i].contains("-doc.pdf"))
                                    attachFileList.add(fileNames[i]);
                            }
                        }else{
                            flag=0;
                        }
                        m.setAttachFileList(attachFileList);
                    }
                }
                m.setHasAttachFlag(flag);
            }
        return new Response().setII(1,m!=null,m,"物料推送弹窗使用");
    }
}