zss
2025-03-06 fd7bc95a3c91fb7d90a921b0ff762fa6095fabd1
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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
package com.ruoyi.inspect.service.impl;
 
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
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.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.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.entity.Custom;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.User;
 
import com.ruoyi.common.numgen.NumberGenerator;
import com.ruoyi.common.utils.EasyExcelUtils;
import com.ruoyi.common.utils.QueryWrappers;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.exception.ErrorException;
import com.ruoyi.inspect.dto.*;
import com.ruoyi.inspect.excel.FiberRibboGeometricalParameterExcelData;
import com.ruoyi.inspect.mapper.*;
import com.ruoyi.inspect.pojo.*;
import com.ruoyi.inspect.service.InsOrderService;
import com.ruoyi.inspect.service.InsProductService;
import com.ruoyi.inspect.vo.ExportInsProductVO;
import com.ruoyi.inspect.vo.SampleDefectsFatherVo;
import com.ruoyi.system.mapper.CustomMapper;
import com.ruoyi.system.mapper.UserMapper;
import com.ruoyi.system.service.ISysDictTypeService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
 
import javax.servlet.http.HttpServletResponse;
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.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
 
/**
 * @author gaoaoy
 * @description 针对表【ins_order(检验下单)】的数据库操作Service实现
 * @createDate 2024-03-12 16:17:55
 */
