zss
2024-10-24 a00890e840b80a741f62eb6cb31b46f13be6202f
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
package com.yuanchu.mom.service.impl;
 
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
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.yuanchu.mom.common.GetLook;
import com.yuanchu.mom.common.PrintChina;
import com.yuanchu.mom.dto.*;
import com.yuanchu.mom.exception.ErrorException;
import com.yuanchu.mom.mapper.*;
import com.yuanchu.mom.pojo.*;
import com.yuanchu.mom.service.InsOrderPlanService;
import com.yuanchu.mom.service.InsOrderService;
import com.yuanchu.mom.service.InsProductService;
import com.yuanchu.mom.utils.GiveCode;
import com.yuanchu.mom.utils.QYWXApi;
import com.yuanchu.mom.utils.QueryWrappers;
import com.yuanchu.mom.vo.SampleDefectsFatherVo;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
 
/**
 * @author gaoaoy
 * @description 针对表【ins_order(检验下单)】的数据库操作Service实现
 * @createDate 2024-03-12 16:17:55
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class InsOrderServiceImpl extends ServiceImpl<InsOrderMapper, InsOrder> implements InsOrderService {
 
    @Resource
    private GetLook getLook;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private InsOrderMapper insOrderMapper;
 
    @Value("${file.path}")
    private String imgUrl;
 
    @Value("${wordUrl}")
    private String wordUrl;
    @Resource
    private InsOrderFileMapper insOrderFileMapper;
    @Resource
    private InsSampleMapper insSampleMapper;
    @Resource
    InsProductResult2Mapper insProductResult2Mapper;
    @Resource
    InsProductResultMapper insProductResultMapper;
    @Resource
    private WarehouseHistoryMapper warehouseHistoryMapper;
    @Resource
    private InsProductMapper insProductMapper;
    @Resource
    private InsProductService insProductService;
    @Resource
    private InsProductUserMapper insProductUserMapper;
    @Resource
    private GiveCode giveCode;
    @Resource
    private InsSampleUserMapper insSampleUserMapper;
    @Resource
    private InsOrderStateMapper insOrderStateMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    PowerMapper powerMapper;
    @Resource
    CustomMapper customMapper;
    @Resource
    QYWXApi qywxApi;
 
 
    //获取检验下单数据
    @Override
    public Map<String, Object> selectInsOrderParameter(IPage<InsOrder> page, SampleOrderDto sampleOrderDto) {
        Map<String, Object> map = new HashMap<>();
        map.put("head", PrintChina.printChina(SampleOrderDto.class));
        //判断全部,个人,组织的权限
        Map<String, Integer> map1 = getLook.selectPowerByMethodAndUserId("selectInsOrderParameter");
        User user = userMapper.selectById(map1.get("userId"));//当前登录的人
        Integer roleId = user.getRoleId();
        String laboratory = null;
        //判断是否是全部权限
        Power power = powerMapper.selectOne(Wrappers.<Power>lambdaQuery().eq(Power::getRoleId, roleId).eq(Power::getMenuMethod, "selectAllInsOrderParameter"));
        if (ObjectUtils.isEmpty(power)) {
            if (map1.get("look") == 1) {
                //个人
                sampleOrderDto.setCreateUser(map1.get("userId"));
            } else {
                //组织
                try {
                    sampleOrderDto.setCompany(customMapper.selectById(user.getCompany()).getCompany());
                } catch (NullPointerException e) {
                    throw new ErrorException("找不到所属单位");
                }
            }
        }
        IPage<SampleOrderDto> sampleOrderDtoIPage = insOrderMapper.selectInsOrderPage(page, QueryWrappers.queryWrappers(sampleOrderDto), laboratory);
        sampleOrderDtoIPage.getRecords().forEach(i -> {
            if (ObjectUtils.isNotEmpty(i.getSampleCode()) && i.getSampleCode().contains(",")) {
                String[] split = i.getSampleCode().split(",");
                i.setSampleCode(split[0]);
            }
        });
        map.put("body", sampleOrderDtoIPage);
        return map;
    }
 
    //分配站点
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int upInsOrder(Integer orderId, Integer sampleId, String appointed, Integer userId, String sonLaboratory) {
        InsOrder insOrder = new InsOrder();
        insOrder.setId(orderId);
        //insOrder.setAppointed(LocalDate.parse(appointed));
        insOrder.setSendTime(LocalDateTime.now());
        insOrderMapper.updateById(insOrder);
        //修改成只给当前选择的试验室下发单子
        InsOrderState insOrderState = new InsOrderState();
        insOrderState.setInsOrderId(orderId);
        insOrderState.setLaboratory(sonLaboratory);
        insOrderState.setInsState(0);
        insOrderState.setNum(1);//初始是第一次
        insOrderStateMapper.insert(insOrderState);
        //这里是在给分配的指定的人和试验室下发检验人
        if (userId != null) {
            InsSampleUser insSampleUser = new InsSampleUser();
            insSampleUser.setState(0);
            insSampleUser.setUserId(userId);
            insSampleUser.setInsSampleId(orderId);
            insSampleUser.setSonLaboratory(sonLaboratory);
            insSampleUserMapper.insert(insSampleUser);
        }
        return 1;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addInsOrder(List<SampleProductDto> list, InsOrder insOrder, List<List<Integer>> pairing, List<MultipartFile> files) {
        insOrder.setState(0);
        //判断选择的委托单位与制单人的委托单位是否一致
        Integer userId = getLook.selectPowerByMethodAndUserId(null).get("userId");
        String company = userMapper.selectById(userId).getCompany();
        if (!company.equals(insOrder.getCompanyId() + "")) {
            //如果不一致那么委托人字段必填
            if (ObjectUtils.isEmpty(insOrder.getPrepareUser())) {
                throw new ErrorException("委托人不能为空");
            }
        } else {
            //如果一致,那么制单人就是委托人
            insOrder.setPrepareUser(insOrder.getCustom());
        }
        //客户代号
        Custom custom = customMapper.selectById(insOrder.getCompanyId());
        String code = custom.getCode2();
        if (!custom.getCompany().equals(insOrder.getCompany())) {
            Custom one = customMapper.selectOne(Wrappers.<Custom>lambdaQuery().eq(Custom::getCompany, insOrder.getCompany()));
            insOrder.setCompanyId(one.getId());
            code = one.getCode2();
        }
        //外部委托编号
        insOrder.setOutEntrustCode(giveCode.giveCode("WT-", "ins_order", "-", "yyMMdd"));
        String giveCode = this.giveCode.giveCode("JCZX-" + code + "-", "ins_sample", "", "yyMMdd");
        insOrderMapper.insert(insOrder);
        AtomicInteger count = new AtomicInteger();
        list.forEach(a -> {
            count.getAndIncrement();
            a.setId(null);
            a.setInsOrderId(insOrder.getId());
            //样品编号
            if (StrUtil.isEmpty(a.getSampleCode())) {
                a.setSampleCode("YP-" + a.getModel() + "-" + giveCode.split("-")[2] + "-" + count.get());
            }
            insSampleMapper.insert(a);
            //样品的检验项目
            if (ObjectUtil.isNotEmpty(a.getInsProduct())) {
                addInsProductMethod(a.getId(), a.getInsProduct());
            }
            //样品的检验标准
            if (ObjectUtil.isNotEmpty(a.getInsulating())) {
                List<InsProduct> ip2 = new ArrayList<>();
                for (Integer i = 0; i < a.getInsulating().getNum(); i++) {
                    ip2.addAll(a.getInsulating().getInsProduct());
                }
                for (InsProduct product : ip2) {
                    product.setStandardMethodListId(a.getInsulating().getStandardMethodListId());
                }
                addInsProductMethod(a.getId(), ip2);
            }
            //样品的检验标准
            if (ObjectUtil.isNotEmpty(a.getSheath())) {
                for (InsProduct product : a.getSheath().getInsProduct()) {
                    product.setStandardMethodListId(a.getSheath().getStandardMethodListId());
                }
                addInsProductMethod(a.getId(), a.getSheath().getInsProduct());
            }
            //子样品配置
            if (ObjectUtil.isNotEmpty(a.getChildSampleList())) {
                for (SampleProductDto b : a.getChildSampleList()) {
                    for (int i = 0; i < b.getNum(); i++) {
                        b.setId(null);
                        b.setInsOrderId(insOrder.getId());
                        b.setParentId(a.getId());
                        if (StrUtil.isEmpty(b.getSampleCode())) {
                            b.setSampleCode(this.giveCode.giveCode("", "ins_sample", "", "yyMMdd"));
                        }
                        insSampleMapper.insert(b);
                        if (ObjectUtil.isNotEmpty(b.getInsProduct())) {
                            addInsProductMethod(b.getId(), b.getInsProduct());
                        }
                    }
                }
            }
 
        });
        //通信:如果是C类订单无需审核直接通过
        if (insOrder.getOrderType().equals("C")) {
            insOrder.setState(1);
            upInsOrderOfState(insOrder);
        }
        //如果有上传的附件
        if (CollectionUtils.isNotEmpty(files)) {
            for (MultipartFile file : files) {
                String urlString;
                String pathName;
                String path;
                String filename = file.getOriginalFilename();
                String contentType = file.getContentType();
                InsOrderFile insOrderFile = new InsOrderFile();
                insOrderFile.setInsOrderId(insOrder.getId());
                insOrderFile.setFileName(filename);
                if (contentType != null && contentType.startsWith("image/")) {
                    // 是图片
                    path = imgUrl;
                    insOrderFile.setType(1);
                } else {
                    // 是文件
                    path = wordUrl;
                    insOrderFile.setType(2);
                }
                try {
                    File realpath = new File(path);
                    if (!realpath.exists()) {
                        realpath.mkdirs();
                    }
                    pathName = UUID.randomUUID() + "_" + file.getOriginalFilename();
                    urlString = realpath + "/" + pathName;
                    file.transferTo(new File(urlString));
                    insOrderFile.setFileUrl(pathName);
                    insOrderFileMapper.insert(insOrderFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println("附件上传错误");
                }
            }
        }
        return insOrder.getId();
    }
 
    private void addInsProductMethod(Integer sampleId, List<InsProduct> productList) {
        for (InsProduct product : productList) {
            if (product.getState() == 1) {
                product.setId(null);
                product.setCreateTime(null);
                product.setCreateUser(null);
                product.setUpdateTime(null);
                product.setUpdateUser(null);
                product.setInsSampleId(sampleId);
                if (product.getInspectionItemSubclass() == null) {
                    product.setInspectionItemSubclass("");
                }
                insProductMapper.insert(product);
            }
        }
    }
 
    @Override
    public Map<String, Object> getInsOrder(Integer id) {
        Map<String, Object> map = new HashMap<>();
        InsOrder insOrder = insOrderMapper.selectById(id);
        List<SampleProductDto> list = insSampleMapper.selectSampleProductListByOrderId2(id);
        if (list.size() == 0) {
            list = insSampleMapper.selectSampleProductListByOrder2Id2(id);
        }
        map.put("insOrder", insOrder);
        map.put("sampleProduct", list);
        return map;
    }
 
    @Override
    public int upInsOrderOfState(InsOrder insOrder) {
        InsOrder order = insOrderMapper.selectById(insOrder.getId());
        insOrder.setCompany(order.getCompany());
        insOrder.setExamineTime(LocalDateTime.now());
        if (insOrder.getState() == 1) {
            //审核通过才会生成委托编号
            insOrder.setEntrustCode(giveCode.giveCode2("WT-", "ins_order", "-", "yyMMdd"));
            insOrder.setSendTime(LocalDateTime.now());
            /*todo 根据订单类型判断是否需要推送企业微信 @zss*/
            /*if (!order.getFormType().equals("其他成品")) {
                String account = userMapper.selectById(order.getIssueUser()).getAccount();
                HashMap<String, Object> map = new HashMap<>();
                map.put("touser", account);//接收消息成员的账号'ZT-031292'这种类型(如果有多个用'|'分隔)
                map.put("msgtype", "text");//消息类型 text:文本
                map.put("agentid", 1000517);//应用id
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("content", "您有一条订单需要完成,请前往LIMS系统查看。订单号是:"+order.getEntrustCode()+",请前往LIMS系统查看。<a href=\"https://ztwxlims.ztt.cn:7443/enter\">中天通信LIMS系统 </a>");
                map.put("text", hashMap);//消息内容
                map.put("safe", 0);//是否保密消息.0否
                map.put("enable_id_trans", 0);//是否开启id转译.0否
                map.put("enable_duplicate_check", 0);//是否开启重复消息检查.0否
                qywxApi.send(map);
            }*/
        }
        return insOrderMapper.updateById(insOrder);
    }
 
    @Override
    public int upInsOrderOfState2(InsOrder insOrder) {
        InsOrder order = insOrderMapper.selectById(insOrder.getId());
        //获取当前人
        Integer userId = getLook.selectPowerByMethodAndUserId(null).get("userId");
        //获取当前人的角色
        String roleName = roleMapper.selectById(userMapper.selectById(userId).getRoleId()).getName();
        //判断是检测中心主任/研发部经理/技术负责人
        switch (roleName) {
            case "检测中心主任":
                order.setCheckState1(insOrder.getState());
                order.setCheckState1User(userId);
                break;
            case "研发部经理":
                order.setCheckState2(insOrder.getState());
                order.setCheckState2User(userId);
                break;
            case "技术负责人":
                order.setCheckState3(insOrder.getState());
                order.setCheckState3User(userId);
                break;
            default:
                throw new ErrorException("当前登录用户的角色不是检测中心主任/研发部经理/技术负责人,无法进行审核");
        }
        insOrderMapper.updateById(order);
        //查询该订单是A类还是B类
        if (order.getOrderType().equals("B")) {
            //如果是B类,1和2和3都审核通过这个单子就审核通过
            if (order.getCheckState1() == 1 && order.getCheckState2() == 1 && order.getCheckState3() == 1) {
                order.setState(1);
                upInsOrderOfState(order);
            } else if (order.getCheckState1() == 2 || order.getCheckState2() == 2 || order.getCheckState3() == 2) {
                order.setState(2);
                upInsOrderOfState(order);
            }
        } else if (order.getOrderType().equals("A")) {
            //如果是A类,1和2审核通过后这个单子就审核通过
            if (order.getCheckState1() == 1 && order.getCheckState2() == 1) {
                order.setState(1);
                upInsOrderOfState(order);
            } else if (order.getCheckState1() == 2 || order.getCheckState2() == 2) {
                order.setState(2);
                upInsOrderOfState(order);
            }
        }
        return 1;
    }
 
    @Override
    public Map<String, Object> getInsOrderAndSample(Integer id, String laboratory) {
        Map<String, Object> map = new HashMap<>();
        InsOrder insOrder = insOrderMapper.selectById2(id);
        List<SampleProductDto> insSamples = insSampleMapper.selectList1(insOrder.getId());
        List<SampleProductDto> list = insSampleMapper.getInsOrderAndSample(id, laboratory);
        //再次试验会出现为空的情况
        if (list.size() != insSamples.size()) {
            List<Integer> ids = list.stream().map(sampleProductDto -> sampleProductDto.getId()).distinct().collect(Collectors.toList());
            List<SampleProductDto> samples = insSamples.stream().filter(insSample ->
                    !ids.contains(insSample.getId())
            ).collect(Collectors.toList());
            for (SampleProductDto insSample : samples) {
                List<InsProduct> insProducts = insProductMapper.selectList(Wrappers.<InsProduct>lambdaQuery()
                        .eq(InsProduct::getInsSampleId, insSample.getId())
                        .eq(InsProduct::getState, 1)
                        .eq(InsProduct::getSonLaboratory, laboratory));
                for (InsProduct insProduct : insProducts) {
                    List<InsProductResult2> insProductResult2List = insProductResult2Mapper.selectList(Wrappers.<InsProductResult2>lambdaQuery()
                            .eq(InsProductResult2::getInsProductId, insProduct.getId()).isNull(InsProductResult2::getNum));
                    insProduct.setInsProductResult2(insProductResult2List);
                    InsProductResult insProductResult = insProductResultMapper.selectOne(Wrappers.<InsProductResult>lambdaQuery()
                            .eq(InsProductResult::getInsProductId, insProduct.getId()).isNull(InsProductResult::getNum));
                    insProduct.setInsProductResult(insProductResult);
                }
                insSample.setInsProduct(insProducts);
                list.add(insSample);
            }
 
        }
        for (SampleProductDto sampleProductDto : list) {
            List<Integer> ids = sampleProductDto.getInsProduct().stream().map(InsProduct::getId).collect(Collectors.toList());
            List<InsProductUser> insProductUsers = insProductUserMapper.selectList(Wrappers.<InsProductUser>lambdaQuery()
                    .in(InsProductUser::getInsProductId, ids));
            if (CollectionUtils.isNotEmpty(insProductUsers)) {
                List<Integer> userIds = insProductUsers.stream().map(InsProductUser::getCreateUser).distinct().collect(Collectors.toList());
                String collect = userMapper.selectBatchIds(userIds).stream().map(User::getName).collect(Collectors.joining(","));
                sampleProductDto.setCheckName(collect);
            }
        }
        map.put("insOrder", insOrder);
        map.put("sampleProduct", list);
        //查询所有记录模版去重
        List<Map<Integer, Object>> list2 = insOrderMapper.selectReportModelByOrderId(id, laboratory);
        map.put("reportModel", list2);
        return map;
    }
 
    @Override
    public Map<String, Object> selectSampleAndProductByOrderId(IPage<SampleProductDto2> page, SampleProductDto2 sampleProductDto) {
        Map<String, Object> map = new HashMap<>();
        map.put("head", PrintChina.printChina(SampleProductDto2.class));
        IPage<SampleProductDto2> productDto2IPage = insOrderMapper.selectSampleAndProductByOrderId(page, QueryWrappers.queryWrappers(sampleProductDto).orderByAsc("inspection_item"), sampleProductDto.getId());
        for (SampleProductDto2 record : productDto2IPage.getRecords()) {
            InsProductUser insProductUser = insProductUserMapper.selectOne(Wrappers.<InsProductUser>lambdaQuery()
                    .eq(InsProductUser::getInsProductId, record.getInsProductId())
                    .orderByDesc(InsProductUser::getCreateTime)
                    .last("limit 1"));
            if (ObjectUtils.isNotEmpty(insProductUser)) {
                record.setCheckName(userMapper.selectById(insProductUser.getCreateUser()).getName());
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                record.setCheckTime(insProductUser.getCreateTime().format(formatter));
            }
        }
        map.put("body", productDto2IPage);
        return map;
    }
 
    @Override
    public Map<String, Object> costStatistics(IPage<CostStatisticsDto> page, CostStatisticsDto costStatisticsDto) {
        String dates = costStatisticsDto.getDates();
        String[] split = dates.replaceAll("\\[", "").replaceAll("]", "").replaceAll("\"", "").split(",");
        costStatisticsDto.setDates(null);
        Map<String, Object> map = new HashMap<>();
        map.put("head", PrintChina.printChina(CostStatisticsDto.class));
        Map<String, Integer> map1 = getLook.selectPowerByMethodAndUserId("costStatistics");
        if (map1.get("look") == 1) costStatisticsDto.setCreateUser(map1.get("userId"));
        IPage<CostStatisticsDto> dtoIPage = insOrderMapper.selectCostStatistics(page, QueryWrappers.queryWrappers(costStatisticsDto).ge("create_time", split[0]).le("create_time", split[1] + " 23:59:59"));
        List<CostStatisticsDto> collect = dtoIPage.getRecords().stream().map(dto -> {
            Set<String> uniqueTags = new HashSet<>();
            if (dto.getInspectionItem().contains(",")) {
                for (String s : dto.getInspectionItem().split(",")) {
                    uniqueTags.add(s.split("@")[0]);
                }
            } else {
                uniqueTags.add(dto.getInspectionItem().split("@")[0]);
            }
            dto.setInspectionItem(uniqueTags.toString());
            return dto;
        }).collect(Collectors.toList());
        dtoIPage.setRecords(collect);
        map.put("body", dtoIPage);
        return map;
    }
 
    @Override
    public Map<String, Object> costStatistics2(CostStatisticsDto costStatisticsDto) {
        Map<String, Object> map = new HashMap<>();
        String dates = costStatisticsDto.getDates();
        String[] split = dates.replaceAll("\\[", "").replaceAll("]", "").replaceAll("\"", "").split(",");
        costStatisticsDto.setDates(null);
        List<CostStatisticsDto> costStatisticsDtos = insOrderMapper.selectCostStatistics2(QueryWrappers.queryWrappers(costStatisticsDto).ge("create_time", split[0]).le("create_time", split[1] + " 23:59:59"));
        double totalPrice = costStatisticsDtos.stream()
                .filter(dto -> dto.getPrice() != null) // 过滤掉价格为 null 的对象
                .mapToDouble(value -> value.getPrice().doubleValue() * value.getNum())
                .sum();
        BigDecimal bd = new BigDecimal(totalPrice).setScale(2, RoundingMode.HALF_UP);
        double roundedTotalPrice = bd.doubleValue();
        map.put("total", roundedTotalPrice);
        return map;
    }
 
    @Override
    public Map<String, Object> selectSampleDefects(Page page, String inspectionItems, String orderNumber) {
        List<SampleDefectsFatherVo> sampleDefectsFatherVos = insOrderMapper.selectSampleDefects(page, inspectionItems, orderNumber);
        Map<String, Object> map = new HashMap<>();
        map.put("records", sampleDefectsFatherVos);
        Long aLong = insOrderMapper.getCount(inspectionItems, orderNumber);
        map.put("total", aLong);
        return map;
    }
 
    @Override
    public int updateStatus(Integer id) {
        return insOrderMapper.updateStatus(id);
    }
 
    //标签打印
    @Override
    public List<SampleProductDto3> labelPrinting(String ids) {
        List<Integer> list = Arrays.stream(ids.split(",")).map(Integer::parseInt).collect(Collectors.toList());
        List<SampleProductDto3> sampleProductDtos = insSampleMapper.selectSampleProductListByOrderId3(list);
        Set<String> processedCodes = new HashSet<>();
       /* List<SampleProductDto3> sampleProductDto3s = sampleProductDtos.stream().filter(sampleProductDto3 -> {
            if (processedCodes.contains(sampleProductDto3.getCode())) {
                return false;
            } else {
                processedCodes.add(sampleProductDto3.getCode());
                return true;
            }
        }).collect(Collectors.toList());*/
        return sampleProductDtos;
    }
 
    //校验电机编号
    @Override
    public Map<String, List<InsSample>> checkNumber(String ids) {
        List<InsSample> samples = new ArrayList<>();
        List<Integer> list = Arrays.stream(ids.split(",")).map(Integer::parseInt).collect(Collectors.toList());
        List<InsSample> sampleDtos = insSampleMapper.selectInsSample(list);
        //判断样品型号是否是BZ
        for (InsSample sampleDto : sampleDtos) {
            if (sampleDto.getModel().contains("BZ")) {
                if (ObjectUtils.isEmpty(sampleDto.getMotorNumber())) {
                    samples.add(sampleDto);
                }
            }
        }
        if (CollectionUtils.isNotEmpty(samples)) {
            Map<String, List<InsSample>> collect = samples.stream().collect(Collectors.groupingBy(InsSample::getEntrustCode));
            return collect;
        } else return null;
    }
 
    @Override
    public void export(CostStatisticsDto costStatisticsDto, HttpServletResponse response) throws IOException {
        //查询导出的费用统计数据
        String dates = costStatisticsDto.getDates();
        String[] split = dates.replaceAll("\\[", "").replaceAll("]", "").replaceAll("\"", "").split(",");
        costStatisticsDto.setDates(null);
        List<CostStatisticsDto> costStatisticsDtos = insOrderMapper.selectCostStatistics2(QueryWrappers.queryWrappers(costStatisticsDto).ge("create_time", split[0]).le("create_time", split[1] + " 23:59:59"));
        costStatisticsDtos = costStatisticsDtos.stream().map(dto -> {
            Set<String> uniqueTags = new HashSet<>();
            if (dto.getInspectionItem().contains(",")) {
                for (String s : dto.getInspectionItem().split(",")) {
                    uniqueTags.add(s.split("@")[0]);
                }
            } else {
                uniqueTags.add(dto.getInspectionItem().split("@")[0]);
            }
            dto.setInspectionItem(uniqueTags.toString());
            return dto;
        }).collect(Collectors.toList());
 
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("样品费用统计导出", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        Map<String, List<CostStatisticsDto>> groupByCompany =
                costStatisticsDtos.stream().filter(e -> StrUtil.isNotEmpty(e.getCompany()))
                        .collect(Collectors.groupingBy(CostStatisticsDto::getCompany));
        try {
            // 新建ExcelWriter
            // 新建ExcelWriter
            ExcelWriter excelWriter =
                    EasyExcel.write(response.getOutputStream())
                            .registerWriteHandler(new SimpleColumnWidthStyleStrategy(25))
                            .build();
            for (Map.Entry<String, List<CostStatisticsDto>> companyDataEntry : groupByCompany.entrySet()) {
                String sheetName = companyDataEntry.getKey();
                List<CostStatisticsDto> dataList = companyDataEntry.getValue();
                WriteSheet mainSheet = EasyExcel.writerSheet(sheetName)
                        .head(CostStatisticsDto.class)
                        .registerWriteHandler(new SimpleColumnWidthStyleStrategy(25))
                        .build();
                excelWriter.write(dataList, mainSheet);
            }
            // 关闭流
            excelWriter.finish();
        } catch (IOException e) {
            throw new RuntimeException("导出失败");
        }
    }
 
    @Override
    public int addNumber(List<InsSample> insSamples) {
        for (InsSample insSample : insSamples) {
            insSampleMapper.updateById(insSample);
        }
        return 0;
    }
}