@Service
@Slf4j
@AllArgsConstructor
public class InsOrderServiceImpl extends ServiceImpl<InsOrderMapper, InsOrder>
        implements InsOrderService {
 
    private InsOrderMapper insOrderMapper;
 
    private InsSampleMapper insSampleMapper;
 
    private InsProductMapper insProductMapper;
 
    private InsProductService insProductService;
 
    private InsProductUserMapper insProductUserMapper;
 
    private NumberGenerator<InsOrder> numberGenerator;
 
    private InsSampleUserMapper insSampleUserMapper;
 
    private InsOrderStateMapper insOrderStateMapper;
 
    UserMapper userMapper;
 
    private InsBushingMapper insBushingMapper;
 
    private InsFibersMapper insFibersMapper;
 
    private InsFiberMapper insFiberMapper;
 
    private InsProductResultMapper insProductResultMapper;
 
    CustomMapper customMapper;
 
    private ISysDictTypeService dictTypeService;
 
    private ProcessOrder1Mapper processOrderMapper;
 
 
    //获取检验下单数据
    @Override
    public Map<String, Object> selectInsOrderParameter(Page<InsOrder> page, SampleOrderDto sampleOrderDto) {
        page.setOptimizeCountSql(false);
        List<String> startAndEndTime = sampleOrderDto.getStartAndEndTime();
        String startTime = "";
        String endTime = "";
        if (CollectionUtils.isNotEmpty(startAndEndTime)) {
            startTime = startAndEndTime.get(0) + " 00:00:00";
            endTime = startAndEndTime.get(1) + " 23:59:59";
        }
 
        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();
//        //获取当前人所属实验室id
//        String departLimsId = user.getDepartLimsId();
        String laboratory = null;
//        if (ObjectUtils.isNotEmpty(departLimsId) && !departLimsId.isEmpty()) {
//            String[] split = departLimsId.split(",");
//            //查询对应架构名称(通信实验室,电力实验室,检测办)
//            String departLims = baseMapper.seldepLimsId(Integer.parseInt(split[split.length - 1]));
//            if (departLims.contains("实验室")) {
//                laboratory = departLims;
//            }
//        }
//        //判断是否是全部权限
//        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("找不到所属单位");
//                }
//            }
//        }
        Integer state = sampleOrderDto.getState();
        sampleOrderDto.setState(null);
        IPage<SampleOrderDto> sampleOrderDtoIPage = insOrderMapper.selectInsOrderPage(page, QueryWrappers.queryWrappers(sampleOrderDto), laboratory, startTime, endTime, String.valueOf(state), null);
        if (sampleOrderDtoIPage.getRecords().isEmpty() && (StringUtils.isNotBlank(sampleOrderDto.getEntrustCode()) || StringUtils.isNotBlank(sampleOrderDto.getOutEntrustCode()))) {
            QueryWrapper<SampleOrderDto> wrapper = QueryWrappers.queryWrappers(sampleOrderDto);
            IPage<InsOrder> orderPage = new Page<>();
            BeanUtil.copyProperties(page, orderPage);
            IPage<SampleOrderDto> otherPage = insOrderMapper.selectInsOrderPage(orderPage, wrapper, laboratory, startTime, endTime, null, String.valueOf(state));
            if (1 == otherPage.getRecords().size()) {
                sampleOrderDtoIPage = otherPage;
            }
        }
        sampleOrderDtoIPage.getRecords().parallelStream().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(UpInsOrderDTO upInsOrderDTO) {
        InsOrder insOrder = new InsOrder();
        insOrder.setId(upInsOrderDTO.getOrderId());
        insOrder.setAppointed(LocalDate.parse(upInsOrderDTO.getAppointed()));
        insOrder.setSendTime(LocalDateTime.now());
        insOrderMapper.updateById(insOrder);
        List<InsSample> insSamples = insSampleMapper.selectList(Wrappers.<InsSample>lambdaQuery().eq(InsSample::getInsOrderId, upInsOrderDTO.getOrderId()).select(InsSample::getId));
        List<Integer> ids = insSamples.stream().map(InsSample::getId).collect(Collectors.toList());
        List<InsProduct> insProducts = insProductMapper.selectList(Wrappers.<InsProduct>lambdaQuery()
                .in(InsProduct::getInsSampleId, ids)
                .eq(InsProduct::getState, 1)
//                .isNull(InsProduct::getInsFibersId)
//                .isNull(InsProduct::getInsFiberId)
                .select(InsProduct::getSonLaboratory).groupBy(InsProduct::getSonLaboratory));
        //查询ins_order_state,没有才新增
        long count = insOrderStateMapper.selectCount(Wrappers.<InsOrderState>lambdaQuery().eq(InsOrderState::getInsOrderId, upInsOrderDTO.getOrderId()));
        if (count == 0) {
            for (InsProduct insProduct : insProducts) {
                InsOrderState insOrderState = new InsOrderState();
                insOrderState.setInsOrderId(upInsOrderDTO.getOrderId());
                try {
                    insOrderState.setLaboratory(insProduct.getSonLaboratory());
                } catch (NullPointerException e) {
                    throw new ErrorException("该检验单有未维护实验室的检验项目");
                }
                insOrderState.setInsState(0);
                insOrderStateMapper.insert(insOrderState);
            }
        }
        //添加样品检验人员
        if (CollectionUtils.isNotEmpty(upInsOrderDTO.getUserIdList())) {
            upInsOrderDTO.getUserIdList().forEach(userId -> {
                InsSampleUser insSampleUser = new InsSampleUser();
                insSampleUser.setState(0);
                insSampleUser.setUserId(userId);
                insSampleUser.setInsSampleId(upInsOrderDTO.getOrderId());
                insSampleUser.setSonLaboratory(upInsOrderDTO.getSonLaboratory());
                insSampleUserMapper.insert(insSampleUser);
            });
        }
        return 1;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addInsOrder(List<SampleProductDto> list, InsOrder insOrder, List<List<Integer>> pairing, List<List<Integer>> fiberPairing) {
        insOrder.setState(0);
        //判断选择的委托单位与制单人的委托单位是否一致
        Integer userId = 1;
        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 customCode = custom.getCode2();
        if (!custom.getCompany().equals(insOrder.getCompany())) {
            Custom one = customMapper.selectOne(Wrappers.<Custom>lambdaQuery().eq(Custom::getCompany, insOrder.getCompany()));
            insOrder.setCompanyId(one.getId());
            customCode = one.getCode2();
        }
        //实验室编号
        String laboratoryCode = baseMapper.selLaboratoryCode(insOrder.getLaboratory());
        if (StringUtils.isEmpty(laboratoryCode)) {
            laboratoryCode = "";
        }
        //外部委托编号
        String outEntrustCodePrefix = getOutEntrustCodePrefix(customCode, laboratoryCode);
        String outEntrustCode = numberGenerator.generateNumberWithPrefix(5, outEntrustCodePrefix, InsOrder::getOutEntrustCode);
        insOrder.setOutEntrustCode(outEntrustCode);
//        String giveCode = this.giveCode.giveCode("JCZX-" + customCode + "-", "ins_sample", "", "yyMMdd");
        String giveCode = "";
//        insOrder.setOutEntrustCode(giveCode.giveCode3("ZT/" + code2 + "-" + code + "-", insOrder.getCompanyId(), insOrder.getLaboratory(), "ins_order", "", "yyMM"));
//        String giveCode = this.giveCode.giveCode("JCZX-" + code + "-", "ins_sample", "", "yyMMdd");
        insOrderMapper.insert(insOrder);
        AtomicInteger count = new AtomicInteger();
        List<FiberDto> fiberList = new ArrayList<>();
        list.forEach(a -> {
            count.getAndIncrement();
            a.setId(null);
            a.setInsOrderId(insOrder.getId());
            if (StrUtil.isEmpty(a.getSampleCode())) {
                a.setSampleCode(giveCode.split("-")[2] + "-" + count.get());
            } else {
                //去除手输的样品编号中首尾可能包含的空格
                a.setSampleCode(a.getSampleCode().trim());
            }
            insSampleMapper.insert(a);
            if (ObjectUtil.isNotEmpty(a.getInsProduct())) {
                addInsProductMethod(a.getId(), a.getInsProduct(), null, 0, false);
                if (ObjectUtil.isNotEmpty(a.getBushing())) {
                    for (BushingDto bushingDto : a.getBushing()) {
                        bushingDto.setInsSampleId(a.getId());
                        insBushingMapper.insert(bushingDto);
                        //光纤不为空
                        if (!bushingDto.getFiber().isEmpty()) {
                            fiberList.addAll(bushingDto.getFiber());
                            for (FiberDto fiberDto : bushingDto.getFiber()) {
                                fiberDto.setInsBushingId(bushingDto.getId());
                                insFiberMapper.insert(fiberDto);
                                addInsProductMethod(a.getId(), a.getInsProduct(), fiberDto.getId(), 2, true);
                                addInsProductMethod(a.getId(), fiberDto.getProductList(), fiberDto.getId(), 2, false);
                            }
                        }
                        //光纤带不为空
                        if (!bushingDto.getFibers().isEmpty()) {
                            for (FibersDto fibersDto : bushingDto.getFibers()) {
                                fibersDto.setInsBushingId(bushingDto.getId());
                                if (StringUtils.isBlank(fibersDto.getCode())) {
//                                    fibersDto.setCode(this.giveCode.giveCode("", "ins_fibers", "", "yyMMdd"));
                                    fibersDto.setCode("");
                                }
                                insFibersMapper.insert(fibersDto);
                                for (FiberDto fiberDto : fibersDto.getFiber()) {
                                    fiberDto.setInsFibersId(fibersDto.getId());
                                    insFiberMapper.insert(fiberDto);
                                    addInsProductMethod(a.getId(), a.getInsProduct(), fiberDto.getId(), 2, true);
                                    addInsProductMethod(a.getId(), fiberDto.getProductList(), fiberDto.getId(), 2, false);
                                }
                                //addInsProductMethod(a.getId(), a.getInsProduct(), fibersDto.getId(), 1);
                                addInsProductMethod(a.getId(), fibersDto.getProductList(), fibersDto.getId(), 1, false);
                            }
                        }
                        //都为空 只配置了套管 这种情况只限于项目或子项是含有松套管的
                        if (StringUtils.isNotBlank(bushingDto.getColor())) {
                            //检验项拼接字符
                            String insItem = a.getInsProduct().stream().map(InsProduct::getInspectionItem).distinct().collect(Collectors.joining(","));
                            //检验子项拼接字符
                            String insItemSubclass = a.getInsProduct().stream().map(InsProduct::getInspectionItemSubclass).distinct().collect(Collectors.joining(","));
                            if (insItem.contains("松套管") || insItemSubclass.contains("松套管")) {
                                //获取检验项目合或子项中包含松套管的检验项目
                                List<InsProduct> products = a.getInsProduct().stream()
                                        .filter(insProduct -> insProduct.getInspectionItem().contains("松套管") ||
                                                insProduct.getInspectionItemSubclass().contains("松套管"))
                                        .collect(Collectors.toList());
                                for (InsProduct product : products) {
                                    product.setInsBushId(bushingDto.getId());
                                    product.setId(null);
                                    product.setCreateTime(null);
                                    product.setCreateUser(null);
                                    product.setUpdateTime(null);
                                    product.setUpdateUser(null);
                                    product.setInsSampleId(a.getId());
                                    if (product.getInspectionItemSubclass() == null) {
                                        product.setInspectionItemSubclass("");
                                    }
                                    insProductMapper.insert(product);
                                }
                            }
//                            else {
//                                throw new ErrorException("样品的光纤配置信息里面没有配置光纤带信息也没有光纤信息,请重新配置保存再提交下单!!!");
//                            }
                        }
                    }
                }
            }
            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, null, 0, false);
            }
            if (ObjectUtil.isNotEmpty(a.getSheath())) {
                for (InsProduct product : a.getSheath().getInsProduct()) {
                    product.setStandardMethodListId(a.getSheath().getStandardMethodListId());
                }
                addInsProductMethod(a.getId(), a.getSheath().getInsProduct(), null, 0, false);
            }
            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"));
                            b.setSampleCode("");
                        }
                        insSampleMapper.insert(b);
                        if (ObjectUtil.isNotEmpty(b.getInsProduct())) {
                            addInsProductMethod(b.getId(), b.getInsProduct(), null, 0, false);
                        }
                    }
                }
            }
            if (ObjectUtil.isEmpty(a.getInsProduct()) && ObjectUtil.isNotEmpty(a.getBushing())) {
                for (BushingDto bushingDto : a.getBushing()) {
                    bushingDto.setInsSampleId(a.getId());
                    insBushingMapper.insert(bushingDto);
                    if (!bushingDto.getFiber().isEmpty()) {
                        fiberList.addAll(bushingDto.getFiber());
                        for (FiberDto fiberDto : bushingDto.getFiber()) {
                            fiberDto.setInsBushingId(bushingDto.getId());
                            insFiberMapper.insert(fiberDto);
                            addInsProductMethod(a.getId(), fiberDto.getProductList(), fiberDto.getId(), 2, false);
                        }
                    } else {
                        for (FibersDto fibersDto : bushingDto.getFibers()) {
                            fibersDto.setInsBushingId(bushingDto.getId());
                            fibersDto.setCode("");
                            insFibersMapper.insert(fibersDto);
                            for (FiberDto fiberDto : fibersDto.getFiber()) {
                                fiberDto.setInsFibersId(fibersDto.getId());
                                insFiberMapper.insert(fiberDto);
                                addInsProductMethod(a.getId(), fiberDto.getProductList(), fiberDto.getId(), 2, false);
                            }
                            addInsProductMethod(a.getId(), fibersDto.getProductList(), fibersDto.getId(), 1, false);
                        }
                    }
                }
            }
        });
        //有光纤接头损耗特殊项的样品才添加两两组合
        for (List<Integer> i : pairing) {
            SampleProductDto sample = JSON.parseObject(JSON.toJSONString(list.get(i.get(0) - 1)), SampleProductDto.class);
            List<InsProduct> insProducts = sample.getInsProduct().stream().filter(a -> Objects.equals(a.getInspectionItem(), "光纤接头损耗")).collect(Collectors.toList());
            if (!insProducts.isEmpty()) {
                sample.setSampleCode(list.get(i.get(0) - 1).getSampleCode() + "/" + list.get(i.get(1) - 1).getSampleCode());
                sample.setId(null);
                sample.setIsPairing("1");
                insSampleMapper.insert(sample);
                try {
                    for (InsProduct insProduct : insProducts) {
                        insProduct.setId(null);
                        insProduct.setInsSampleId(sample.getId());
                        insProductMapper.insert(insProduct);
                    }
                } catch (Exception e) {
                }
            }
        }
        //光纤配置的熔接配对
        if (!fiberPairing.isEmpty()) {
            for (List<Integer> integers : fiberPairing) {
                StringBuilder code1 = new StringBuilder(list.get(0).getSampleCode() + "-");
                StringBuilder code2 = new StringBuilder(list.get(1).getSampleCode() + "-");
                //配对的两个光纤色标
                FiberDto fiberDto1 = fiberList.get(integers.get(0) - 1);
                code1.append(fiberDto1.getBushColor()).append("-").append(fiberDto1.getColor());
                FiberDto fiberDto2 = fiberList.get(integers.get(1) - 1);
                code2.append(fiberDto2.getBushColor()).append("-").append(fiberDto2.getColor());
                //勾选的光纤接头损耗检验项
                //List<InsProduct> insProducts = fiberDto1.getProductList().stream().filter(a -> Objects.equals(a.getInspectionItem(), "光纤接头损耗")).collect(Collectors.toList());
 
                //配对后的样品
                InsSample insSample = new InsSample();
                BeanUtil.copyProperties(list.get(0), insSample);
                insSample.setSampleCode(code1 + "/" + code2);
                insSample.setId(null);
                insSample.setIsPairing("1");
                insSampleMapper.insert(insSample);
 
 
                // 如果是光纤配置的熔接配对,只需要获取list的bushing就行,生成的样品个数与下单界面样品个数无关
                // 一个样品下面只需要添加一次product 只添加光纤接头损耗的检验项
                // 添加套管
                List<BushingDto> bushing = list.get(0).getBushing();
                if (CollectionUtils.isNotEmpty(bushing)) {
                    for (int j = 0; j < bushing.size(); j++) {
                        bushing.get(j).setId(null);
                        bushing.get(j).setInsSampleId(insSample.getId());
                        insBushingMapper.insert(bushing.get(j));
                        Integer bushingId = bushing.get(j).getId();
                        // 添加光纤带
                        List<FibersDto> fibers = bushing.get(j).getFibers();
                        if (CollectionUtils.isNotEmpty(fibers)) {
                            fibers.forEach(item -> {
                                item.setId(null);
                                item.setInsBushingId(bushingId); // 套管id
                                insFibersMapper.insert(item);
                                // 将检验项的光纤带id赋值
                                if (CollectionUtils.isNotEmpty(item.getProductList())) {
                                    item.getProductList().forEach(insProduct -> {
                                        if (insProduct.getInspectionItem().equals("光纤接头损耗")) {
                                            insProduct.setInsFibersId(item.getId()); // 光纤带id
                                            insProduct.setInsSampleId(insSample.getId()); // 样品id
                                            insProduct.setId(null);
                                            insProductMapper.insert(insProduct);
                                        }
                                    });
                                }
                                // 是否含有光纤
                                if (CollectionUtils.isNotEmpty(item.getFiber())) {
                                    List<FiberDto> fiber = item.getFiber();
                                    fiber.forEach(f -> {
                                        f.setId(null);
                                        f.setInsBushingId(bushingId); // 套管id
                                        insFiberMapper.insert(f);
                                        f.getProductList().forEach(insProduct -> {
                                            if (insProduct.getInspectionItem().equals("光纤接头损耗")) {
                                                insProduct.setInsFiberId(f.getId()); // 光纤id
                                                insProduct.setInsSampleId(insSample.getId()); // 样品id
                                                insProduct.setId(null);
                                                insProductMapper.insert(insProduct);
                                            }
                                        });
                                    });
                                }
 
                            });
                        }
                        // 只有光纤的情况下
                        else {
                            bushing.get(j).getFiber().forEach(f -> {
                                f.setInsBushingId(bushingId); // 套管id
                                f.setId(null);
                                insFiberMapper.insert(f);
                                f.getProductList().forEach(insProduct -> {
                                    if (insProduct.getInspectionItem().equals("光纤接头损耗")) {
                                        insProduct.setInsFiberId(f.getId()); // 光纤id
                                        insProduct.setInsSampleId(insSample.getId()); // 样品id
                                        insProduct.setId(null);
                                        insProductMapper.insert(insProduct);
                                    }
                                });
                            });
                        }
                    }
                }
 
                // 没有进行光纤配置的熔接配对,直接添加样品
//                try {
//                    for (InsProduct insProduct : insProducts) {
//                        insProduct.setId(null);
//                        insProduct.setInsSampleId(insSample.getId());
//                        insProductMapper.insert(insProduct);
//                    }
//                } catch (Exception e) {
//                }
            }
        }
        return insOrder.getId();
    }
 
    /**
     * 生成外部委托编号前缀:ZT/TX-01-2411XXXXX
     *
     * @param customCode 客户代号
     * @param labCode    试验室代号
     * @return
     */
    private static String getOutEntrustCodePrefix(String customCode, String labCode) {
        String currentMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyMM"));
        return "ZT/" + labCode + "-" + customCode + "-" + currentMonth;
    }
 
    /**
     * 生成检测中心委托编号前缀:JCZX/TX-01-2411XXXXX
     *
     * @param customCode 客户代号
     * @param labCode    试验室代号
     * @return
     */
    private static String getEntrustCodePrefix(String customCode, String labCode) {
        String currentMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyMM"));
        return "JCZX/" + labCode + "-" + customCode + "-" + currentMonth;
    }
 
    private void addInsProductMethod(Integer sampleId, List<InsProduct> productList, Integer id, Integer type, Boolean is) {
        InsOrder insOrder = insOrderMapper.selectById(insSampleMapper.selectById(sampleId).getInsOrderId());
        String name = insSampleMapper.selMethodById(sampleId);
        for (InsProduct product : productList) {
            if (product.getInspectionItem().contains("松套管") || (!Objects.isNull(product.getInspectionItemSubclass()) && product.getInspectionItemSubclass().contains("松套管"))) {
                continue;
            }
            if (product.getState() == 1 && !product.getInspectionItem().equals("光纤接头损耗")) {
                //判断光缆的温度循环项目添加
                if (insOrder.getSampleType().equals("光缆") && product.getInspectionItem().equals("温度循环") && type != 0) {
                    //判断选择的标准方法是委托要求还是其他标准方法
                    if (!name.equals("委托要求")) {
                        //判断标准方法的温度循环的要求描述是否有填写
                        if (ObjectUtils.isEmpty(product.getTell()) || product.getTell().isEmpty()) {
                            throw new ErrorException("光缆的温度循环的要求描述为空,需要在标准库配置要求描述!!!");
                        } else {
                            //解析(温度范围:20℃,-40℃,65℃;保温时间:12h; 循环次数:2次; 光纤(1310nm,1550nm)附加衰减不大于0.03dB/km)
                            String tell = product.getTell().replace(")", ")")
                                    .replace("(", "(")
                                    .replace(")", ")")
                                    .replace(",", ",")
                                    .replace(":", ":")
                                    .replace(";", ";")
                                    .replace("不大于", "≤")
                                    .replace("不小于", "≥")
                                    .replace("大于", ">")
                                    .replace("小于", "<")
                                    .replace("等于", "=");
                            String[] message = null;
                            String[] nm = null;
                            String ask = null;
                            String count = null;
                            try {
                                String[] strings = tell.split(";");
                                //温度
                                String temperature = strings[0];
                                String[] split = temperature.split(":");
                                message = split[1].split(",");
                                //循环次数
                                count = strings[2].split(":")[1].split("次")[0];
                                //光纤项目和要求值
                                String string = strings[3];
                                nm = string.split("(")[1].split(")")[0].split(",");
                                ask = string.split("衰减")[1].split("dB")[0];
                            } catch (Exception e) {
                                throw new ErrorException("温度循环的要求描述格式异常,请参照温度范围:20℃,-40℃,65℃;保温时间:12h; 循环次数:2次; 光纤(1310nm,1550nm)附加衰减不大于0.03dB/km");
                            }
                            //拼接
                            String s = "";
                            for (int i = 0; i < nm.length; i++) {
                                s += "20℃(常温)," + nm[i] + ",null;";
                                for (int j = 0; j < message.length; j++) {
                                    s += message[j] + "," + nm[i] + "," + ask + ";";
                                }
                            }
                            s += count;
                            product.setAsk(s);
                            insProductMapper.updateById(product);
                            dealWithTemperatureLoop(type, id, sampleId, product);
                        }
                    } else {
                        //20℃(常温),1310nm,null;-40℃,1310nm,≤0.2;75℃,1310nm,<0.3;20℃,1310nm,≤0.1;20℃(常温),1550nm,null;-40℃,1550nm,≤0.2;75℃,1550nm,<0.3;20℃,1550nm,≤0.1;3
                        dealWithTemperatureLoop(type, id, sampleId, product);
                    }
                }
                //判断热循环项目的添加和温升试验项目的添加
                else if (product.getInspectionItem().equals("热循环") || product.getInspectionItem().equals("温升试验")) {
                    List<InsProduct> insProductess = new ArrayList<>();
                    product.setId(null);
                    product.setInsSampleId(sampleId);
                    insProductMapper.insert(product);
//                    insProductess.add(product);
                    List<InsProduct> insProductes = new ArrayList<>();
                    List<InsProduct> insProducts = new ArrayList<>();
                    String[] strings = product.getAsk().split(";");
                    //循环次数
                    int count = Integer.parseInt(strings[strings.length - 1]);
                    for (int i = 0; i < strings.length - 1; i++) {
                        String[] split = strings[i].split(",");
                        InsProduct insProduct = new InsProduct();
                        insProduct.setInspectionItem("1");//检验父项--循环次数
                        insProduct.setInspectionItemSubclass(split[0]);//检验子项--环境温度/导线温度/耐张温度/接续温度
                        insProduct.setInspectionItemSubclassEn(split[1]);//检验子项英文--环境温度/导线温度/耐张温度/接续温度
                        insProduct.setAsk(null);//检验要求
                        insProduct.setTell(null);//检验描述
                        insProduct.setInsSampleId(sampleId);
                        insProduct.setState(1);
                        insProduct.setFactory(product.getFactory());
                        insProduct.setLaboratory(product.getLaboratory());
                        insProduct.setSampleType(product.getSampleType());
                        insProduct.setSample(product.getSample());
                        insProduct.setModel(product.getModel());
                        insProduct.setSonLaboratory(product.getSonLaboratory());
                        insProduct.setUnit("℃");//单位
                        insProduct.setManHour(product.getManHour());//工时
                        insProduct.setManHourGroup(product.getManHourGroup());
                        insProduct.setInspectionItemType("0");
                        insProduct.setInspectionValueType("1");
                        insProduct.setTemplateId(product.getTemplateId());//添加模板id
                        insProduct.setSpecialItemParentId(product.getId());//特殊项父id
                        if (product.getInspectionItem().equals("热循环")) {
                            insProduct.setInspectionItemClass("直流电阻");//检验子子项--直流电阻
                            insProduct.setInspectionItemClassEn("DC resistance");//检验子子项英文--直流电阻
                            insProduct.setUnit("Ω/km");//单位
                        }
                        insProducts.add(insProduct);
                        insProductes.add(insProduct);
                        insProductess.add(insProduct);
                    }
                    //热循环才有多次循环次数
                    if (count > 1) {
                        //循环超过1次
                        for (int j = 2; j <= count; j++) {
                            for (InsProduct insProduct : insProductes) {
                                InsProduct insProduct1 = new InsProduct();
                                BeanUtils.copyProperties(insProduct, insProduct1);
                                insProduct1.setInspectionItem(j + "");//循环次数
                                insProductess.add(insProduct1);
                            }
                        }
                    }
                    insProductService.saveBatch(insProductess);
                }
                //弧垂特殊项
                else if (product.getInspectionItem().contains("弧垂")) {
                    product.setId(null);
                    product.setInsSampleId(sampleId);
                    insProductMapper.insert(product);
                    //需要添加的子项
                    List<Map<String, Object>> childrenMapList = initChildrenList();
                    //子项
                    List<InsProduct> childrenProducts = new ArrayList<>();
                    for (Map<String, Object> map : childrenMapList) {
                        InsProduct insProduct = new InsProduct();
                        insProduct.setInspectionItem(product.getInspectionItem());
                        insProduct.setInspectionItemSubclass(map.get("inspectionItem").toString());
                        insProduct.setUnit(map.get("unit").toString());
                        insProduct.setAsk(null);//检验要求
                        insProduct.setTell(null);//检验描述
                        insProduct.setInsSampleId(sampleId);
                        insProduct.setState(1);
                        insProduct.setFactory(product.getFactory());
                        insProduct.setLaboratory(product.getLaboratory());
                        insProduct.setSampleType(product.getSampleType());
                        insProduct.setSample(product.getSample());
                        insProduct.setModel(product.getModel());
                        insProduct.setSonLaboratory(product.getSonLaboratory());
                        insProduct.setManHour(product.getManHour());//工时
                        insProduct.setManHourGroup(product.getManHourGroup());
                        insProduct.setInspectionItemType("0");
                        insProduct.setInspectionValueType("1");
                        insProduct.setTemplateId(product.getTemplateId());//添加模板id
                        insProduct.setSpecialItemParentId(product.getId());//特殊项父id
                        childrenProducts.add(insProduct);
                    }
                    insProductService.saveBatch(childrenProducts);
                } else {
                    if (!is) {
                        switch (type) {
                            case 1:
                                product.setInsFibersId(id);
                                break;
                            case 2:
                                product.setInsFiberId(id);
                                break;
                        }
                        product.setId(null);
                        product.setCreateTime(null);
                        product.setCreateUser(null);
                        product.setUpdateTime(null);
                        product.setUpdateUser(null);
                        product.setInsSampleId(sampleId);
                        if (product.getInspectionItemSubclass() == null) {
                            product.setInspectionItemSubclass("");
                        }
                        // 普通项目 如果ask包含了 % 就去除
                        if(product.getAsk().contains("%")) {
                            String ask = product.getAsk().replace("%", "").trim();
                            product.setAsk(ask);
                        }
                        insProductMapper.insert(product);
                    }
                }
            }
 
 
        }
    }
 
    /**
     * 初始化弧垂特殊项目子项
     * 固定子项:额定拉断力,跨距长度,载荷,高度,弧垂,导线温度,室温,张力
     *
     * @return
     */
    private List<Map<String, Object>> initChildrenList() {
        List<Map<String, Object>> maps = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("inspectionItem", "额定拉断力");
        map1.put("unit", "kN");
        Map<String, Object> map2 = new HashMap<>();
        map2.put("inspectionItem", "跨距长度");
        map2.put("unit", "m");
        Map<String, Object> map3 = new HashMap<>();
        map3.put("inspectionItem", "载荷");
        map3.put("unit", "kN");
        Map<String, Object> map5 = new HashMap<>();
        map5.put("inspectionItem", "弧垂");
        map5.put("unit", "mm");
        Map<String, Object> map6 = new HashMap<>();
        map6.put("inspectionItem", "导线温度");
        map6.put("unit", "℃");
        Map<String, Object> map7 = new HashMap<>();
        map7.put("inspectionItem", "室温");
        map7.put("unit", "℃");
        Map<String, Object> map8 = new HashMap<>();
        map8.put("inspectionItem", "张力");
        map8.put("unit", "kN");
 
        maps.add(map1);
        maps.add(map2);
        maps.add(map3);
        maps.add(map5);
        maps.add(map6);
        maps.add(map7);
        maps.add(map8);
 
        return maps;
    }
 
    //温度循环的处理
    private void dealWithTemperatureLoop(Integer type, Integer id, Integer sampleId, InsProduct product) {
        List<InsProduct> insProductes = new ArrayList<>();
        List<InsProduct> insProducts = new ArrayList<>();
        String[] strings = product.getAsk().split(";");
        for (int i = 0; i < strings.length; i++) {
            int count = Integer.parseInt(strings[strings.length - 1]);
            if (i != strings.length - 1) {
                InsProduct insProduct = new InsProduct();
                switch (type) {
                    case 1:
                        insProduct.setInsFibersId(id);
                        break;
                    case 2:
                        insProduct.setInsFiberId(id);
                        break;
                }
                String[] split = strings[i].split(",");
                if (split[0].equals("20℃")) {
                    insProduct.setInspectionItem(count + "");//检验项--循环次数
                } else {
                    insProduct.setInspectionItem("1");//检验项--循环次数
                }
                insProduct.setInspectionItemSubclass(split[0]);//检验项--温度
                insProduct.setInspectionItemClass(split[1]);//检验项--光纤项目
                insProduct.setAsk(split[2]);//检验要求
                insProduct.setTell(strings[i]);//检验描述
                insProduct.setInsSampleId(sampleId);
                insProduct.setState(1);
                insProduct.setFactory(product.getFactory());
                insProduct.setLaboratory(product.getLaboratory());
                insProduct.setSampleType(product.getSampleType());
                insProduct.setSample(product.getSample());
                insProduct.setModel(product.getModel());
                insProduct.setSonLaboratory(product.getSonLaboratory());
                insProduct.setUnit(product.getUnit());
                insProduct.setManHourGroup(product.getManHourGroup());
                insProduct.setManHour(product.getManHour());
                insProduct.setInspectionItemType("0");
                insProduct.setInspectionValueType("1");
                insProduct.setTemplateId(product.getTemplateId());//添加模板id
                insProduct.setSpecialItemParentId(product.getId());//特殊项父id
                insProducts.add(insProduct);
                insProductes.add(insProduct);
            } else {
                //最后一个数据是说明会循环多少次
                if (count > 1) {
                    //循环超过1次
                    for (int j = 2; j <= count; j++) {
                        for (InsProduct insProduct : insProducts) {
                            if (!insProduct.getInspectionItemSubclass().equals("20℃") && !insProduct.getInspectionItemSubclass().equals("20℃(常温)")) {
                                InsProduct insProduct1 = new InsProduct();
                                BeanUtils.copyProperties(insProduct, insProduct1);
                                insProduct1.setInspectionItem(j + "");
                                insProductes.add(insProduct1);
                            }
                        }
                    }
                }
            }
        }
        insProductService.saveBatch(insProductes);
    }
 
    @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);
        // 如果是光纤配置接头损耗只需展示A端、B端、平均值
        if (CollectionUtils.isNotEmpty(list)) {
            for (SampleProductDto dto : list) {
                // 获取检验项目
                List<InsProduct> insProducts = dto.getInsProduct();
                if (CollectionUtils.isNotEmpty(insProducts)) {
                    // 过滤出光纤配置的光纤接头损耗检验项目
                    List<InsProduct> productList = insProducts.stream().filter(item -> item.getInspectionItem().equals("光纤接头损耗")
                            && (!Objects.isNull(item.getInsFiberId()) || !Objects.isNull(item.getInsFibersId()))).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(productList)) {
                        // 只返回光纤街头损耗检验项目 且 只展示一次
                        // 根据检验项进行分组
                        Map<String, List<InsProduct>> collect = productList.stream().collect(Collectors.groupingBy(InsProduct::getInspectionItemSubclass));
                        List<InsProduct> productList2 = new ArrayList<>();
                        Iterator<Map.Entry<String, List<InsProduct>>> iterator = collect.entrySet().iterator();
                        while (iterator.hasNext()) {
                            Map.Entry<String, List<InsProduct>> entry = iterator.next();
                            productList2.add(entry.getValue().get(0));
                        }
                        dto.setInsProduct(productList2);
                    }
 
                }
            }
        }
        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) {
            //审核通过才会生成委托编号
            String laboratoryCode = baseMapper.selLaboratoryCode(insOrder.getLaboratory());
            if (StringUtils.isEmpty(laboratoryCode)) {
                laboratoryCode = "";
            }
            Custom custom = customMapper.selectById(order.getCompanyId());
//            System.out.println("============="+custom.getCompany());
//            System.out.println("-------------"+order.getCompany());
            String customCode = custom.getCode2();
            if (!custom.getCompany().equals(order.getCompany())) {
                Custom one = customMapper.selectOne(Wrappers.<Custom>lambdaQuery().eq(Custom::getCompany, order.getCompany()));
                insOrder.setCompanyId(one.getId());
                customCode = one.getCode2();
            }
            String entrustCodePrefix = getEntrustCodePrefix(customCode, laboratoryCode);
            String entrustCode = numberGenerator.generateNumberWithPrefix(4, entrustCodePrefix, InsOrder::getEntrustCode);
            insOrder.setEntrustCode(entrustCode);
//            insOrder.setEntrustCode(giveCode.giveCode2("JCZX/" + code + "-" + code2 + "-", insOrder.getCompanyId(), insOrder.getLaboratory(), "ins_order", "", "yyMM"));
            /*审核通过还需要新增一条cnas要求、标书和合同评审*/
            ProcessOrder processOrder = new ProcessOrder();
            processOrder.setInsOrderId(insOrder.getId());
            processOrderMapper.insert(processOrder);
        }
        return insOrderMapper.updateById(insOrder);
    }
 
    @Override
    public Map<String, Object> getInsOrderAndSample(Integer id, String laboratory) {
        Map<String, Object> map = new HashMap<>();
        InsOrder insOrder = insOrderMapper.selectById(id);
        Integer insState = insOrderStateMapper.selectOne(new LambdaQueryWrapper<InsOrderState>().eq(InsOrderState::getLaboratory, laboratory).eq(InsOrderState::getInsOrderId, id)).getInsState();
        List<SampleProductDto> list = insSampleMapper.getInsOrderAndSample(id, laboratory);
        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);
        map.put("insState", insState);
        //查询所有记录模版去重
        List<Map<Integer, Object>> list2 = insOrderMapper.selectReportModelByOrderId(id, laboratory);
        map.put("reportModel", list2);
        return map;
    }
 
    @Override
    public Map<String, Object> selectSampleAndProductByOrderId(SampleProductDto2 sampleProductDto) {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> headList = new ArrayList<>();
        List<SampleProductDto2> SampleProductDto2S = null;
        if (!Objects.isNull(sampleProductDto.getId())) {
            String laboratory = insOrderMapper.selectById(sampleProductDto.getId()).getLaboratory();
            if (laboratory.equals("电力产品实验室")) {
                //电力试验室的数据查看,删除光纤配置相关字段
//                headList = PrintChina.printChina(SampleProductDTODL.class);
                SampleProductDto2S = insOrderMapper.selectSampleAndProductByOrderId(
                        QueryWrappers.queryWrappers(sampleProductDto).orderByAsc("ins_product_id"),
                        sampleProductDto.getId());
            } else {
//                headList = PrintChina.printChina(SampleProductDto2.class);
                SampleProductDto2S = insOrderMapper.selectSampleAndProductByOrderId(
                        QueryWrappers.queryWrappers(sampleProductDto)
                                .orderByAsc("son_laboratory"),
//                                .orderByAsc("inspection_item")
//                                .orderByAsc("inspection_item_subclass"),
                        sampleProductDto.getId());
                List<SampleProductDto2> collect = SampleProductDto2S
                        .stream()
                        .filter(item -> item.getInspectionItem().contains("松套管") || item.getInspectionItemSubclass()
                                .contains("松套管")).collect(Collectors.toList());
                // 样品下的松套管
                Map<String, List<SampleProductDto2>> collect1 = collect
                        .stream()
                        .collect(Collectors.groupingBy(item -> item.getSampleCode() + '@' + item.getInspectionItemSubclass() + '@' + item.getInspectionItem()));
                Iterator<Map.Entry<String, List<SampleProductDto2>>> iterator = collect1.entrySet().iterator();
                ArrayList<SampleProductDto2> list = new ArrayList<>();
                while (iterator.hasNext()) {
                    SampleProductDto2 sampleProductDto2 = new SampleProductDto2();
                    double avg = 0.0;
                    double count = 0.0;
                    boolean flag = true;
                    Map.Entry<String, List<SampleProductDto2>> next = iterator.next();
                    for (SampleProductDto2 s : next.getValue()) {
                        if (StringUtils.isNotEmpty(s.getLastValue()) && (NumberUtil.isNumber(s.getLastValue()))) {
                            count += Double.parseDouble(s.getLastValue());
                        } else if (!NumberUtil.isNumber(s.getLastValue()) && StringUtils.isNotEmpty(s.getLastValue())) {
                            flag = false;
                        }
                    }
                    BeanUtil.copyProperties(next.getValue().get(0), sampleProductDto2);
                    sampleProductDto2.setBushColor("");
                    List<SampleProductDto2> collect2 = next.getValue().stream().filter(item -> Objects.nonNull(item.getInsResult()) && item.getInsResult().equals(0)).collect(Collectors.toList()); // 不合格
                    List<SampleProductDto2> collect3 = next.getValue().stream().filter(item -> Objects.nonNull(item.getInsResult()) && item.getInsResult().equals(3)).collect(Collectors.toList()); // 不判定
                    List<SampleProductDto2> collect4 = next.getValue().stream().filter(item -> StringUtils.isNotEmpty(item.getLastValue())).collect(Collectors.toList()); // 不判定
                    if (CollectionUtils.isNotEmpty(collect2)) {
                        sampleProductDto2.setInsResult(0);
                        sampleProductDto2.setLastValue(collect2.get(0).getLastValue());
                    } else if (CollectionUtils.isNotEmpty(collect3)) {
                        sampleProductDto2.setInsResult(3);
                    } else if (CollectionUtils.isNotEmpty(collect4)) {
                        sampleProductDto2.setInsResult(1);
                    } else {
                        sampleProductDto2.setInsResult(null);
                    }
                    if (flag) {
                        avg = BigDecimal.valueOf(count).divide(BigDecimal.valueOf(next.getValue().size()), 4, RoundingMode.HALF_UP).doubleValue();
                        if (avg == 0.0) {
                            sampleProductDto2.setLastValue("");
                        } else {
                            sampleProductDto2.setLastValue(String.valueOf(avg));
                        }
                    }
                    sampleProductDto2.setInspectionItem(next.getKey().split("@")[2]);
                    sampleProductDto2.setInspectionItemSubclass(next.getKey().split("@")[1]);
                    list.add(sampleProductDto2);
                }
                // 过滤出不包含为松套管且不为光纤接头损耗的数据
                List<SampleProductDto2> collect2 = SampleProductDto2S
                        .stream()
                        .filter(item -> !item.getInspectionItem().contains("松套管") && !item.getInspectionItemSubclass()
                                .contains("松套管") && !item.getInspectionItem().equals("光纤接头损耗")).collect(Collectors.toList());
                // 如果是光纤接头损耗 一个样品只取其中一个的A端、B端、平均值
                Map<String, List<SampleProductDto2>> fiberMap = SampleProductDto2S
                        .stream()
                        .filter(item -> item.getInspectionItem().equals("光纤接头损耗"))
                        .collect(Collectors.groupingBy(e -> e.getSampleCode() + e.getInspectionItem() + e.getInspectionItemSubclass()));
                Iterator<Map.Entry<String, List<SampleProductDto2>>> iterator1 = fiberMap.entrySet().iterator();
                while (iterator1.hasNext()) {
                    Map.Entry<String, List<SampleProductDto2>> entry = iterator1.next();
                    list.add(entry.getValue().get(0));
                }
                collect2.addAll(list);
                SampleProductDto2S = collect2;
//                SampleProductDto2S.sort(new CustomComparator(enumService));
            }
        }
        for (SampleProductDto2 record : SampleProductDto2S) {
            List<String> values = new ArrayList<>();
            //光纤带编号不为空&&检验过程值不为空
            if (StringUtils.isNotBlank(record.getCode()) && (StringUtils.isNotBlank(record.getInsValue()) || Objects.equals(record.getInsValue(), "[]"))) {
                JSONArray insValueJsonArray = JSON.parseArray(record.getInsValue());
                for (Object o : insValueJsonArray) {
                    JSONObject insValue = JSON.parseObject(JSON.toJSONString(o));
                    if (StringUtils.isNotBlank(insValue.get("v").toString())) {
                        values.add(insValue.get("v").toString());
                    }
                }
                record.setLastValue(String.join(",", values));
            }
        }
        map.put("head", headList);
        map.put("body", SampleProductDto2S);
        return map;
    }
 
    @Override
    public List<Map<String, Object>> viewDetails(Map<String, Object> map) {
        List<Map<String, Object>> list = new ArrayList<>();
        String inspectionItem = map.get("inspectionItem").toString(); // 检验项
        if (inspectionItem.equals("单根垂直燃烧")) {
            ArrayList<Integer> numbers = new ArrayList<>();
            InsProduct insProduct = insProductMapper.selectById(Integer.parseInt(map.get("insProductId").toString()));
            String[] split = insProduct.getTell().split(",");
            Pattern pattern = Pattern.compile("-?\\d+");
            Matcher matcher = pattern.matcher(split[1]);
            while (matcher.find()) {
                String numberStr = matcher.group();
                numbers.add(Integer.parseInt(numberStr));
            }
            InsProductResult result = insProductResultMapper.selectOne(new LambdaQueryWrapper<InsProductResult>()
                    .eq(InsProductResult::getInsProductId, Integer.parseInt(map.get("insProductId").toString())));
 
 
            for (int i = 0; i < numbers.get(0); i++) {
                HashMap<String, Object> map1 = new HashMap<>();
                map1.put("entrustCode", map.get("entrustCode")); // 委托编号
                map1.put("sampleCode", map.get("sampleCode")); // 样品编号
                map1.put("color", ""); // 套管
                map1.put("inspectionItem", inspectionItem); // 检验项
                if (!Objects.isNull(result)) {
                    List<Map> maps = JSONArray.parseArray(result.getInsValue(), Map.class);
                    if (maps.size() - 1 < i) {
                        map1.put("insValue", ""); // 检验结果
                    } else {
                        map1.put("insValue", maps.get(i).get("v")); // 检验结果
                    }
                }
                list.add(map1);
            }
        } else if (inspectionItem.equals("抗拉强度")) {
            InsProduct insProduct = insProductMapper.selectById(Integer.parseInt(map.get("insProductId").toString()));
            InsProductResult insProductResult = insProductResultMapper.selectOne(new LambdaQueryWrapper<InsProductResult>()
                    .eq(InsProductResult::getInsProductId, insProduct.getId()));
            if(Objects.isNull(insProductResult)) {
                return list;
            }
            List<Map<String, Object>> values = JSON.parseObject(insProductResult.getInsValue(), new TypeReference<List<Map<String, Object>>>() {
            });
            // 进行排序 根据坐标
            values.sort((o1, o2) -> {
                int i = Integer.parseInt(o1.get("r").toString());
                int i1 = Integer.parseInt(o2.get("r").toString());
                return Integer.compare(i,i1);
            });
            // 将得到的宽度、厚度、检验值分别进行存储
            Map<Object, List<Map<String, Object>>> group = values.stream().collect(Collectors.groupingBy(item -> item.get("r")));
            Iterator<Map.Entry<Object, List<Map<String, Object>>>> iterator = group.entrySet().iterator();
            List<String> widths = new ArrayList<>();
            List<String> thickness = new ArrayList<>();
            List<String> testValue = new ArrayList<>();
            Integer count = 0;
            while (iterator.hasNext()) {
                Map.Entry<Object, List<Map<String, Object>>> entry = iterator.next();
                List<Map<String, Object>> value = entry.getValue();
                for(Map<String,Object> m : value) {
                    if(count == 0) {
                        widths.add(m.get("v").toString());
                    }else if(count == 1) {
                        thickness.add(m.get("v").toString());
                    }else {
                        testValue.add(m.get("v").toString());
                    }
                }
                count++;
            }
            // 进行封装返回
            // 找到最长的那个集合
            List<Integer> list1 = Arrays.asList(widths.size(), thickness.size(), testValue.size());
            list1.sort((a1, a2) -> {
                return Integer.compare(a2,a1);
            });
            for (int i = 0; i < list1.get(0); i++) {
                HashMap<String, Object> map1 = new HashMap<>();
                map1.put("inspectionItem",insProduct.getInspectionItem()); // 检验项
                map1.put("inspectionItemSubclass",insProduct.getInspectionItemSubclass()); // 检验子项
                map1.put("width",""); // 宽度
                map1.put("thickness",""); // 厚度
                map1.put("testValue",""); // 检验值
                if(i < widths.size() ) {
                    map1.put("width",widths.get(i));
                }
                if(i < thickness.size()) {
                    map1.put("thickness",thickness.get(i));
                }
                if(i < testValue.size()) {
                    map1.put("testValue",testValue.get(i));
                }
                list.add(map1);
            }
 
        } else if(inspectionItem.equals("断裂伸长率")) {
            InsProduct insProduct = insProductMapper.selectById(Integer.parseInt(map.get("insProductId").toString()));
            InsProductResult insProductResult = insProductResultMapper.selectOne(new LambdaQueryWrapper<InsProductResult>()
                    .eq(InsProductResult::getInsProductId, insProduct.getId()));
            if(Objects.isNull(insProductResult)) {
                return list;
            }
            List<Map<String, Object>> values = JSON.parseObject(insProductResult.getInsValue(), new TypeReference<List<Map<String, Object>>>() {
            });
            HashMap<String, Object> map1 = new HashMap<>();
            map1.put("inspectionItem",insProduct.getInspectionItem()); // 检项项
            map1.put("inspectionItemSubclass",insProduct.getInspectionItemSubclass()); // 检项子项
            ArrayList<Map<String, Object>> tableHeader = new ArrayList<>();
            for (int i = 0; i < values.size(); i++) {
                HashMap<String, Object> map2 = new HashMap<>();
                map2.put("testValue" + i,values.get(i).get("v")); // 检项值  表头
                tableHeader.add(map2);
                map1.put("testValue" + i,values.get(i).get("v"));
            }
            map1.put("tableHeader",tableHeader);
            list.add(map1);
        } else {
            // 松套管 过滤出检验项名称一致的数据
            List<InsProduct> productList = insProductMapper.selectList(new LambdaQueryWrapper<InsProduct>()
                            .eq(InsProduct::getInsSampleId, Integer.parseInt(map.get("insSampleId").toString())))
                    .stream()
                    .filter(item -> item.getInspectionItem().equals(inspectionItem))
                    .collect(Collectors.toList());
            for (InsProduct product : productList) {
                HashMap<String, Object> map2 = new HashMap<>();
                map2.put("entrustCode", map.get("entrustCode")); // 委托编号
                map2.put("sampleCode", map.get("sampleCode")); // 样品编号
                map2.put("inspectionItem", product.getInspectionItem()); // 检验项
                map2.put("insValue", product.getLastValue()); // 检验结果
                // 拿到相应的套管
                String color = "";
                if (!Objects.isNull(product.getInsBushId())) {
                    color = insBushingMapper.selectById(product.getInsBushId()).getColor(); // 套管
                }
                map2.put("color", color); // 套管颜色
//                InsProductResult result = insProductResultMapper.selectOne(new LambdaQueryWrapper<InsProductResult>()
//                        .eq(InsProductResult::getInsProductId, product.getId()));
//                if(!Objects.isNull(result)) {
//                    List<Map> maps = JSONArray.parseArray(result.getInsValue(), Map.class);
//                    map2.put("insValue",maps.get(0).get("v").toString()); // 检验结果
//                }
                list.add(map2);
            }
        }
        return list;
    }
 
    /**
     * 导出已检委托单
     *
     * @param data
     * @param response
     */
    @Override
    public void exportChecked(Map<String, Object> data, HttpServletResponse response) {
//        Integer userId = getLook.selectPowerByMethodAndUserId(null).get("userId");
        Integer userId = Integer.valueOf(String.valueOf(SecurityUtils.getLoginUser().getUserId()));
        User user = userMapper.selectById(userId);
        List<String> names = null;
        String startTime = "";
        String endTime = "";
        if (data.containsKey("startTime")) {
            startTime = data.get("startTime").toString() + " 00:00:00";
        }
        if (data.containsKey("endTime")) {
            endTime = data.get("endTime").toString() + " 23:59:59";
        }
        List<ExcelChecked> list = new ArrayList<>();
 
        // 如果是检测中心人员可以导入所有客户下的单 , 如果是客户,可以导出该单位所有的单
        if (user.getIsCustom().equals(0)) {
            names = new ArrayList<>();
        } else {
            String company = user.getCompany();
            List<User> users = userMapper.selectList(new LambdaQueryWrapper<User>()
                    .eq(User::getCompany, company)
                    .eq(User::getIsCustom, 1)
                    .eq(User::getStatus, 0));
            if (CollectionUtils.isNotEmpty(users)) {
                names = users.stream().map(item -> item.getName()).collect(Collectors.toList());
            }
        }
        //总的检验结果
        List<ExportInsProductVO> exportInsProductVOS = insOrderMapper.exportChecked(names, startTime, endTime);
        //排除光纤带几何参数(尺寸参数),温度循环的检验结果
//        List<ExcelChecked> excelCheckeds = exportInsProductVOS.stream().map(e -> {
//            ExcelChecked excelChecked = new ExcelChecked();
//            BeanUtil.copyProperties(e, excelChecked);
//            return excelChecked;
//        }).collect(Collectors.toList());
        // 排除光纤带几何参数(尺寸参数),温度循环的检验结果
        List<ExportInsProductVO> excelCheckeds = exportInsProductVOS.stream().filter(e -> !e.getInspectionItem().equals("温度循环")
                        && !(NumberUtil.isInteger(e.getInspectionItem()) && Objects.nonNull(e.getSpecialItemParentId()))
                        && !(e.getInspectionItem().equals("尺寸参数")
                        && e.getSampleType().equals("光纤带")))
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(excelCheckeds)) {
            for (ExportInsProductVO a : excelCheckeds) {
                ExcelChecked excelChecked = new ExcelChecked();
                BeanUtil.copyProperties(a, excelChecked);
                list.add(excelChecked);
            }
        }
        //过滤出光纤带几何参数的检验结果
        List<ExportInsProductVO> sizeParameter = exportInsProductVOS.stream().filter(e ->
                        e.getInspectionItem().equals("尺寸参数")
                                && e.getSampleType().equals("光纤带"))
                .collect(Collectors.toList());
        List<FiberRibboGeometricalParameterExcelData> fiberList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(sizeParameter)) {
            // 根据委托单号、样品编号、套管、光纤带编号进行分组
            Map<String, List<ExportInsProductVO>> groupData = sizeParameter.stream().sorted(Comparator.comparing(ExportInsProductVO::getSampleCode))
                    .collect(Collectors.toMap(e ->
                                    e.getEntrustCode() + '@' + e.getSampleCode() + '@' + e.getBushColor() + '@' + e.getCode(),
                            Collections::singletonList,
                            (left, right) -> {
                                ArrayList<ExportInsProductVO> list1 = new ArrayList<>(left);
                                list1.addAll(right);
                                return list1;
                            },
                            TreeMap::new));
            Iterator<Map.Entry<String, List<ExportInsProductVO>>> iterator = groupData.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, List<ExportInsProductVO>> entry = iterator.next();
                FiberRibboGeometricalParameterExcelData fiber = new FiberRibboGeometricalParameterExcelData();
                ExportInsProductVO exportInsProductVO = entry.getValue().get(0);
                fiber.setEntrustCode(exportInsProductVO.getEntrustCode()); // 委托单号
                fiber.setSampleCode(exportInsProductVO.getSampleCode()); // 样品编号
                fiber.setBushColor(exportInsProductVO.getBushColor()); // 套管色标
                fiber.setCode(exportInsProductVO.getCode()); // 光纤带编号
                fiber.setInspectionItemType("光纤几何参数"); // 检验项
                fiber.setInspector(exportInsProductVO.getCheckName()); // 检验人
 
                for (ExportInsProductVO a : entry.getValue()) {
                    if (Objects.isNull(fiber.getInsTime())) {
                        if (Objects.nonNull(a.getCheckTime())) {
                            String format = a.getCheckTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                            fiber.setInsTime(LocalDate.parse(format)); // 检验时间
                        }
                    }
                    switch (a.getInspectionItemSubclass()) {
                        case "宽度":
                            List<Map> maps1 = getInsValueList(a.getInsValue());
                            if (CollectionUtils.isNotEmpty(maps1)) {
                                if (maps1.size() >= 2) {
                                    fiber.setWidthA(maps1.get(0).get("v").toString());
                                    fiber.setWidthB(maps1.get(1).get("v").toString());
                                } else {
                                    fiber.setWidthA(maps1.get(0).get("v").toString());
                                }
                            }
                            break;
                        case "厚度":
                            List<Map> maps2 = getInsValueList(a.getInsValue());
                            if (CollectionUtils.isNotEmpty(maps2)) {
                                if (maps2.size() >= 2) {
                                    fiber.setThicknessA(maps2.get(0).get("v").toString());
                                    fiber.setThicknessB(maps2.get(1).get("v").toString());
                                } else {
                                    fiber.setThicknessA(maps2.get(0).get("v").toString());
                                }
                            }
                            break;
                        case "相邻光纤水平间距":
                            List<Map> maps3 = getInsValueList(a.getInsValue());
                            if (CollectionUtils.isNotEmpty(maps3)) {
                                if (maps3.size() >= 2) {
                                    fiber.setAdjacentSpacingA(maps3.get(0).get("v").toString());
                                    fiber.setAdjacentSpacingB(maps3.get(1).get("v").toString());
                                } else {
                                    fiber.setAdjacentSpacingA(maps3.get(0).get("v").toString());
                                }
                            }
                            break;
                        case "两侧光纤水平间距":
                            List<Map> maps4 = getInsValueList(a.getInsValue());
                            if (CollectionUtils.isNotEmpty(maps4)) {
                                if (maps4.size() >= 2) {
                                    fiber.setSideSpacingA(maps4.get(0).get("v").toString());
                                    fiber.setSideSpacingB(maps4.get(1).get("v").toString());
                                } else {
                                    fiber.setSideSpacingA(maps4.get(0).get("v").toString());
                                }
                            }
                            break;
                        case "平整度":
                            List<Map> maps5 = getInsValueList(a.getInsValue());
                            if (CollectionUtils.isNotEmpty(maps5)) {
                                if (maps5.size() >= 2) {
                                    fiber.setEvennessA(maps5.get(0).get("v").toString());
                                    fiber.setEvennessB(maps5.get(1).get("v").toString());
                                } else {
                                    fiber.setEvennessA(maps5.get(0).get("v").toString());
                                }
                            }
                            break;
                    }
                }
                fiberList.add(fiber);
            }
        }
 
        //过滤出温度循环
        List<ExportInsProductVO> temperatureCycling = exportInsProductVOS.stream().filter(e ->
                        NumberUtil.isInteger(e.getInspectionItem()) && Objects.nonNull(e.getSpecialItemParentId()) && e.getSonLaboratory().equals("光纤试验室"))
                .collect(Collectors.toList());
 
        List<TemperatureCycling> temperatureCyclingList = getTemList(temperatureCycling);
        try {
            String fileName = URLEncoder.encode("已检委托单", "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-disposition", "attachment;filename=" + fileName + ".xlsx");
            HorizontalCellStyleStrategy arveStyleStrategy = EasyExcelUtils.getStyleStrategy();
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerWriteHandler(arveStyleStrategy).build();
            WriteSheet build = EasyExcel.writerSheet().sheetName("Sheet1").head(ExcelChecked.class).build();
            excelWriter.write(list, build);
            if (CollectionUtils.isNotEmpty(fiberList)) {
                WriteSheet build1 = EasyExcel.writerSheet().sheetName("光纤几何参数").head(FiberRibboGeometricalParameterExcelData.class).build();
                excelWriter.write(fiberList, build1);
            }
            if (CollectionUtils.isNotEmpty(temperatureCycling)) {
                WriteSheet build2 = EasyExcel.writerSheet().sheetName("温度循环").head(TemperatureCycling.class).build();
                excelWriter.write(temperatureCyclingList, build2);
            }
            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("导出失败" + e.getMessage());
        }
    }
 
    @Override
    public List<Map<String, Object>> getInsOrderTemList(Map<String, Object> data) {
        String entrustCode = data.get("entrustCode").toString();
        Integer createUser = null;
        String name= "";
        if (StringUtils.isNotBlank(data.get("createUser").toString())) {
            createUser = Integer.parseInt(data.get("createUser").toString());
//            name = userMapper.selectByCreaterUser(createUser);
        }
        String sampleCode = data.get("sampleCode").toString();
        String startTime = "";
        String endTime = "";
        List<Map<String, Object>> maps = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (StringUtils.isNotBlank(data.get("insTime").toString()) && !Objects.isNull(data.get("insTime"))) {
                List insTime = objectMapper.readValue(JSONUtil.toJsonStr(data.get("insTime")), List.class);
                startTime = insTime.get(0).toString();
                endTime = insTime.get(1).toString();
            }
            List<ExportInsProductVO> insOrderTemList = insOrderMapper.getInsOrderTemList(entrustCode, sampleCode, startTime, endTime,name);
            List<TemperatureCycling> temList = getTemList(insOrderTemList);;
//            if (StringUtils.isEmpty(name)) {
//                temList = getTemList(insOrderTemList);
//            } else {
//                temList = getTemList(insOrderTemList).stream()
//                        .filter(tl -> name.equals(tl.getCheckName()))
//                        .collect(Collectors.toList());
//            }
            maps = new ArrayList<>(temList.size());
            for (TemperatureCycling map : temList) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("entrustCode", map.getEntrustCode()); //委托单号
                resultMap.put("sampleCode", map.getSampleCode()); //样品编号
                resultMap.put("bushing", map.getBushColor()); //套管
                resultMap.put("fiber", map.getColor()); //光纤
                resultMap.put("fibers", map.getCode()); //光纤带
                resultMap.put("userName", map.getCheckName()); //检验人
                resultMap.put("insTime", map.getInsTime()); //检测时间
                resultMap.put("sendTime", map.getSendTime()); //下发时间
//                resultMap.put("inspectionItem", map.getSample()); //检验项目
                //温度循环子项
                resultMap.put("inspectionItems", map.getInspectionItem());
                resultMap.put("inspectionItemSubclass", map.getInspectionItemSubclass());
                resultMap.put("attenuationCoefficient1310", map.getAttenuationCoefficient1310());
                resultMap.put("attenuationDifference1", map.getAttenuationDifference1());
                resultMap.put("attenuationCoefficient1550", map.getAttenuationCoefficient1550());
                resultMap.put("attenuationDifference2", map.getAttenuationDifference2());
                resultMap.put("attenuationCoefficient1625", map.getAttenuationCoefficient1625());
                resultMap.put("attenuationDifference3", map.getAttenuationDifference3());
                resultMap.put("attenuationCoefficient1383", map.getAttenuationCoefficient1383());
                resultMap.put("attenuationDifference4", map.getAttenuationDifference4());
                resultMap.put("attenuationCoefficient1490", map.getAttenuationCoefficient1490());
                resultMap.put("attenuationDifference5", map.getAttenuationDifference5());
                resultMap.put("attenuationDifferenceMax", map.getAttenuationDifferenceMax());
                resultMap.put("insResult", map.getInsResult());
                maps.add(resultMap);
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return maps;
    }
 
    @Override
    public Map<String,Object> permute(Integer num,Boolean isValue) {
        HashMap<String, Object> map = new HashMap<>();
        ArrayList<Integer> integers = new ArrayList<>();
        for (int i = 1; i <= num; i++) { // 使用较小的数字范围进行测试
            integers.add(i);
        }
        List<List<Integer>> result = permutes(integers);
        if(isValue) {
            map.put("resultData",result);
        }else {
            map.put("resultData",result.size());
        }
        return map;
    }
 
    private static List<List<Integer>> permutes(List<Integer> nums) {
        List<List<Integer>> result = new ArrayList<>();
        backtrack(new ArrayList<>(), nums, result);
        return result;
    }
 
    private static void backtrack(List<Integer> temp, List<Integer> nums, List<List<Integer>> result) {
        if (temp.size() == 2) {
            result.add(new ArrayList<>(temp)); // 添加当前组合到结果列表
            return;
        }
 
        for (int i = 0; i < nums.size(); i++) {
            // 规定顺序,避免重复组合
            if (temp.size() > 0 && nums.get(i) < temp.get(temp.size() - 1)) continue;
            temp.add(nums.get(i)); // 添加当前数字到临时组合
            backtrack(temp, nums, result); // 递归调用
            temp.remove(temp.size() - 1); // 恢复状态
        }
    }
 
    public List<TemperatureCycling> getTemList(List<ExportInsProductVO> temperatureCycling) {
        List<TemperatureCycling> temperatureCyclingList = new ArrayList<>();
        List<TemperatureCycling> newTemperatureCyclingList = new ArrayList<>(); // 返回的温度循环数据
        if (CollectionUtils.isNotEmpty(temperatureCycling)) {
            // 根据委托单号、样品编号、套管、光线色标、循环的次数进行分组
            List<ExportInsProductVO> collect = temperatureCycling.stream()
                    .sorted(Comparator.comparing(ExportInsProductVO::getInspectionItem)).collect(Collectors.toList());
            Map<String, List<ExportInsProductVO>> temperatureGroup = collect.stream()
                    .sorted(Comparator.comparing(t -> getInspectionItemSubclassOrder(t.getInspectionItemSubclass()))).collect(Collectors.groupingBy(e ->
                                    e.getEntrustCode() + "@" + e.getSampleCode() + "@" + e.getBushColor() + "@" + e.getColor() + "@" + e.getInspectionItem() + "@" + e.getInspectionItemSubclass(),
                            TreeMap::new,
                            Collectors.toList()));
            // 获取20℃的数据 来进行差值的运算 只获取第一次的20℃常温的数据,根据单号、样品编号好、套管和光纤来(会存在多个单子多个样品)
            Map<String, BigDecimal> map = new HashMap<>();
            for (ExportInsProductVO a : collect) {
                if (a.getInspectionItem().equals("1") && a.getInspectionItemSubclass().equals("20℃(常温)")) {
                    switch (a.getInspectionItemClass()) {
                        case "1310nm":
                            List<Map> insValue = getInsValueList(a.getComValue());
                            BigDecimal decay1310 = BigDecimal.ZERO;
                            if (CollectionUtils.isNotEmpty(insValue)) {
                                decay1310 = new BigDecimal(isNumber(insValue.get(0).get("v").toString()));
 
                            }
                            map.put(a.getEntrustCode() + a.getSampleCode() + a.getBushColor() + a.getColor() + a.getInspectionItemClass(), decay1310);
                            break;
                        case "1550nm":
                            List<Map> insValue1 = getInsValueList(a.getComValue());
                            BigDecimal decay1550 = BigDecimal.ZERO;
                            if (CollectionUtils.isNotEmpty(insValue1)) {
                                decay1550 = new BigDecimal(isNumber(insValue1.get(0).get("v").toString()));
                            }
                            map.put(a.getEntrustCode() + a.getSampleCode() + a.getBushColor() + a.getColor() + a.getInspectionItemClass(), decay1550);
                            break;
                        case "1625nm":
                            List<Map> insValue2 = getInsValueList(a.getComValue());
                            BigDecimal decay1625 = BigDecimal.ZERO;
                            if (CollectionUtils.isNotEmpty(insValue2)) {
                                decay1625 = new BigDecimal(isNumber(insValue2.get(0).get("v").toString()));
                            }
                            map.put(a.getEntrustCode() + a.getSampleCode() + a.getBushColor() + a.getColor() + a.getInspectionItemClass(), decay1625);
                            break;
                        case "1383nm":
                            List<Map> insValue3 = getInsValueList(a.getComValue());
                            BigDecimal decay1383 = BigDecimal.ZERO;
                            if (CollectionUtils.isNotEmpty(insValue3)) {
                                decay1383 = new BigDecimal(isNumber(insValue3.get(0).get("v").toString()));
                            }
                            map.put(a.getEntrustCode() + a.getSampleCode() + a.getBushColor() + a.getColor() + a.getInspectionItemClass(), decay1383);
                            break;
                        case "1490nm":
                            List<Map> insValue4 = getInsValueList(a.getComValue());
                            BigDecimal decay1490 = BigDecimal.ZERO;
                            if (CollectionUtils.isNotEmpty(insValue4)) {
                                decay1490 = new BigDecimal(isNumber(insValue4.get(0).get("v").toString()));
                            }
                            map.put(a.getEntrustCode() + a.getSampleCode() + a.getBushColor() + a.getColor() + a.getInspectionItemClass(), decay1490);
                            break;
                    }
                }
            }
 
            // 根据委托编号、样品编号、循环次数、温度点进行分组
            Map<String, List<ExportInsProductVO>> collect1 = temperatureCycling.stream()
                    .collect(Collectors.groupingBy(e -> e.getEntrustCode() + "@" + e.getSampleCode() + "@" + e.getInspectionItem() + "@" + e.getInspectionItemSubclass()));
 
 
            // 将差值保存
            Map<String, List<BigDecimal>> map1 = new HashMap<>();
            Set<String> strings = new HashSet<>();
            Iterator<Map.Entry<String, List<ExportInsProductVO>>> iterator1 = collect1.entrySet().iterator();
            while (iterator1.hasNext()) {
                Map.Entry<String, List<ExportInsProductVO>> entry = iterator1.next();
                for (ExportInsProductVO a : entry.getValue()) {
                    // 将得到的衰减系数保存 后面要用到
                    strings.add(a.getInspectionItemClass());
                    switch (a.getInspectionItemClass()) {
                        case "1310nm":
                        case "1490nm":
                        case "1383nm":
                        case "1550nm":
                        case "1625nm":
                            List<Map> insValue = getInsValueList(a.getComValue());
                            if (CollectionUtils.isNotEmpty(insValue)) {
                                ArrayList<BigDecimal> bigDecimals = new ArrayList<>();
                                BigDecimal bigDecimal = new BigDecimal(isNumber(insValue.get(0).get("v").toString()));// 当前衰减值
                                BigDecimal bigDecimal1 = map.get(a.getEntrustCode() + a.getSampleCode() + a.getBushColor() + a.getColor() + a.getInspectionItemClass());// 20℃的衰减值
                                BigDecimal v = bigDecimal.subtract(bigDecimal1);
                                bigDecimals.add(v.abs());
                                if (map1.containsKey(a.getEntrustCode() + a.getSampleCode() + a.getInspectionItemSubclass() + a.getInspectionItemClass())) {
                                    map1.get(a.getEntrustCode() + a.getSampleCode() + a.getInspectionItemSubclass() + a.getInspectionItemClass()).addAll(bigDecimals);
                                } else {
                                    map1.put(a.getEntrustCode() + a.getSampleCode() + a.getInspectionItemSubclass() + a.getInspectionItemClass(), bigDecimals);
                                }
                            } else {
                                if (!map1.containsKey(a.getEntrustCode() + a.getSampleCode() + a.getInspectionItemSubclass() + a.getInspectionItemClass())) {
                                    map1.put(a.getEntrustCode() + a.getSampleCode() + a.getInspectionItemSubclass() + a.getInspectionItemClass(), new ArrayList<>());
                                }
                            }
                            break;
                    }
                }
            }
 
 
            Iterator<Map.Entry<String, List<ExportInsProductVO>>> iterator = temperatureGroup.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, List<ExportInsProductVO>> entry = iterator.next();
                TemperatureCycling temperature = new TemperatureCycling();
                for (ExportInsProductVO a : entry.getValue()) {
                    BeanUtils.copyProperties(a, temperature);
                    // 时间格式化
                    if (Objects.nonNull(a.getCheckTime())) {
                        String format = a.getCheckTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                        LocalDate parse = LocalDate.parse(format);
                        temperature.setInsTime(parse);
                    }
                    // 衰减系数获取计算值
                    List<Map> insValue = getInsValueList(a.getComValue());
                    if (CollectionUtils.isNotEmpty(insValue)) {
                        switch (a.getInspectionItemClass()) {
                            case "1310nm":
                                temperature.setAttenuationCoefficient1310(isNumber(insValue.get(0).get("v").toString()));
                                // 20℃(常温)的是没有差值的
                                if (!a.getInspectionItemSubclass().contains("20℃(常温)")) {
                                    BigDecimal v = new BigDecimal(isNumber(insValue.get(0).get("v").toString())).subtract(map.get(a.getEntrustCode() + a.getSampleCode() + a.getBushColor() + a.getColor() + a.getInspectionItemClass()));
                                    String attenuationDifference = v.abs().toString();
                                    temperature.setAttenuationDifference1(attenuationDifference);
                                }
                                break;
                            case "1550nm":
                                temperature.setAttenuationCoefficient1550(isNumber(insValue.get(0).get("v").toString()));
                                // 20℃(常温)的是没有差值的
                                if (!a.getInspectionItemSubclass().contains("20℃(常温)")) {
                                    BigDecimal v = new BigDecimal(isNumber(insValue.get(0).get("v").toString())).subtract(map.get(a.getEntrustCode() + a.getSampleCode() + a.getBushColor() + a.getColor() + a.getInspectionItemClass()));
                                    String attenuationDifference = v.abs().toString();
                                    temperature.setAttenuationDifference2(attenuationDifference);
                                }
                                break;
                            case "1625nm":
                                temperature.setAttenuationCoefficient1625(isNumber(insValue.get(0).get("v").toString()));
                                // 20℃(常温)的是没有差值的
                                if (!a.getInspectionItemSubclass().contains("20℃(常温)")) {
                                    BigDecimal v = new BigDecimal(isNumber(insValue.get(0).get("v").toString())).subtract(map.get(a.getEntrustCode() + a.getSampleCode() + a.getBushColor() + a.getColor() + a.getInspectionItemClass()));
                                    String attenuationDifference = v.abs().toString();
                                    temperature.setAttenuationDifference3(attenuationDifference);
                                }
                                break;
                            case "1383nm":
                                temperature.setAttenuationCoefficient1383(isNumber(insValue.get(0).get("v").toString()));
                                // 20℃(常温)的是没有差值的
                                if (!a.getInspectionItemSubclass().contains("20℃(常温)")) {
                                    BigDecimal v = new BigDecimal(isNumber(insValue.get(0).get("v").toString())).subtract(map.get(a.getEntrustCode() + a.getSampleCode() + a.getBushColor() + a.getColor() + a.getInspectionItemClass()));
                                    String attenuationDifference = v.abs().toString();
                                    temperature.setAttenuationDifference4(attenuationDifference);
                                }
                                break;
                            case "1490nm":
                                temperature.setAttenuationCoefficient1490(isNumber(insValue.get(0).get("v").toString()));
                                // 20℃(常温)的是没有差值的
                                if (!a.getInspectionItemSubclass().contains("20℃(常温)")) {
                                    BigDecimal v = new BigDecimal(isNumber(insValue.get(0).get("v").toString())).subtract(map.get(a.getEntrustCode() + a.getSampleCode() + a.getBushColor() + a.getColor() + a.getInspectionItemClass()));
                                    String attenuationDifference = v.abs().toString();
                                    temperature.setAttenuationDifference5(attenuationDifference);
                                }
                                break;
                        }
                        // 进行衰减差值的最大值赋值
                        StringBuffer value = new StringBuffer();
                        if (strings.contains("1310nm")) {
                            BigDecimal bigDecimal = BigDecimal.ZERO;
                            if (map1.containsKey(a.getEntrustCode() + a.getSampleCode() + a.getInspectionItemSubclass() + "1310nm")) {
                                bigDecimal = Optional.ofNullable(map1.get(a.getEntrustCode() + a.getSampleCode() + a.getInspectionItemSubclass() + "1310nm"))
                                        .orElse(Collections.emptyList()) // 如果值为 null,返回空列表
                                        .stream()
                                        .sorted(Comparator.reverseOrder()) // 降序排序
                                        .findFirst() // 获取第一个元素(最大值)
                                        .orElse(BigDecimal.ZERO); // 如果列表为空,返回默认值(例如 BigDecimal.ZERO)
                            }
                            if (bigDecimal.abs().compareTo(BigDecimal.ZERO) > 0) {
                                value.append("|∆ɑ|1310nm max").append(bigDecimal.abs()).append("dB/km");
                            }
                        }
                        if (strings.contains("1550nm")) {
                            BigDecimal bigDecimal = BigDecimal.ZERO;
                            if (map1.containsKey(a.getEntrustCode() + a.getSampleCode() + a.getInspectionItemSubclass() + "1550nm")) {
                                List<BigDecimal> valuesList = map1.get(a.getEntrustCode() + a.getSampleCode() + a.getInspectionItemSubclass() + "1550nm").stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
                                bigDecimal = valuesList.isEmpty() ? BigDecimal.ZERO : valuesList.get(0);
                            }
                            if (bigDecimal.abs().compareTo(BigDecimal.ZERO) > 0) {
                                value.append("|∆ɑ|1550nm max").append(bigDecimal.abs()).append("dB/km");
                            }
                        }
                        if (strings.contains("1625nm")) {
                            BigDecimal bigDecimal = BigDecimal.ZERO;
                            if (map1.containsKey(a.getEntrustCode() + a.getSampleCode() + a.getInspectionItemSubclass() + "1625nm")) {
                                bigDecimal = map1.get(a.getEntrustCode() + a.getSampleCode() + a.getInspectionItemSubclass() + "1625nm").stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList()).get(0);
                            }
                            if (bigDecimal.abs().compareTo(BigDecimal.ZERO) > 0) {
                                value.append("|∆ɑ|1625nm max").append(bigDecimal.abs()).append("dB/km");
                            }
                        }
 
                        if (strings.contains("1383nm")) {
                            BigDecimal bigDecimal = BigDecimal.ZERO;
                            if (map1.containsKey(a.getEntrustCode() + a.getSampleCode() + a.getInspectionItemSubclass() + "1383nm")) {
                                bigDecimal = map1.get(a.getEntrustCode() + a.getSampleCode() + a.getInspectionItemSubclass() + "1383nm").stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList()).get(0);
                            }
                            if (bigDecimal.abs().compareTo(BigDecimal.ZERO) > 0) {
                                value.append("|∆ɑ|1383nm max").append(bigDecimal.abs()).append("dB/km");
                            }
                        }
 
                        if (strings.contains("1490nm")) {
                            BigDecimal bigDecimal = BigDecimal.ZERO;
                            if (map1.containsKey(a.getEntrustCode() + a.getSampleCode() + a.getInspectionItemSubclass() + "1490nm")) {
                                bigDecimal = map1.get(a.getEntrustCode() + a.getSampleCode() + a.getInspectionItemSubclass() + "1490nm").stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList()).get(0);
                            }
                            if (bigDecimal.abs().compareTo(BigDecimal.ZERO) > 0) {
                                value.append("|∆ɑ|1490nm max").append(bigDecimal.abs()).append("dB/km");
                            }
                        }
                        if (StringUtils.isNotEmpty(value.toString())) {
                            value.insert(0, a.getInspectionItemSubclass() + " ");
                        }
                        temperature.setAttenuationDifferenceMax(value.toString());
                    }
                    temperatureCyclingList.add(temperature);
                }
            }
        }
        temperatureCyclingList = temperatureCyclingList.stream().distinct().collect(Collectors.toList());
        //查询全色谱,过滤色标并排序
        List<String> colorList = dictTypeService.selectDictDataByType("color_type").stream()
                .sorted(Comparator.comparing(SysDictData::getDictSort))
                .map(SysDictData::getDictLabel)
                .collect(Collectors.toList());
        Map<String, List<TemperatureCycling>> collect = temperatureCyclingList.stream().collect(Collectors.groupingBy(TemperatureCycling::getEntrustCode));
        Iterator<Map.Entry<String, List<TemperatureCycling>>> iterator = collect.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, List<TemperatureCycling>> entry = iterator.next();
            //温度循环根据色标排序
            entry.getValue().sort((o1, o2) -> {
                //根据套管色标以及光纤色标排序
                if (StringUtils.isNotBlank(o1.getBushColor()) && StringUtils.isNotBlank(o2.getBushColor())) {
                    //先按样品编号升序
                    if (!Objects.equals(o1.getSampleCode(), o2.getSampleCode())) {
                        if (containsOnlyDigits(o1.getSampleCode()) && containsOnlyDigits(o2.getSampleCode())) {
                            Long o1Num = Long.parseLong(o1.getSampleCode());
                            Long o2Num = Long.parseLong(o2.getSampleCode());
                            return o1Num.compareTo(o2Num);
                        }
                        return o1.getSampleCode().compareTo(o2.getSampleCode());
                    }
                    //循环次数排序
                    if (StringUtils.isNotBlank(o1.getInspectionItem()) && StringUtils.isNotBlank(o2.getInspectionItem())) {
                        if (!Objects.equals(o1.getInspectionItem(), o2.getInspectionItem())) {
                            Integer o1Index = Integer.parseInt(o1.getInspectionItem());
                            Integer o2Index = Integer.parseInt(o2.getInspectionItem());
                            return o1Index.compareTo(o2Index);
                        }
                    }
                    //套管色标排序
                    if (!Objects.equals(o1.getBushColor(), o2.getBushColor())) {
                        Integer o1Index = colorList.indexOf(o1.getBushColor());
                        Integer o2Index = colorList.indexOf(o2.getBushColor());
                        return o1Index.compareTo(o2Index);
                    }
                    //光纤带排序
                    if (StringUtils.isNotBlank(o1.getCode()) && StringUtils.isNotBlank(o2.getCode())) {
                        if (!Objects.equals(o1.getCode(), o2.getCode())) {
                            return o1.getCode().compareTo(o2.getCode());
                        }
                    }
                    //光纤色标排序
                    if (StringUtils.isNotBlank(o1.getColor()) && StringUtils.isNotBlank(o2.getColor())) {
                        if (!Objects.equals(o1.getColor(), o2.getColor())) {
                            Integer o1Index = colorList.indexOf(o1.getColor());
                            Integer o2Index = colorList.indexOf(o2.getColor());
                            return o1Index.compareTo(o2Index);
                        }
                    }
                }
                return 0;
            });
            newTemperatureCyclingList.addAll(entry.getValue());
        }
        //温度循环根据色标排序
//        temperatureCyclingList.sort((o1, o2) -> {
//            // 处理 null 值
//            if (o1 == null && o2 == null) return 0;
//            if (o1 == null) return -1;
//            if (o2 == null) return 1;
//
//            // ---------------------- 1. 按样品编号排序 ----------------------
//            int sampleCodeCompare = compareSampleCode(o1.getSampleCode(), o2.getSampleCode());
//            if (sampleCodeCompare != 0) return sampleCodeCompare;
//
//            // ---------------------- 2. 按套管色标排序 ----------------------
//            int bushColorCompare = compareColor(o1.getBushColor(), o2.getBushColor(), colorList);
//            if (bushColorCompare != 0) return bushColorCompare;
//
//            // ---------------------- 3. 按光纤带排序 ----------------------
//            int codeCompare = compareNullableString(o1.getCode(), o2.getCode());
//            if (codeCompare != 0) return codeCompare;
//
//            // ---------------------- 4. 按光纤色标排序 ----------------------
//            return compareColor(o1.getColor(), o2.getColor(), colorList);
//        });
        return newTemperatureCyclingList;
    }
 
    //1: 样品编号比较(支持数字和字符串混合排序)
    private static int compareSampleCode(String code1, String code2) {
        if (Objects.equals(code1, code2)) return 0;
 
        boolean isCode1Numeric = containsOnlyDigits(code1);
        boolean isCode2Numeric = containsOnlyDigits(code2);
 
        // 如果都是数字,转为 Long 比较
        if (isCode1Numeric && isCode2Numeric) {
            return Long.compare(Long.parseLong(code1), Long.parseLong(code2));
        }
 
        // 如果一个是数字,另一个不是,数字优先
        if (isCode1Numeric != isCode2Numeric) {
            return isCode1Numeric ? -1 : 1;
        }
 
        // 其他情况按字符串比较
        return code1.compareTo(code2);
    }
 
    //2: 色标比较(处理不在 colorList 中的情况)
    private static int compareColor(String color1, String color2, List<String> colorList) {
        if (Objects.equals(color1, color2)) return 0;
 
        // 处理 colorList 中的索引
        int index1 = colorList.indexOf(color1);
        int index2 = colorList.indexOf(color2);
 
        // 将不在列表中的色标统一排序到最后(赋予最大值)
        index1 = index1 == -1 ? Integer.MAX_VALUE : index1;
        index2 = index2 == -1 ? Integer.MAX_VALUE : index2;
 
        return Integer.compare(index1, index2);
    }
 
    //3: 处理可能为空的字符串比较
    private static int compareNullableString(String str1, String str2) {
        if (Objects.equals(str1, str2)) return 0;
 
        // 空字符串视为较小值
        boolean isStr1Blank = StringUtils.isBlank(str1);
        boolean isStr2Blank = StringUtils.isBlank(str2);
 
        if (isStr1Blank && isStr2Blank) return 0;
        if (isStr1Blank) return -1;
        if (isStr2Blank) return 1;
 
        // 非空时按自然顺序比较
        return str1.compareTo(str2);
    }
 
    public List<Map> getInsValueList(String insValue) {
        List<Map> list = new ArrayList<>();
        if (StringUtils.isNotBlank(insValue)) {
            List<Map> maps = JSONArray.parseArray(insValue, Map.class);
            list.addAll(maps);
        }
        return list;
    }
 
    /**
     * 判断是否可以转数字
     */
    public String isNumber(String str) {
        if (NumberUtil.isDouble(str)) {
            return str;
        } else {
            return "0";
        }
    }
 
    /**
     * 排序规格
     *
     * @param t
     * @return
     */
    public Integer getInspectionItemSubclassOrder(String t) {
        switch (t) {
            case "20℃(常温)":
                return 1;
            case "20℃":
                return 2;
            case "-40℃":
                return 3;
            case "65℃":
                return 4;
            default:
                return 5; // 未知温度点
        }
    }
 
 
    @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 = new HashMap<>();
        if (map1.get("look") == 1) costStatisticsDto.setCreateUser(map1.get("userId"));
        // 获取当前人所在实验室
        Integer userId = 1;
        String departLimsId = userMapper.selectById(userId).getDepartLimsId();
        String laboratory = "";
        if (StringUtils.isNotBlank(departLimsId)) {
            String[] split1 = departLimsId.split(",");
            for (String s : split1) {
                if (StringUtils.isNotBlank(s) && (!Arrays.asList("1", "22").contains(s))) {
                    laboratory = insOrderMapper.getDepartment(Integer.parseInt(s));
                }
            }
        }
        LocalDate today = LocalDate.parse(split[1]);
        LocalTime end = LocalTime.of(23, 59, 59);
        IPage<CostStatisticsDto> dtoIPage = insOrderMapper.selectCostStatistics(page, QueryWrappers.queryWrappers(costStatisticsDto), split[0], today.atTime(end).toString(), laboratory);
        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);
        // 获取当前人所在实验室
        Integer userId = 1;
        String departLimsId = userMapper.selectById(userId).getDepartLimsId();
        String laboratory = "";
        if (StringUtils.isNotBlank(departLimsId)) {
            String[] split1 = departLimsId.split(",");
            for (String s : split1) {
                if (StringUtils.isNotBlank(s) && (!Arrays.asList("1", "22").contains(s))) {
                    laboratory = insOrderMapper.getDepartment(Integer.parseInt(s));
                }
            }
        }
        LocalDate today = LocalDate.parse(split[1]);
        LocalTime end = LocalTime.of(23, 59, 59);
        List<CostStatisticsDto> costStatisticsDtos = insOrderMapper.selectCostStatistics2(QueryWrappers.queryWrappers(costStatisticsDto), split[0], today.atTime(end).toString(), laboratory);
//        double totalPrice = costStatisticsDtos.stream()
//                .filter(dto -> dto.getPrice() != null) // 过滤掉价格为 null 的对象
//                .mapToDouble(value -> value.getPrice().doubleValue() * value.getNum())
//                .sum();
        BigDecimal total = BigDecimal.ZERO;
        for (CostStatisticsDto dto : costStatisticsDtos) {
            if (Objects.isNull(dto.getPrice()) || dto.getPrice().compareTo(BigDecimal.ZERO) == 0) {
                dto.setPrice(new BigDecimal(0));
            }
            total = total.add(dto.getPrice());
        }
        map.put("total", total);
        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
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    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 (!"光纤".equals(sampleProductDto3.getIoSampleType()) &&
                    !"光纤带".equals(sampleProductDto3.getIoSampleType()) &&
                    !"钢绞线".equals(sampleProductDto3.getIoSampleType()) &&
                    sampleProductDto3.getInsProduct().stream().noneMatch(i -> StringUtils.equals("光纤接头损耗", i.getInspectionItem()))
            ) {
                return true;
            }
            if (processedCodes.contains(sampleProductDto3.getCode())) {
                return false;
            } else {
                processedCodes.add(sampleProductDto3.getCode());
                return true;
            }
        }).collect(Collectors.toList());
        return sampleProductDto3s;
    }
 
    @Override
    public void export(CostStatisticsDto costStatisticsDto, HttpServletResponse response) throws IOException {
        // 判断当前人属于电力 还是 通信  过滤掉为1
        List<String> dept = new ArrayList<>();
        Map<String, Integer> map1 = new HashMap<>();
        User user = userMapper.selectById(map1.get("userId"));//当前登录的人
        String departLimsId = user.getDepartLimsId();
        String laboratory = "";
        if (StringUtils.isNotBlank(departLimsId) && Objects.nonNull(departLimsId)) {
            String[] split = departLimsId.split(",");
            for (int i = 0; i < split.length; i++) {
                if (StringUtils.isNotBlank(split[i])) {
                    if (split[i].equals("1") || split[i].equals("22")) {
                        continue;
                    }
                    laboratory = insOrderMapper.getDepartment(Integer.parseInt(split[i]));
                    dept.add(insOrderMapper.getDepartment(Integer.parseInt(split[i])));
                }
            }
        }
        //查询导出的费用统计数据
        String dates = costStatisticsDto.getDates();
        String[] split = dates.replaceAll("\\[", "").replaceAll("]", "").replaceAll("\"", "").split(",");
        costStatisticsDto.setDates(null);
 
 
        LocalDate today = LocalDate.parse(split[1]);
        LocalTime end = LocalTime.of(23, 59, 59);
        List<CostStatisticsDto> costStatisticsDtos = insOrderMapper.selectCostStatistics2(QueryWrappers.queryWrappers(costStatisticsDto), split[0], today.atTime(end).toString(), laboratory);
        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();
            List<CostStatisticsDto> costStatisticsDtos1 = new ArrayList<>();
            for (Map.Entry<String, List<CostStatisticsDto>> companyDataEntry : groupByCompany.entrySet()) {
                String sheetName = companyDataEntry.getKey();
                List<CostStatisticsDto> dataList = companyDataEntry.getValue();
                // 根据该单子的实验室 来判断是否属于当前登录人的部门
                for (CostStatisticsDto costStatisticsDto1 : dataList) {
                    if (StringUtils.isNotBlank(costStatisticsDto1.getLaboratory()) && Objects.nonNull(costStatisticsDto1.getLaboratory())) {
                        if (dept.contains(costStatisticsDto1.getLaboratory())) {
                            costStatisticsDtos1.add(costStatisticsDto1);
                        }
                    }
                }
                WriteSheet mainSheet = EasyExcel.writerSheet(sheetName)
                        .head(CostStatisticsDto.class)
                        .registerWriteHandler(new SimpleColumnWidthStyleStrategy(25))
                        .build();
                excelWriter.write(costStatisticsDtos1, mainSheet);
                costStatisticsDtos1.clear();
            }
            // 关闭流
            excelWriter.finish();
        } catch (IOException e) {
            throw new RuntimeException("导出失败");
        }
    }
 
    public static boolean containsOnlyDigits(String str) {
        String regex = "\\d+"; // 匹配一个或多个数字
        return Pattern.matches(regex, str);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public Boolean hasSendUrgentOrder() {
        Integer userId = 1;
        //查询当前客户的紧急额度
        Map<String, Object> quotaMap = baseMapper.selectCurrentCompanyUrgentQuota(userId);
        if (quotaMap == null) {
            return false;
        }
        //查询当天客户已创建的紧急订单
        long count = baseMapper.selectCount(Wrappers.<InsOrder>lambdaQuery()
                .eq(InsOrder::getCompany, quotaMap.get("company"))
                .eq(InsOrder::getType, 2)
                .gt(InsOrder::getCreateTime, LocalDateTime.of(LocalDate.now(), LocalTime.MIN))
                .lt(InsOrder::getCreateTime, LocalDateTime.of(LocalDate.now(), LocalTime.MAX)));
        int quota = Integer.parseInt(quotaMap.get("quota").toString());
        return quota > count;
    }
}