yanghb
2025-02-18 1fc203f758ace853f4bfa900c422c2f741d09e79
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
package com.zzg.system.service.state.impl;
 
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.zzg.common.core.domain.BaseEntity;
import com.zzg.common.core.domain.entity.state.*;
import com.zzg.common.core.domain.entity.system.SysDept;
import com.zzg.common.enums.*;
import com.zzg.common.exception.GlobalException;
import com.zzg.common.utils.FileUtil;
import com.zzg.common.utils.PageUtils;
import com.zzg.common.utils.SecurityUtils;
import com.zzg.system.convert.StateProjectConvert;
import com.zzg.system.domain.bo.*;
import com.zzg.system.domain.vo.*;
import com.zzg.system.mapper.state.*;
import com.zzg.system.service.state.StateHouseholdOwnerService;
import com.zzg.system.service.state.StateProcessTemplateService;
import com.zzg.system.service.state.StateSettlementService;
import com.zzg.system.service.system.ISysDeptService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
 
@Service
@RequiredArgsConstructor
public class StateSettlementImpl extends ServiceImpl<StateSettlementMapper, StateSettlement> implements StateSettlementService {
 
    private final StateSettlementMapper settlementMapper;
    private final StateProjectMapper stateProjectMapper;
    private final StateHouseholdMapper stateHouseholdMapper;
    private final StateAgreementMapper stateAgreementMapper;
    private final StateHouseholdOwnerService stateHouseholdOwnerService;
    private final StateAssetMapper stateAssetMapper;
    private final ISysDeptService deptService;
    private final StateProcessTemplateService processTemplateService;
    private final StateSettlementMapper stateSettlementMapper;
 
    private List<HouseholdVO> listHouseHoldVO(SettlementBO settlementBO) {
 
        List<HouseholdVO> householdVOList = settlementMapper.listSettleData(settlementBO);
        if (CollectionUtils.isEmpty(householdVOList)) {
            return new ArrayList<>();
        }
 
        List<HouseholdVO> householdVOS = new ArrayList<>();
        List<HouseholdVO> voArrayList;
        //拼接名字
        List<String> houseIdList = householdVOList.stream()
                .map(HouseholdVO::getId) // 获取 houseStateId
                .filter(Objects::nonNull) // 过滤掉 houseStateId 为 null 的情况
                .distinct() // 去重
                .collect(Collectors.toList());
 
        LambdaQueryWrapper<StateHouseholdOwner> householdOwnerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        householdOwnerLambdaQueryWrapper.in(StateHouseholdOwner::getStateHouseholdId, houseIdList);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(settlementBO.getOwnerName())) {
            householdOwnerLambdaQueryWrapper.like(StateHouseholdOwner::getOwnerName, settlementBO.getOwnerName());
        }
        List<StateHouseholdOwner> stateHouseholdOwners = stateHouseholdOwnerService.list(householdOwnerLambdaQueryWrapper);
 
        Map<String, List<StateHouseholdOwner>> ownerMap = stateHouseholdOwners.stream().collect(Collectors.groupingBy(StateHouseholdOwner::getStateHouseholdId));
        if (org.apache.commons.lang3.StringUtils.isNotBlank(settlementBO.getOwnerName())) {
            householdVOList = householdVOList.stream().filter(data -> ownerMap.containsKey(data.getId())).collect(Collectors.toList());
        }
        householdVOList.sort(Comparator.comparing(BaseEntity::getCreateTime));
        Map<String, HouseholdVO> listMap = householdVOList.stream().collect(Collectors.toMap(HouseholdVO::getId, Function.identity()));
        //拼接名字
        for (String houseId : listMap.keySet()) {
            HouseholdVO assetDetailVO = listMap.get(houseId);
            //组装名字
            if (ownerMap.containsKey(houseId)) {
                String fullName = ownerMap.get(houseId).stream().map(StateHouseholdOwner::getOwnerName).collect(Collectors.joining("|"));
                assetDetailVO.setOwnerName(fullName);
                assetDetailVO.setOwnerType(ownerMap.get(houseId).get(0).getOwnerType());
                assetDetailVO.setPersonNum((long) ownerMap.get(houseId).size());
            }
            householdVOS.add(assetDetailVO);
        }
 
        voArrayList = appendSettleData(settlementBO.getIsSettled(), houseIdList, settlementBO, householdVOS);
 
        List<HouseholdVO> result = new ArrayList<>();
 
        //根据批次名字存在进行过滤
        if (StringUtils.isNoneBlank(settlementBO.getSettleName())) {
            result.addAll(voArrayList.stream()
                    .filter(data -> Objects.nonNull(data) && Objects.equals(data.getSettleName(), settlementBO.getSettleName()))
                    .collect(Collectors.toList()));
        } else {
            result.addAll(voArrayList);
        }
        //过滤出房产删除之后的数据
        result = result.stream().filter(data -> !Objects.equals(data.getDelFlag(), DeleteFlagEnum.DELETED.getKey())).collect(Collectors.toList());
        //赋值房屋用途和产别数据
        appendStrData(result);
        return result;
    }
 
    /**
     * 安置情况页面数据
     * @param settlementBO
     * @return
     */
    @Override
    public PageInfo<HouseholdVO> listSettleData(SettlementBO settlementBO) {
        PageUtils.startPage();
        //根据查询条件查询房产数据
        List<HouseholdVO> householdVOList = settlementMapper.listSettleData(settlementBO);
        if (CollectionUtils.isEmpty(householdVOList)) {
            return new PageInfo<>();
        }
        PageInfo<HouseholdVO> pageInfo = new PageInfo<>(householdVOList);
 
        List<HouseholdVO> householdVOS = new ArrayList<>();
        List<HouseholdVO> voArrayList;
        //拼接名字
        List<String> houseIdList = householdVOList.stream()
                .map(HouseholdVO::getId) // 获取 houseStateId
                .filter(Objects::nonNull) // 过滤掉 houseStateId 为 null 的情况
                .distinct() // 去重
                .collect(Collectors.toList());
        //根据房产id查询所有权利人信息
        LambdaQueryWrapper<StateHouseholdOwner> householdOwnerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        householdOwnerLambdaQueryWrapper.in(StateHouseholdOwner::getStateHouseholdId, houseIdList);
        if (!com.zzg.common.utils.StringUtils.isEmpty(settlementBO.getOwnerName())) {
            householdOwnerLambdaQueryWrapper.like(StateHouseholdOwner::getOwnerName, settlementBO.getOwnerName());
        }
        List<StateHouseholdOwner> stateHouseholdOwners = stateHouseholdOwnerService.list(householdOwnerLambdaQueryWrapper);
        //根据房产id 将权利人分组
        Map<String, List<StateHouseholdOwner>> ownerMap = stateHouseholdOwners.stream().collect(Collectors.groupingBy(StateHouseholdOwner::getStateHouseholdId));
        if (!com.zzg.common.utils.StringUtils.isEmpty(settlementBO.getOwnerName())) {
            householdVOList = householdVOList.stream().filter(data -> ownerMap.containsKey(data.getId())).collect(Collectors.toList());
        }
 
        Map<String, HouseholdVO> listMap = householdVOList.stream().collect(Collectors.toMap(HouseholdVO::getId, Function.identity()));
        //拼接名字
        for (String houseId : listMap.keySet()) {
            HouseholdVO assetDetailVO = listMap.get(houseId);
            //组装名字
            if (ownerMap.containsKey(houseId)) {
                String fullName = ownerMap.get(houseId).stream().map(StateHouseholdOwner::getOwnerName).collect(Collectors.joining("|"));
                assetDetailVO.setOwnerName(fullName);
                assetDetailVO.setOwnerType(ownerMap.get(houseId).get(0).getOwnerType());
                assetDetailVO.setPersonNum((long) ownerMap.get(houseId).size());
            }
            householdVOS.add(assetDetailVO);
        }
 
        voArrayList = appendSettleData(settlementBO.getIsSettled(), houseIdList, settlementBO, householdVOS);
 
        List<HouseholdVO> result = new ArrayList<>();
 
        //根据批次名字存在进行过滤
        if (StringUtils.isNoneBlank(settlementBO.getSettleName())) {
            result.addAll(voArrayList.stream()
                    .filter(data -> Objects.nonNull(data) && Objects.equals(data.getSettleName(), settlementBO.getSettleName()))
                    .collect(Collectors.toList()));
        } else {
            result.addAll(voArrayList);
        }
 
        appendStrData(result);
        List<String> deptIdList = result.stream()
                .map(HouseholdVO::getDeptId)
                .collect(Collectors.toList());
        Map<String, SysDept> stringSysDeptMap = deptService.selectMapDeptById(deptIdList);
 
        for (HouseholdVO e : result) {
            SysDept sysDept = stringSysDeptMap.get(e.getDeptId());
            if (Objects.nonNull(sysDept)) {
                e.setBelongingStreetTown(sysDept.getDeptName());
            }
        }
        result.sort((o1, o2) -> {
            int num1 = extractNumber(o1.getSettleName());
            int num2 = extractNumber(o2.getSettleName());
            return Integer.compare(num1, num2);
        });
        pageInfo.setList(result);
        pageInfo.setTotal(pageInfo.getTotal());
        return pageInfo;
    }
 
    public static int extractNumber(String settleName) {
        if (StringUtils.isBlank(settleName)) {
            return 0;
        }
        // 使用正则表达式提取字符串中的数字
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(settleName);
        if (matcher.find()) {
            return Integer.parseInt(matcher.group());
        }
        return 0; // 如果没有数字部分,返回 0
    }
 
    private List<HouseholdVO> appendSettleData(Integer isSettled, List<String> houseIdList
            , SettlementBO settlementBO
            , List<HouseholdVO> householdVOS) {
        List<HouseholdVO> voArrayList = new ArrayList<>();
        LambdaQueryWrapper<StateSettlement> stateSettlementLambdaQueryWrapper = new LambdaQueryWrapper<>();
        stateSettlementLambdaQueryWrapper.in(StateSettlement::getStateHouseholdId, houseIdList);
        stateSettlementLambdaQueryWrapper.eq(StateSettlement::getDelFlag, DeleteFlagEnum.NOT_DELETED.getKey());
        stateSettlementLambdaQueryWrapper.isNotNull(StateSettlement::getAuditStatus);
        //根据条件查询安置情况
        List<StateSettlement> stateSettlementList = this.list(stateSettlementLambdaQueryWrapper);
 
        Map<String, String> departmentMap = stateSettlementList.stream().collect(Collectors.toMap(StateSettlement::getStateHouseholdId, StateSettlement::getSettleDepartment));
 
        householdVOS.forEach(innerHouse -> {
            if (departmentMap.containsKey(innerHouse.getId())) {
                innerHouse.setSettleDepartment(departmentMap.get(innerHouse.getId()));
            }
        });
 
        //根据入参区分是否安置
        if (Objects.nonNull(settlementBO.getIsSettled())) {
            //未安置
            if (Objects.equals(settlementBO.getIsSettled(), SettledProcessEnum.NOT_SETTLE.getValue())) {
                List<String> settledHouseId;
                if (CollectionUtils.isNotEmpty(stateSettlementList)) {
                    List<String> settledHouseIdList = stateSettlementList.stream().map(StateSettlement::getStateHouseholdId).collect(Collectors.toList());
                    //过滤未安置的房产id
                    settledHouseId = houseIdList.stream().filter(e -> !settledHouseIdList.contains(e)).collect(Collectors.toList());
                    List<String> finalSettledHouseId = settledHouseId;
                    voArrayList.addAll(householdVOS.stream().filter(data -> finalSettledHouseId.contains(data.getId())).collect(Collectors.toList()));
                } else {
                    voArrayList.addAll(householdVOS);
                }
            //已安置
            } else {
                //已安置房产id列表
                List<String> settledHouseId = stateSettlementList.stream().map(StateSettlement::getStateHouseholdId).collect(Collectors.toList());
                //过滤已安置的房产
                List<HouseholdVO> list = householdVOS.stream().filter(data -> settledHouseId.contains(data.getId())).collect(Collectors.toList());
                //设置安置时间 安置状态 安置批次
                Map<String, StateSettlement> settlementMap = stateSettlementList
                        .stream().collect(Collectors.toMap(StateSettlement::getStateHouseholdId, Function.identity()));
                list.forEach(innerHouse -> {
                    if (settlementMap.containsKey(innerHouse.getId())) {
                        StateSettlement stateSettlement = settlementMap.get(innerHouse.getId());
                        innerHouse.setSettleName(Optional.ofNullable(stateSettlement.getSettleName()).orElse(""));
                        innerHouse.setSettleStatus(Optional.ofNullable(stateSettlement.getAuditStatus()).orElse(0));
                        innerHouse.setSettleTime(stateSettlement.getCreateTime());
                        innerHouse.setTaskId(stateSettlement.getTaskId());
                    }
                });
                voArrayList.addAll(list);
            }
        } else {
            //对于没有传是否安置的参数的情况下不做数据筛选
            voArrayList.addAll(householdVOS);
        }
        voArrayList.forEach(e -> e.setHouseHoldArea(BigDecimal.valueOf(e.getHouseHoldArea()).setScale(2, RoundingMode.UP).doubleValue()));
        return voArrayList;
    }
 
    private void appendStrData(List<HouseholdVO> result) {
        Map<Integer, String> houseUsingMap = Stream.of(HouseUsingTypeEnum.values()).collect(Collectors.toMap(HouseUsingTypeEnum::getValue, HouseUsingTypeEnum::getText));
 
        Map<Integer, String> stringMap = Stream.of(HouseProductionTypeEnum.values()).collect(Collectors.toMap(HouseProductionTypeEnum::getValue, HouseProductionTypeEnum::getText));
 
        Map<Integer, String> agreeMoveMap = Stream.of(HouseMoveEnum.values()).collect(Collectors.toMap(HouseMoveEnum::getValue, HouseMoveEnum::getText));
        result.forEach(data -> {
            if (houseUsingMap.containsKey(data.getHouseUsingType())) {
                data.setHouseUsingTypeStr(houseUsingMap.get(data.getHouseUsingType()));
            }
            if (stringMap.containsKey(data.getProductionType())) {
                data.setProductionTypeStr(stringMap.get(data.getProductionType()));
            }
            if (agreeMoveMap.containsKey(data.getAgreeMove())) {
                data.setAgreeMoveStr(agreeMoveMap.get(data.getAgreeMove()));
            }
        });
    }
 
    @Override
    public List<HouseholdVO> exportSettleData(SettlementBO settlementBO, HttpServletResponse response) {
 
        List<HouseholdVO> result = listHouseHoldVO(settlementBO);
 
        if (CollectionUtils.isEmpty(result)) {
            return Collections.emptyList();
        }
 
 
        return result;
    }
 
    /**
     * 安置详情
     * @param settlementDetailBO
     * @return
     */
    @Override
    public SettlementDetailPageVO listDetailData(SettlementDetailBO settlementDetailBO) {
        SettlementDetailPageVO pageVO = new SettlementDetailPageVO();
 
        PageUtils.startPage();
        //分页查询安置情况
        List<SettlementDetailVO> settlementDetailVOS = settlementMapper.listSettleDetail(settlementDetailBO);
        if (CollectionUtils.isEmpty(settlementDetailVOS)) {
            pageVO.setPageData(new PageInfo<>());
            return pageVO;
        }
 
        PageInfo<SettlementDetailVO> settlementDetailVOPageInfo = new PageInfo<>(settlementDetailVOS);
        List<SettlementDetailVO> detailVOS = new ArrayList<>();
        //拼接名字
        //根据房产id进行分组
        Map<String, SettlementDetailVO> householdMap = settlementDetailVOS.stream().filter(Objects::nonNull).collect(Collectors.toMap(StateSettlement::getStateHouseholdId, Function.identity()));
        for (Map.Entry<String, SettlementDetailVO> entry : householdMap.entrySet()) {
            String householdId = entry.getKey();
            SettlementDetailVO innerList = householdMap.get(householdId);
            Double beforeHouseHoldArea = Optional.ofNullable(innerList.getBeforeHouseHoldArea()).orElse(0.0);
            Double exchangeArea = Optional.ofNullable(innerList.getExchangeArea()).orElse(0.0);
            BigDecimal difArea = new BigDecimal(beforeHouseHoldArea - exchangeArea).setScale(2, BigDecimal.ROUND_HALF_UP);
            innerList.setDifArea(difArea.doubleValue());
            double agreementMoney = Optional.ofNullable(innerList.getAgreementMooney()).orElse(0.0);
            double exchangeMoney = Optional.ofNullable(innerList.getExchangeMoney()).orElse(0.0);
            double difMoney = new BigDecimal(agreementMoney-exchangeMoney).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            innerList.setDifMoney(difMoney);
            detailVOS.add(innerList);
        }
        settlementDetailVOPageInfo.setList(detailVOS);
        pageVO.setPageData(settlementDetailVOPageInfo);
        reBuildOneObject(settlementDetailBO.getProjectId(), pageVO);
        return pageVO;
    }
 
    @Override
    public SettlementDetailPageVO listDetailUpdateData(SettlementDetailBO settlementDetailBO) {
        SettlementDetailPageVO pageVO = new SettlementDetailPageVO();
        //回显用
        //对于新添加的数据但是没有提交 需要默认展示赔偿方式为 最新的未审核的安置房产的赔偿方式
        LambdaQueryWrapper<StateHousehold> stateHouseholdLambdaQueryWrapper = new LambdaQueryWrapper<>();
        stateHouseholdLambdaQueryWrapper.in(StateHousehold::getStateProjectId, settlementDetailBO.getProjectId());
        List<StateHousehold> stateHouseholds = stateHouseholdMapper.selectList(stateHouseholdLambdaQueryWrapper);
 
        if (CollectionUtils.isEmpty(stateHouseholds)) {
            pageVO.setPageData(new PageInfo<>());
            return pageVO;
        }
 
        LambdaQueryWrapper<StateSettlement> stateSettlementLambdaQueryWrapper = new LambdaQueryWrapper<>();
        stateSettlementLambdaQueryWrapper.in(StateSettlement::getStateHouseholdId,
                stateHouseholds.stream().map(StateHousehold::getId).collect(Collectors.toList()));
        stateSettlementLambdaQueryWrapper.isNull(StateSettlement::getAuditStatus);
        stateSettlementLambdaQueryWrapper.orderByDesc(StateSettlement::getCreateTime);
        //查询安置情况
        List<StateSettlement> stateSettlementList = this.list(stateSettlementLambdaQueryWrapper);
        if (CollectionUtils.isNotEmpty(stateSettlementList)) {
            String latestHouseId = stateSettlementList.get(0).getStateHouseholdId();
            Optional<StateHousehold> stateHousehold = stateHouseholds.stream().filter(data -> Objects.equals(data.getId(), latestHouseId)).findFirst();
            if (Objects.isNull(settlementDetailBO.getCompensationType())) {
                settlementDetailBO.setCompensationType(stateHousehold.isPresent()
                        ? stateHousehold.get().getCompensationType() : CompensationCategoryEnum.PROPERTY_SWAP_2.getCode());
                settlementDetailBO.setBatchName(stateSettlementList.get(0).getSettleName());
            }
        }
 
        PageUtils.startPage();
        List<SettlementDetailVO> settlementDetailVOS = settlementMapper.listSettleUpdateDetail(settlementDetailBO);
        if (CollectionUtils.isEmpty(settlementDetailVOS)) {
            pageVO.setPageData(new PageInfo<>());
            return pageVO;
        }
        PageInfo<SettlementDetailVO> settlementDetailVOPageInfo = new PageInfo<>(settlementDetailVOS);
        List<SettlementDetailVO> detailVOS = new ArrayList<>();
 
        //拼接名字
        Map<String, SettlementDetailVO> householdMap = settlementDetailVOS.stream().filter(Objects::nonNull).collect(Collectors.toMap(StateSettlement::getStateHouseholdId, Function.identity()));
        for (Map.Entry<String, SettlementDetailVO> entry : householdMap.entrySet()) {
            String householdId = entry.getKey();
            SettlementDetailVO innerList = householdMap.get(householdId);
            Double beforeHouseHoldArea = Optional.ofNullable(innerList.getBeforeHouseHoldArea()).orElse(0.0);
            Double exchangeArea = Optional.ofNullable(innerList.getExchangeArea()).orElse(0.0);
            BigDecimal difArea = new BigDecimal(beforeHouseHoldArea - exchangeArea).setScale(2, BigDecimal.ROUND_HALF_UP);
            innerList.setDifArea(difArea.doubleValue());
            double agreementMoney = Optional.ofNullable(innerList.getAgreementMooney()).orElse(0.0);
            double exchangeMoney = Optional.ofNullable(innerList.getExchangeMoney()).orElse(0.0);
            double difMoney = new BigDecimal(agreementMoney).subtract(new BigDecimal(exchangeMoney)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            innerList.setDifMoney(difMoney);
            detailVOS.add(innerList);
        }
        settlementDetailVOPageInfo.setList(detailVOS);
        pageVO.setPageData(settlementDetailVOPageInfo);
        reBuildOneObject(settlementDetailBO.getProjectId(), pageVO);
        return pageVO;
    }
 
 
    /**
     * 抽离第一个
     */
    private void reBuildOneObject(String id, SettlementDetailPageVO pageVO) {
        if (ObjectUtil.isEmpty(pageVO) || ObjectUtil.isEmpty(pageVO.getPageData()) || ObjectUtil.isEmpty(pageVO.getPageData().getList())) {
            return;
        }
 
        // 使用Stream简化循环查找
        SettlementDetailVO obj = pageVO.getPageData().getList()
                .stream()
                .filter(item -> item.getProjectId().equals(id))
                .findFirst()
                .orElse(new SettlementDetailVO());
        // 如果未找到匹配的对象,直接返回
        if (ObjectUtil.isEmpty(obj)) {
            return;
        }
 
        // 设置值
        pageVO.setSettleName(obj.getSettleName());
        pageVO.setSettleTime(ObjectUtil.isNotEmpty(obj.getCreateTime()) ? obj.getCreateTime() : null);
        pageVO.setAuditStatus(obj.getAuditStatus());
        pageVO.setAuditStatus(obj.getAuditStatus());
        pageVO.setFileUrl(obj.getFileUrl());
        // 查询StateHousehold并设置置换条件
        if (ObjectUtil.isNotEmpty(obj.getCompensationType())) {
            pageVO.setCompensationType(obj.getCompensationType());
        }
    }
 
    /**
     * 外层项目实施数据
     * @param projectId
     * @return
     */
    @Override
    public SettlementSumVO sumSettleData(String projectId) {
        LambdaQueryWrapper<StateProject> stateProjectQueryWrapper = new LambdaQueryWrapper<>();
        stateProjectQueryWrapper.eq(StateProject::getId, projectId);
        //查询项目
        StateProject stateProject = stateProjectMapper.selectOne(stateProjectQueryWrapper);
        if (Objects.isNull(stateProject)) {
            return new SettlementSumVO();
        }
        //查询房产
        LambdaQueryWrapper<StateHousehold> stateHouseholdQueryWrapper = new LambdaQueryWrapper<>();
        stateHouseholdQueryWrapper.eq(StateHousehold::getStateProjectId, projectId);
        List<StateHousehold> stateHouseholds = stateHouseholdMapper.selectList(stateHouseholdQueryWrapper);
 
        if (CollectionUtils.isEmpty(stateHouseholds)) {
            return new SettlementSumVO();
        }
 
        SettlementSumVO settlementSumVO = new SettlementSumVO();
        //查询房产的协议/安置情况
        List<String> householdIds = stateHouseholds.stream().map(StateHousehold::getId).distinct().collect(Collectors.toList());
        //查询结算
        LambdaQueryWrapper<StateSettlement> stateSettlementQueryWrapper = new LambdaQueryWrapper<>();
        stateSettlementQueryWrapper.in(StateSettlement::getStateHouseholdId, householdIds);
        stateSettlementQueryWrapper.isNotNull(StateSettlement::getAuditStatus);
        List<StateSettlement> stateSettlementList = this.list(stateSettlementQueryWrapper);
        if (CollectionUtils.isEmpty(stateSettlementList)) {
            settlementSumVO.setSettlementMoney((double) 0);
            settlementSumVO.setSettlementArea((double) 0);
            settlementSumVO.setSettlementPersons(0);
            settlementSumVO.setUnsettledPersons(stateHouseholds.size());
        }
        settlementSumVO.setSettlementPersons(stateSettlementList.size());
        settlementSumVO.setUnsettledPersons(householdIds.size() - stateSettlementList.size());
        //区分安置类型 产权置换/货币补偿
        Map<Integer, List<StateHousehold>> compensationTypeMap = stateHouseholds
                .stream()
                .collect(Collectors.groupingBy(StateHousehold::getCompensationType));
 
        long goodsPerson = 0;
        long moneyPerson = 0;
        double totalCompensationArea = 0;
        double totalCompensationMoney = 0;
 
        for (Integer type : compensationTypeMap.keySet()) {
 
            List<StateHousehold> compensationHouse = compensationTypeMap.get(type);
            //房屋置换人员名单
            if (Objects.equals(ResettlementTypeEnum.GOODS.getValue(), type)) {
 
                if (!CollectionUtils.isEmpty(stateSettlementList)) {
                    //不计算赔偿人员,只需要确认是否安置里面是否有数据 有就算一个人
                    Map<String, StateSettlement> stringStateSettlementMap = stateSettlementList.stream().
                            collect(Collectors.toMap(StateSettlement::getStateHouseholdId, Function.identity()));
 
                    // 遍历 goodCompensationHouse
                    goodsPerson += compensationHouse.stream()
                            .filter(data -> stringStateSettlementMap.containsKey(data.getId()))
                            .count();
                    totalCompensationArea += compensationHouse.stream()
                            .filter(data -> stringStateSettlementMap.containsKey(data.getId()))
                            .mapToDouble(data -> Optional.ofNullable(stringStateSettlementMap.get(data.getId()).getExchangeArea()).orElse(0.0)) // 获取面积
                            .sum();
 
                    totalCompensationMoney += compensationHouse.stream()
                            .filter(data -> stringStateSettlementMap.containsKey(data.getId()))
                            .mapToDouble(data -> Optional.ofNullable(stringStateSettlementMap.get(data.getId()).getExchangeMoney()).orElse(0.0)) // 获取金额
                            .sum();
                }
            }
            //货币赔偿人员名单
            else if (Objects.equals(ResettlementTypeEnum.MONKEY.getValue(), type)) {
                if (!CollectionUtils.isEmpty(stateSettlementList)) {
                    //不计算赔偿人员,只需要确认是否安置里面是否有数据 有就算一个人
                    Map<String, StateSettlement> stringStateSettlementMap = stateSettlementList.stream().
                            collect(Collectors.toMap(StateSettlement::getStateHouseholdId, Function.identity()));
 
                    // 计算货币赔偿人数
                    moneyPerson += compensationHouse.stream()
                            .filter(data -> stringStateSettlementMap.containsKey(data.getId()))
                            .count();
 
                    //计算金额和面积
                    totalCompensationArea += compensationHouse.stream()
                            .filter(data -> stringStateSettlementMap.containsKey(data.getId()))
                            .mapToDouble(data -> Optional.ofNullable(stringStateSettlementMap.get(data.getId()).getSettlementArea()).orElse(0.0)) // 获取面积
                            .sum();
 
                    totalCompensationMoney += compensationHouse.stream()
                            .filter(data -> stringStateSettlementMap.containsKey(data.getId()))
                            .mapToDouble(data -> Optional.ofNullable(stringStateSettlementMap.get(data.getId()).getSettlementMoney()).orElse(0.0)) // 获取金额
                            .sum();
                }
            }
        }
        settlementSumVO.setGoodsCompensationPersons(goodsPerson);
        settlementSumVO.setMoneyCompensationPersons(moneyPerson);
        settlementSumVO.setSettlementMoney(new BigDecimal(totalCompensationMoney).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
        settlementSumVO.setSettlementArea(new BigDecimal(totalCompensationArea).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        return settlementSumVO;
    }
 
    /**
     * 项目实施明细
     * @param executionBO
     * @return
     */
    @Override
    public PageInfo<StateExecutionDetailVO> listExecution(StateExecutionBO executionBO) {
        PageUtils.startPage();
        List<StateExecutionDetailVO> list = settlementMapper.listExecutionData(executionBO);
        if (CollectionUtils.isEmpty(list)) {
            return new PageInfo<>();
        }
        PageInfo<StateExecutionDetailVO> pageInfo = new PageInfo<>(list);
        //返回的结果列表
        List<StateExecutionDetailVO> result = new ArrayList<>();
 
        List<StateExecutionDetailVO> executionDetailVOS = list.stream().filter(Objects::nonNull).collect(Collectors.toList());
 
        List<String> houseIdList = executionDetailVOS.stream()
                .map(StateExecutionDetailVO::getHouseStateId) // 获取 houseStateId
                .filter(Objects::nonNull) // 过滤掉 houseStateId 为 null 的情况
                .distinct() // 去重
                .collect(Collectors.toList());
 
        LambdaQueryWrapper<StateHouseholdOwner> householdOwnerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        householdOwnerLambdaQueryWrapper.in(StateHouseholdOwner::getStateHouseholdId, houseIdList);
        if (!com.zzg.common.utils.StringUtils.isEmpty(executionBO.getOwnerName())) {
            householdOwnerLambdaQueryWrapper.like(StateHouseholdOwner::getOwnerName, executionBO.getOwnerName());
        }
        List<StateHouseholdOwner> stateHouseholdOwners = stateHouseholdOwnerService.list(householdOwnerLambdaQueryWrapper);
 
        Map<String, List<StateHouseholdOwner>> ownerMap = stateHouseholdOwners.stream().collect(Collectors.groupingBy(StateHouseholdOwner::getStateHouseholdId));
        if (!com.zzg.common.utils.StringUtils.isEmpty(executionBO.getOwnerName())) {
            list = list.stream().filter(data -> ownerMap.containsKey(data.getHouseStateId())).collect(Collectors.toList());
        }
 
        Map<String, StateExecutionDetailVO> listMap = list.stream().collect(Collectors.toMap(StateExecutionDetailVO::getHouseStateId, Function.identity()));
 
        for (String houseId : listMap.keySet()) {
            StateExecutionDetailVO assetDetailVO = listMap.get(houseId);
            //组装名字
            if (ownerMap.containsKey(houseId)) {
                String fullName = ownerMap.get(houseId).stream().map(StateHouseholdOwner::getOwnerName).collect(Collectors.joining("|"));
                assetDetailVO.setOwnerName(fullName);
            }
            result.add(assetDetailVO);
        }
 
        LambdaQueryWrapper<StateAgreement> agreementQueryWrapper = new LambdaQueryWrapper<>();
        agreementQueryWrapper.in(StateAgreement::getStateHouseholdId, houseIdList);
        agreementQueryWrapper.isNotNull(StateAgreement::getAgreementNumber);
        List<StateAgreement> agreementList = stateAgreementMapper.selectList(agreementQueryWrapper);
        if (CollectionUtils.isEmpty(agreementList)) {
            return pageInfo;
        }
        //查询协议添加 协议签订时间
        Map<String, Map<Integer, StateAgreement>> agreementMap = agreementList.stream().collect(Collectors.groupingBy(StateAgreement::getStateHouseholdId,
                Collectors.toMap(StateAgreement::getAgreementFileType, Function.identity())));
 
        result.forEach(data -> {
            if (agreementMap.containsKey(data.getHouseStateId())) {
                Map<Integer, StateAgreement> innerAgreementMap = agreementMap.get(data.getHouseStateId());
 
                if (innerAgreementMap.containsKey(AgreementTypeEnum.STATE_AGREEMENT.getValue())) {
                    StateAgreement stateAgreement = innerAgreementMap.get(AgreementTypeEnum.STATE_AGREEMENT.getValue());
                    data.setOfficialSignedTime(stateAgreement.getSignAt());
                }
                if (innerAgreementMap.containsKey(AgreementTypeEnum.VIRTUAL_STATE_AGREEMENT.getValue())) {
                    StateAgreement virtualAgreement = innerAgreementMap.get(AgreementTypeEnum.VIRTUAL_STATE_AGREEMENT.getValue());
                    data.setVirtualSignedTime(virtualAgreement.getSignAt());
                }
 
            }
        });
        pageInfo.setList(result);
        return pageInfo;
    }
 
    /**
     * 安置详情-回显
     * @param executionB
     * @return
     */
    @Override
    public List<StateExecutionDetailVO> exportExecution(StateExecutionBO executionB) {
        if (StringUtils.isNoneBlank(executionB.getHouseStateId())) {
            String[] split = executionB.getHouseStateId().split(",");
            executionB.setHouseStateIdList(Arrays.asList(split));
        }
        List<StateExecutionDetailVO> list = settlementMapper.listExecutionData(executionB);
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<StateExecutionDetailVO> result = new ArrayList<>();
        //过滤空值
        List<StateExecutionDetailVO> executionDetailVOS = list.stream().filter(Objects::nonNull).collect(Collectors.toList());
 
        List<String> houseIdList = executionDetailVOS.stream()
                .map(StateExecutionDetailVO::getHouseStateId) // 获取 houseStateId
                .filter(Objects::nonNull) // 过滤掉 houseStateId 为 null 的情况
                .distinct() // 去重
                .collect(Collectors.toList());
 
        LambdaQueryWrapper<StateHouseholdOwner> householdOwnerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        householdOwnerLambdaQueryWrapper.in(StateHouseholdOwner::getStateHouseholdId, houseIdList);
        if (!com.zzg.common.utils.StringUtils.isEmpty(executionB.getOwnerName())) {
            householdOwnerLambdaQueryWrapper.like(StateHouseholdOwner::getOwnerName, executionB.getOwnerName());
        }
        //查询权利人
        List<StateHouseholdOwner> stateHouseholdOwners = stateHouseholdOwnerService.list(householdOwnerLambdaQueryWrapper);
 
        Map<String, List<StateHouseholdOwner>> ownerMap = stateHouseholdOwners.stream().collect(Collectors.groupingBy(StateHouseholdOwner::getStateHouseholdId));
        if (!com.zzg.common.utils.StringUtils.isEmpty(executionB.getOwnerName())) {
            list = list.stream().filter(data -> ownerMap.containsKey(data.getHouseStateId())).collect(Collectors.toList());
        }
 
        Map<String, StateExecutionDetailVO> listMap = list.stream().collect(Collectors.toMap(StateExecutionDetailVO::getHouseStateId, Function.identity()));
 
        for (String houseId : listMap.keySet()) {
            StateExecutionDetailVO assetDetailVO = listMap.get(houseId);
            //组装名字
            if (ownerMap.containsKey(houseId)) {
                String fullName = ownerMap.get(houseId).stream().map(StateHouseholdOwner::getOwnerName).collect(Collectors.joining("|"));
                assetDetailVO.setOwnerName(fullName);
            }
            result.add(assetDetailVO);
        }
 
        LambdaQueryWrapper<StateAgreement> agreementQueryWrapper = new LambdaQueryWrapper<>();
        agreementQueryWrapper.in(StateAgreement::getStateHouseholdId, houseIdList);
        agreementQueryWrapper.isNotNull(StateAgreement::getAgreementNumber);
        //查询协议
        List<StateAgreement> agreementList = stateAgreementMapper.selectList(agreementQueryWrapper);
        if (CollectionUtils.isEmpty(agreementList)) {
            return new ArrayList<>(result);
        }
        //查询协议添加 协议签订时间
        Map<String, Map<Integer, StateAgreement>> agreementMap = agreementList.stream().collect(Collectors.groupingBy(StateAgreement::getStateHouseholdId,
                Collectors.toMap(StateAgreement::getAgreementFileType, Function.identity())));
 
        result.forEach(data -> {
            if (agreementMap.containsKey(data.getHouseStateId())) {
                Map<Integer, StateAgreement> innerAgreementMap = agreementMap.get(data.getHouseStateId());
 
                if (innerAgreementMap.containsKey(AgreementTypeEnum.STATE_AGREEMENT.getValue())) {
                    StateAgreement stateAgreement = innerAgreementMap.get(AgreementTypeEnum.STATE_AGREEMENT.getValue());
                    //正式签字时间
                    data.setOfficialSignedTime(stateAgreement.getSignAt());
                }
                if (innerAgreementMap.containsKey(AgreementTypeEnum.VIRTUAL_STATE_AGREEMENT.getValue())) {
                    StateAgreement virtualAgreement = innerAgreementMap.get(AgreementTypeEnum.VIRTUAL_STATE_AGREEMENT.getValue());
                    //模拟签字时间
                    data.setVirtualSignedTime(virtualAgreement.getSignAt());
                }
 
            }
        });
        return result;
    }
 
    /**
     * 给项目展示使用
     * @param projectIdList
     * @param projectStreet
     * @return
     */
    @Override
    public Map<String, Map<Integer, ProjectExecutionSumVO>> listProjectExecutionByProjectId(List<String> projectIdList, String projectStreet) {
 
        if (CollectionUtils.isEmpty(projectIdList)) {
            return new HashMap<>();
        }
 
        //查询项目
        LambdaQueryWrapper<StateProject> stateProjectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        stateProjectLambdaQueryWrapper.in(StateProject::getId, projectIdList);
        List<StateProject> stateProjects = stateProjectMapper.selectList(stateProjectLambdaQueryWrapper);
        if (CollectionUtils.isEmpty(stateProjects)) {
            return new HashMap<>();
        }
 
        //查询房产
        LambdaQueryWrapper<StateHousehold> householdQueryWrapper = new LambdaQueryWrapper<>();
        householdQueryWrapper.in(StateHousehold::getStateProjectId, projectIdList);
        if (StringUtils.isNoneBlank(projectStreet)) {
            householdQueryWrapper.like(StateHousehold::getBelongingStreetTown, projectStreet);
        }
        if (StringUtils.isNoneBlank(projectStreet)) {
            householdQueryWrapper.like(StateHousehold::getBelongingStreetTown, projectStreet);
        }
        householdQueryWrapper.eq(StateHousehold::getDelFlag, DeleteFlagEnum.NOT_DELETED.getKey());
        List<StateHousehold> households = stateHouseholdMapper.selectList(householdQueryWrapper);
        if (CollectionUtils.isEmpty(households)) {
            return new HashMap<>();
        }
        //根据房产信息查询协议/安置信息
        Map<String, Map<Integer, ProjectExecutionSumVO>> result = new HashMap<>();
 
        Map<String, List<StateHousehold>> householdMap = households.stream().collect(Collectors.groupingBy(StateHousehold::getStateProjectId));
        //废弃代码
        //List<String> houseIdList = households.stream().map(StateHousehold::getId).collect(Collectors.toList());
        List<String> acceptHoustIdList = households.stream().filter(e ->
                Objects.nonNull(e.getAgreementStatus())
        ).map(StateHousehold::getId).collect(Collectors.toList());
 
        List<StateAgreement> stateAgreementList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(acceptHoustIdList)) {
            //协议
            LambdaQueryWrapper<StateAgreement> stateAgreementQueryWrapper = new LambdaQueryWrapper<>();
            stateAgreementQueryWrapper.in(StateAgreement::getStateHouseholdId, acceptHoustIdList);
            //只需要模拟和正式合同
            stateAgreementQueryWrapper.in(StateAgreement::getAgreementFileType,
                    Arrays.asList(AgreementTypeEnum.STATE_AGREEMENT.getValue(), AgreementTypeEnum.VIRTUAL_STATE_AGREEMENT.getValue()));
            stateAgreementQueryWrapper.isNotNull(StateAgreement::getAgreementNumber);
//        stateAgreementQueryWrapper.isNotNull(StateAgreement::getAuditStatus);
            stateAgreementList = stateAgreementMapper.selectList(stateAgreementQueryWrapper);
        }
        //正式合同数据
        List<StateAgreement> stateAgreements = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(stateAgreementList)) {
            stateAgreements = stateAgreementList.stream()
                    .filter(data -> Objects.nonNull(data.getAgreementFileType())
                            && Objects.equals(data.getAgreementFileType(), AgreementTypeEnum.STATE_AGREEMENT.getValue()))
                    .collect(Collectors.toList());
        }
        //模拟合同数据
        List<StateAgreement> virtualAgreement = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(stateAgreements)) {
            List<StateAgreement> finalStateAgreements = stateAgreements;
            virtualAgreement = stateAgreementList.stream().filter(data -> !finalStateAgreements.contains(data)).collect(Collectors.toList());
        }
 
        //项目资金
        LambdaQueryWrapper<StateAsset> stateAssetQueryWrapper = new LambdaQueryWrapper<>();
        stateAssetQueryWrapper.in(StateAsset::getStateProjectId, projectIdList);
        stateAssetQueryWrapper.eq(StateAsset::getDelFlag, DeleteFlagEnum.NOT_DELETED.getKey());
        List<StateAsset> assetList = stateAssetMapper.selectList(stateAssetQueryWrapper);
 
        //多个
        Map<String, List<StateAsset>> stateAssetMap = assetList.stream()
                .collect(Collectors.groupingBy(StateAsset::getStateProjectId, Collectors.toList()));
 
        // 需要处理内部map 以协议的type为key type放进了 ProjectExecutionSumVO直接后面转成map就行了,比率直接查数据 只有有数据必然是签订的 没有数据就没签订的
        for (String data : projectIdList) {
            if (householdMap.containsKey(data)) {
                ProjectExecutionSumVO projectStateExecutionSumVO = new ProjectExecutionSumVO();
                ProjectExecutionSumVO projectVirtualExecutionSumVO = new ProjectExecutionSumVO();
                List<StateHousehold> innerHouseList = householdMap.get(data);
                if (CollectionUtils.isEmpty(innerHouseList)) {
                    continue;
                }
                //获取调查评估状态
                Map<Integer, Long> countMap = innerHouseList.stream()
                        .filter(item -> item.getStatus() != null)
                        .map(StateHousehold::getAppendData) // 假设这是获取 appendData 的方法
                        .filter(Objects::nonNull) // 确保不为 null
                        .map(jsonData -> {
                            try {
                                return JSON.parseObject(jsonData); // 解析 JSON 数据
                            } catch (Exception e) {
                                return null; // 解析失败时返回 null
                            }
                        })
                        .filter(Objects::nonNull) // 过滤解析失败的对象
                        .filter(jsonObject -> jsonObject.containsKey("surveyResultRegistrationBO")) // 确保包含 surveyResultRegistrationBO
                        .collect(Collectors.groupingBy(
                                jsonObject -> {
                                    JSONObject surveyResult = jsonObject.getJSONObject("surveyResultRegistrationBO");
                                    // 判空检查,确保 surveyResult 和 isSign 存在
                                    if (Objects.nonNull(surveyResult) && (surveyResult.containsKey("isSignedVirtualAgreement")
                                            && surveyResult.getString("isSignedVirtualAgreement").equals("1")
//                                            || surveyResult.containsKey("isSignedVirtualAgreement")
//                                            || surveyResult.containsKey("isSignOfficialAgreement"))
//                                            || surveyResult.containsKey("isSignStateAgreement")
                                    )) {
                                        return surveyResult.getInteger("isSignedVirtualAgreement");
                                    }
                                    return 0; // 使用默认值或处理逻辑
                                },
                                Collectors.counting() // 计数
                        ));
 
                // 获取 isSign 为 1 和 0 的数量
                long searchedPersons = countMap.getOrDefault(1, 0L);
 
                long notSearchedPersons = countMap.getOrDefault(0, 0L);
 
                //添加appendData为null的数据
                notSearchedPersons += innerHouseList.stream().filter(innerHouse -> Objects.isNull(innerHouse.getAppendData())).count();
                //房产id
                List<String> innerHouseId = innerHouseList.stream().map(StateHousehold::getId).collect(Collectors.toList());
 
                //计算产权置换/货币置换人数
                Map<Integer, List<StateHousehold>> compensationTypeHouse = innerHouseList.
                        stream().filter(innerHouse -> Objects.nonNull(innerHouse.getCompensationType()))
                        .collect(Collectors.groupingBy(StateHousehold::getCompensationType));
                if (compensationTypeHouse.containsKey(CompensationCategoryEnum.MONEY_COMPENSATION_1.getCode())) {
                    projectStateExecutionSumVO.setMoneyCompensationPersons((CollectionUtils.isNotEmpty(compensationTypeHouse)
                            ? (long) compensationTypeHouse.get(CompensationCategoryEnum.MONEY_COMPENSATION_1.getCode()).size()
                            : 0L));
 
                    projectVirtualExecutionSumVO.setMoneyCompensationPersons((CollectionUtils.isNotEmpty(compensationTypeHouse)
                            ? (long) compensationTypeHouse.get(CompensationCategoryEnum.MONEY_COMPENSATION_1.getCode()).size()
                            : 0L));
                }
                if (compensationTypeHouse.containsKey(CompensationCategoryEnum.PROPERTY_SWAP_2.getCode())) {
                    projectStateExecutionSumVO.setGoodsCompensationPersons((CollectionUtils.isNotEmpty(compensationTypeHouse)
                            ? (long) compensationTypeHouse.get(CompensationCategoryEnum.PROPERTY_SWAP_2.getCode()).size()
                            : 0L));
 
                    projectVirtualExecutionSumVO.setGoodsCompensationPersons((CollectionUtils.isNotEmpty(compensationTypeHouse)
                            ? (long) compensationTypeHouse.get(CompensationCategoryEnum.PROPERTY_SWAP_2.getCode()).size()
                            : 0L));
                }
 
                //设置项目预算金额
                if (stateAssetMap.containsKey(data)) {
                    BigDecimal virtualMoney = stateAssetMap.get(data).stream().map(StateAsset::getVirtualMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
                    projectStateExecutionSumVO.setVirtualMoney(virtualMoney);
                    projectVirtualExecutionSumVO.setVirtualMoney(virtualMoney);
                }else{
                    projectStateExecutionSumVO.setVirtualMoney(BigDecimal.ZERO.setScale(4,BigDecimal.ROUND_HALF_UP));
                    projectVirtualExecutionSumVO.setVirtualMoney(BigDecimal.ZERO.setScale(4,BigDecimal.ROUND_HALF_UP));
 
                }
 
 
                //模拟合同金额
                BigDecimal virtualMoney = virtualAgreement.stream()
                        .filter(agreement -> innerHouseId.contains(agreement.getStateHouseholdId()) && Objects.nonNull(agreement.getMoney()))
                        .map(agreement -> BigDecimal.valueOf(agreement.getMoney())) // 提取 money 值并转换为 BigDecimal
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
 
                // 正式合同金额
                BigDecimal stateMoney = stateAgreements.stream()
                        .filter(agreement -> innerHouseId.contains(agreement.getStateHouseholdId()) && Objects.nonNull(agreement.getMoney()))
                        .map(agreement -> BigDecimal.valueOf(agreement.getMoney())) // 提取 money 值并转换为 BigDecimal
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
 
 
                //模拟合同设置模拟金额
                projectVirtualExecutionSumVO.setAgreementMoney(virtualMoney.setScale(4, BigDecimal.ROUND_HALF_UP));
 
                //正式合同设置正式金额
                projectStateExecutionSumVO.setAgreementMoney(stateMoney.setScale(4, BigDecimal.ROUND_HALF_UP));
 
                List<String> stateAgreementIdList = stateAgreements.stream()
                        .map(StateAgreement::getStateHouseholdId)
                        .filter(innerHouseId::contains).collect(Collectors.toList());
 
                List<String> virtualAgreementIdList = virtualAgreement.stream()
                        .map(StateAgreement::getStateHouseholdId)
                        .filter(innerHouseId::contains).collect(Collectors.toList());
 
 
                //查询正式合同比例
                long signedStatePerson = stateAgreements.stream()
                        .filter(stateSettlement -> innerHouseId.contains(stateSettlement.getStateHouseholdId())
                                && stateAgreementIdList.contains(stateSettlement.getStateHouseholdId()))
                        .count();
 
                long notSignedStatePerson = innerHouseList.size() - signedStatePerson;
 
                //对于项目阶段而言 模拟阶段只有模拟协议 正式阶段只有正式协议
                //模拟阶段签字人数 项目阶段是唯一的 人数只需要比对签字人数就行 未签字是 houseSize - 签字人数
 
                //查询虚拟合同签字人数
                long signedVirtualPerson = virtualAgreement.stream()
                        .filter(stateSettlement -> innerHouseId.contains(stateSettlement.getStateHouseholdId())
                                && virtualAgreementIdList.contains(stateSettlement.getStateHouseholdId()))
                        .count();
 
                long notSignedVirtualPerson = innerHouseList.size() - signedVirtualPerson;
                //计算正式签约的比例
                appendData(searchedPersons, notSearchedPersons, innerHouseId, signedStatePerson, notSignedStatePerson, projectStateExecutionSumVO);
 
                //计算模拟签约的比例
                appendData(searchedPersons, notSearchedPersons, innerHouseId, signedVirtualPerson, notSignedVirtualPerson, projectVirtualExecutionSumVO);
 
                Map<Integer, ProjectExecutionSumVO> projectExecutionSumVOMap = new HashMap<>();
                projectExecutionSumVOMap.put(AgreementTypeEnum.STATE_AGREEMENT.getValue(), projectStateExecutionSumVO);
                projectExecutionSumVOMap.put(AgreementTypeEnum.VIRTUAL_STATE_AGREEMENT.getValue(), projectVirtualExecutionSumVO);
                result.put(data, projectExecutionSumVOMap);
            }
        }
        return result;
    }
 
    //生成批次名字逻辑 根据当前项目id查询当前项目有多少已经审核的数据 然后批次名字+1
 
    /**
     * 1.compensationType为null 直接显示库总数据
     * 2.compensationType不为null 需要判断是否有数据
     *
     * @param projectId
     * @param componsationType
     * @return
     */
    @Override
    public String generateBatchName(String projectId, String componsationType) {
        StateProject stateProject = stateProjectMapper.selectById(projectId);
        if (Objects.isNull(stateProject)) {
            return "";
        }
        int batchNum = 1;
 
 
        List<StateSettlement> stateSettlementList = null;
        //compensationType第一次查询直接已提交审核的下一次提交的批次
        if (ObjectUtil.isEmpty(componsationType) || componsationType.equals("null")) {
            //查询已提交审核的正常下一批次
            return searchLastBatchName(stateProject.getId());
        } else {
            //1.先查安置情况下是否有未提交的数据,
            //有数据 compensationType和当前选择一致则回显,不一致则需要用提交审核的批次+1
            //无数据 正常显示已提交的下一批次
            LambdaQueryWrapper<StateHousehold> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(StateHousehold::getStateProjectId, stateProject.getId());
            lambdaQueryWrapper.eq(StateHousehold::getCompensationType, NumberUtil.parseInt(componsationType));
            List<StateHousehold> stateHouseholds = stateHouseholdMapper.selectList(lambdaQueryWrapper);
            if (CollectionUtils.isEmpty(stateHouseholds)) {
                return "第" + batchNum + "批次";
            }
            Map<String, StateHousehold> stateHouseholdMap = stateHouseholds.stream().collect(Collectors.toMap(StateHousehold::getId, Function.identity()));
            LambdaQueryWrapper<StateSettlement> stateSettlementLambdaQueryWrapper = new LambdaQueryWrapper<>();
            stateSettlementLambdaQueryWrapper.in(StateSettlement::getStateHouseholdId,
                    stateHouseholds.stream().map(StateHousehold::getId).collect(Collectors.toList()));
            stateSettlementLambdaQueryWrapper.isNull(StateSettlement::getAuditStatus);
            stateSettlementLambdaQueryWrapper.orderByAsc(StateSettlement::getSettleName);
            //查询安置情况
            stateSettlementList = this.list(stateSettlementLambdaQueryWrapper);
            if (ObjectUtil.isNotEmpty(stateSettlementList)) {
                StateHousehold stateHousehold = stateHouseholdMap.get(stateSettlementList.get(0).getStateHouseholdId());
                if (ObjectUtil.isNotEmpty(stateHousehold) && stateHousehold.getCompensationType().toString().equals(componsationType)) {
                    //有数据返回未提交的批次名称
                    return stateSettlementList.get(0).getSettleName();
                } else {
                    //查询已提交审核的正常下一批次
                    return searchLastBatchName(stateProject.getId());
                }
            } else {
                return searchLastBatchName(stateProject.getId());
            }
        }
    }
 
    /**
     * 查询已审核完成的下一次提交的批次
     *
     * @param projectId
     * @return
     */
    public String searchLastBatchName(String projectId) {
        Integer batchNum = 1;
        LambdaQueryWrapper<StateHousehold> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(StateHousehold::getStateProjectId, projectId);
        List<StateHousehold> stateHouseholds = stateHouseholdMapper.selectList(lambdaQueryWrapper);
        if (CollectionUtils.isEmpty(stateHouseholds)) {
            return "第" + batchNum + "批次";
        }
        LambdaQueryWrapper<StateSettlement> stateSettlementLambdaQueryWrapper = new LambdaQueryWrapper<>();
        stateSettlementLambdaQueryWrapper.in(StateSettlement::getStateHouseholdId,
                stateHouseholds.stream().map(StateHousehold::getId).collect(Collectors.toList()));
//        stateSettlementLambdaQueryWrapper.isNotNull(StateSettlement::getAuditStatus);
        stateSettlementLambdaQueryWrapper.orderByAsc(StateSettlement::getSettleName);
        List<StateSettlement> stateSettlementList = this.list(stateSettlementLambdaQueryWrapper);
 
        if (ObjectUtil.isNotEmpty(stateSettlementList)) {
            stateSettlementList.sort(Comparator.comparing(BaseEntity::getCreateTime));
            List<String> batchNameSet = stateSettlementList.stream().filter(Objects::nonNull)
                    .map(StateSettlement::getSettleName).distinct().collect(Collectors.toList());
            String latestBatchName = batchNameSet.get(batchNameSet.size() - 1);
            batchNum += extractNumber(latestBatchName);
        }
        return "第" + batchNum + "批次";
    }
 
    /**
     * 当前项目批次列表
     * @param projectId
     * @return
     */
    @Override
    public List<String> listBatchName(String projectId) {
        if (StringUtils.isEmpty(projectId)) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<StateHousehold> stateHouseholdLambdaQueryWrapper = new LambdaQueryWrapper<>();
        stateHouseholdLambdaQueryWrapper.eq(StateHousehold::getStateProjectId, projectId);
        List<StateHousehold> stateHouseholds = stateHouseholdMapper.selectList(stateHouseholdLambdaQueryWrapper);
 
        if (CollectionUtils.isEmpty(stateHouseholds)) {
            return new ArrayList<>();
        }
        List<String> houseId = stateHouseholds.stream().map(StateHousehold::getId).distinct().collect(Collectors.toList());
 
        LambdaQueryWrapper<StateSettlement> stateSettlementLambdaQueryWrapper = new LambdaQueryWrapper<>();
        stateSettlementLambdaQueryWrapper.in(StateSettlement::getStateHouseholdId, houseId);
        List<StateSettlement> stateSettlementList = this.list(stateSettlementLambdaQueryWrapper);
        stateSettlementList.sort(Comparator.comparing(BaseEntity::getCreateTime));
        return stateSettlementList.stream().map(StateSettlement::getSettleName).distinct().collect(Collectors.toList());
    }
 
    /**
     * 安置情况保存
     * @param stateSettlement
     */
    @Override
    @Transactional
    public void saveOrUpdateSettlement(List<StateSettlement> stateSettlement) {
        if (CollectionUtils.isEmpty(stateSettlement)) {
            throw new GlobalException("数据不能为空");
        }
        //新增的
        List<StateSettlement> newAddList = stateSettlement.stream().filter(e -> Objects.isNull(e.getId())).collect(Collectors.toList());
        //编辑的
        List<StateSettlement> oldUpdateList = stateSettlement.stream().filter(e -> Objects.nonNull(e.getId())).collect(Collectors.toList());
 
 
        List<String> newAddHouseId = newAddList.stream().map(StateSettlement::getStateHouseholdId).collect(Collectors.toList());
 
        List<StateHousehold> stateHouseholds = stateHouseholdMapper.selectBatchIds(stateSettlement.stream().map(StateSettlement::getStateHouseholdId).collect(Collectors.toList()));
 
        Map<String, Double> areaMap = stateHouseholds.stream().collect(Collectors.toMap(StateHousehold::getId, StateHousehold::getHouseHoldArea));
        //对于货币补偿的结算面积
        stateSettlement.forEach(data -> {
            if (Objects.nonNull(data.getSettlementMoney())) {
                data.setSettlementArea(areaMap.get(data.getStateHouseholdId()));
            }
        });
        //全为编辑
        if (CollectionUtils.isEmpty(newAddHouseId)) {
            this.saveOrUpdateBatch(oldUpdateList);
            return;
        }
 
        //根据批次名字与项目id进行筛选进行筛选不允许批次名字重复添加
        String batchName = stateSettlement.get(0).getSettleName();
        String currentHouseId = stateSettlement.get(0).getStateHouseholdId();
        StateHousehold stateHousehold = stateHouseholdMapper.selectById(currentHouseId);
        String projectId = stateHousehold.getStateProjectId();
 
        List<String> currentProjectBatchName = this.listBatchName(projectId);
        if (CollectionUtils.isNotEmpty(currentProjectBatchName)
                && !Objects.equals(currentProjectBatchName.get(currentProjectBatchName.size() - 1), batchName)
        ) {
            if (CollectionUtils.isNotEmpty(currentProjectBatchName) && currentProjectBatchName.contains(batchName)) {
                throw new GlobalException("该批次数据已经存在,清重新输入批次 或者 当前有未提交的数据,请先删除在从新提交");
            }
        }
 
        if (SecurityUtils.getLoginUser().getUser().getDept() != null &&
                SecurityUtils.getLoginUser().getUser().getDept().getDeptName() != null) {
            stateSettlement.forEach(data -> data.setSettleDepartment(SecurityUtils.getLoginUser().getUser().getDept().getDeptName()));
        }
 
        String taskId = UUID.randomUUID().toString().replace("-", "");
        Optional<String> first = oldUpdateList.stream().map(StateSettlement::getTaskId).findFirst();
        if (first.isPresent()) {
            if (com.zzg.common.utils.StringUtils.isNotBlank(first.get())) {
                taskId = first.get();
            }
        }
        LambdaQueryWrapper<StateSettlement> lqw = new LambdaQueryWrapper<>();
        lqw.in(StateSettlement::getStateHouseholdId, newAddHouseId).ne(StateSettlement::getDelFlag, DeleteFlagEnum.DELETED.getKey());
        List<StateSettlement> list = this.list(lqw);
        //新增
        if (CollectionUtils.isEmpty(list)) {
 
            //查询当前批次是否存在已经拒绝的,如果有则代表是 审核失败编辑页面新增的情况,这里需要吧审核状态设置为已拒绝 同一批次,审核状态统一,要么全为接收要么全为退回
            LambdaQueryWrapper<StateHousehold> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StateHousehold::getStateProjectId, projectId);
            List<StateHousehold> allHousehold = stateHouseholdMapper.selectList(queryWrapper);
            if (ObjectUtil.isNotEmpty(allHousehold)) {
                List<String> hoursIds = allHousehold.stream().map(StateHousehold::getId).collect(Collectors.toList());
                LambdaQueryWrapper<StateSettlement> stateSettlementLambdaQueryWrapper = new LambdaQueryWrapper<>();
                stateSettlementLambdaQueryWrapper.eq(StateSettlement::getSettleName, batchName);
                stateSettlementLambdaQueryWrapper.eq(StateSettlement::getAuditStatus, SubmitStatusEnum.REJECT.getValue());
                stateSettlementLambdaQueryWrapper.in(StateSettlement::getStateHouseholdId, hoursIds);
                stateSettlementLambdaQueryWrapper.ne(StateSettlement::getDelFlag, DeleteFlagEnum.DELETED.getKey());
                if (this.stateSettlementMapper.exists(stateSettlementLambdaQueryWrapper)) {
                    for (StateSettlement settlement : stateSettlement) {
                        settlement.setAuditStatus(SubmitStatusEnum.REJECT.getValue());
                    }
                }
            }
            this.saveOrUpdateBatch(stateSettlement);
        } else {
            List<String> houseIdInDB = list.stream().map(StateSettlement::getStateHouseholdId).collect(Collectors.toList());
            List<StateSettlement> newList = stateSettlement.stream().filter(e -> !houseIdInDB.contains(e.getStateHouseholdId())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(newList)) {
                throw new GlobalException("所选的数据都已被选择");
            } else {
                for (StateSettlement e : newList) {
                    e.setTaskId(taskId);
                }
                newList.addAll(oldUpdateList);
                this.saveOrUpdateBatch(newList);
            }
        }
    }
 
    /**
     * 新增安置情况 - 提交审核
     * @param settlementIds
     */
    @Override
    @Transactional
    public void workflowSubmit(List<String> settlementIds) {
        List<StateSettlement> stateSettlementList = listByIds(settlementIds);
 
        Optional<String> houseId = stateSettlementList.stream().map(StateSettlement::getStateHouseholdId).filter(Objects::nonNull).findFirst();
        if (houseId.isPresent()) {
            String houseIdData = houseId.get();
 
            StateHousehold stateHousehold = stateHouseholdMapper.selectById(houseIdData);
 
            String projectId = stateHousehold.getStateProjectId();
            if (Objects.isNull(projectId)) {
                return;
            }
            StateProject stateProject = stateProjectMapper.selectById(projectId);
 
            ProcessStartBO processStartBO = new ProcessStartBO();
            processStartBO.setCategory(String.valueOf(ProcessCategoryEnum.CATEGORY7.getValue()));
            processStartBO.setName(stateProject.getProjectName());
            processStartBO.setModuleName(ProcessCategoryEnum.CATEGORY7.getText());
            String remake = String.format("【镇/街】:%s,【征收实施单位】:%s,【批次名称】:%s,【安置类型】:%s",
                    stateProject.getStreet(),
                    stateProject.getDepartment(),
                    stateSettlementList.stream().map(StateSettlement::getSettleName).distinct().collect(Collectors.joining(",")),
                    CompensationCategoryEnum.getDescription(stateHousehold.getCompensationType()));
            processStartBO.setRemark(remake);
            Map<String, Object> variable = new HashMap<>();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", settlementIds);
            variable.put("settleId", jsonObject.toJSONString());
            variable.put("projectId", stateProject.getId());
            variable.put("batchName", stateSettlementList.get(0).getSettleName());
            variable.put("compensationType", stateHousehold.getCompensationType());
            processStartBO.setVariable(variable);
            processTemplateService.start(processStartBO);
            saveOrUpdateBatch(stateSettlementList);
        }
    }
 
    @Override
    public void updateSettleStatus(List<String> recordId, Integer status) {
        LambdaUpdateWrapper<StateSettlement> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(StateSettlement::getId, recordId)
                .set(StateSettlement::getAuditStatus, status);
        this.update(updateWrapper);
    }
 
    //     MONEY_COMPENSATION_1(1, "货币补偿", "平方米/元"),
    //    PROPERTY_SWAP_2(2, "产权置换", "平方米/元"),
    @Override
    public void stateSettlementImport(ImportSettlementBO importSettlementBO) throws IOException {
        if (2 == importSettlementBO.getCompensationType()) {
            importProperty(importSettlementBO);
        } else if (1 == importSettlementBO.getCompensationType()) {
            importCurrency(importSettlementBO);
        }
    }
 
    /**
     * 安置情况删除
     * @param id
     */
    @Override
    public void deleteSettlement(String id) {
        stateSettlementMapper.deleteSettlement(id);
    }
 
    public static List<Map<Integer, String>> readExcelHead(File file) {
        // 构建读取器
        ExcelReaderSheetBuilder excelReaderSheetBuilder = EasyExcel.read(file)
                .sheet(0)
                .headRowNumber(0); // 设置表头的行数为1
        // 返回表头数据
        return excelReaderSheetBuilder.doReadSync();
    }
 
    private void importProperty(ImportSettlementBO importSettlementBO) throws IOException {
        LambdaQueryWrapper<StateHousehold> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StateHousehold::getStateProjectId, importSettlementBO.getProjectId());
        List<StateHousehold> list = stateHouseholdMapper.selectList(lqw);
        if (CollectionUtils.isEmpty(list)) {
            throw new GlobalException("不存在房产");
        }
        List<Map<Integer, String>> maps = readExcelHead(FileUtil.convertToFile(importSettlementBO.getFile()));
        if (!Objects.equals(maps.get(0).get(0), "*不动产权证号")
                || !Objects.equals(maps.get(0).get(1), "*置换后镇街")
                || !Objects.equals(maps.get(0).get(2), "*置换后坐落")
                || !Objects.equals(maps.get(0).get(3), "*置换后房屋面积")
                || !Objects.equals(maps.get(0).get(4), "*置换后房屋价值")
                || !Objects.equals(maps.get(0).get(5), "*付款时间")
                || !Objects.equals(maps.get(0).get(6), "备注")
        ) {
            throw new GlobalException("Excel表头格式不对");
        }
        List<ImportSettlementTemplatePropertyVO> dataList;
        try {
            dataList = EasyExcelFactory.read(FileUtil.convertToFile(importSettlementBO.getFile()))
                    .head(ImportSettlementTemplatePropertyVO.class)
                    .sheet()
                    .doReadSync();
        } catch (IOException e) {
            throw new GlobalException("读取Excel文件失败");
        }
        if (CollectionUtils.isEmpty(dataList)) {
            throw new GlobalException("未解析出数据");
        }
        List<String> identifiersInDB = list.stream()
                .map(StateHousehold::getRealEstateCertificateNumber)
                .collect(Collectors.toList());
 
        List<ImportSettlementTemplatePropertyVO> errorDateList = dataList.stream()
                .filter(obj -> !identifiersInDB.contains(obj.getRealEstateCertificateNumber()))
                .collect(Collectors.toList());
 
        if (!CollectionUtils.isEmpty(errorDateList)) {
            String error = errorDateList.stream().map(ImportSettlementTemplatePropertyVO::getRealEstateCertificateNumber).collect(Collectors.joining(","));
            throw new GlobalException(String.format("这些不动产号未存在:%s", error));
        }
 
 
        Map<String, StateHousehold> listMap = list.stream()
                .collect(Collectors.toMap(StateHousehold::getRealEstateCertificateNumber, x -> x));
        dataList.forEach(e -> {
            StateHousehold matchingObject = listMap.get(e.getRealEstateCertificateNumber());
            if (matchingObject != null) {
                if (!Objects.equals(matchingObject.getCompensationType(), importSettlementBO.getCompensationType())) {
                    errorDateList.add(e);
                }
            }
        });
 
        if (!CollectionUtils.isEmpty(errorDateList)) {
            String error = errorDateList.stream().map(ImportSettlementTemplatePropertyVO::getRealEstateCertificateNumber).collect(Collectors.joining(","));
            throw new GlobalException(String.format("这些不动产号安置类型错误:%s", error));
        }
 
        Map<String, StateHousehold> stateHouseholdMap = list.stream().collect(Collectors.toMap(StateHousehold::getRealEstateCertificateNumber, Function.identity()));
        dataList.forEach(e -> {
            StateHousehold stateHousehold = stateHouseholdMap.get(e.getRealEstateCertificateNumber());
            if (Objects.nonNull(stateHousehold)) {
                e.setStateHouseholdId(stateHousehold.getId());
            }
        });
        List<StateSettlement> stateSettlementsInDb = settlementMapper.selectList(new LambdaQueryWrapper<StateSettlement>()
                .in(StateSettlement::getSettleName, importSettlementBO.getSettleName()));
 
        List<String> settlementHouseIdInDB = stateSettlementsInDb.stream()
                .map(StateSettlement::getStateHouseholdId)
                .collect(Collectors.toList());
        List<ImportSettlementTemplatePropertyVO> errorList = dataList.stream()
                .filter(obj -> (settlementHouseIdInDB.contains(obj.getStateHouseholdId()))).collect(Collectors.toList());
 
        if (!CollectionUtils.isEmpty(errorList)) {
            String error = errorList.stream().map(ImportSettlementTemplatePropertyVO::getRealEstateCertificateNumber).collect(Collectors.joining(","));
            throw new GlobalException(String.format("这些不动产号已导入:%s", error));
        }
 
        List<StateSettlement> stateSettlement = StateProjectConvert.INSTANCE.templatePropertyVOToEntity(dataList);
 
        LambdaQueryWrapper<StateSettlement> stateSettlementLQW = new LambdaQueryWrapper<>();
        stateSettlementLQW.eq(StateSettlement::getSettleName, importSettlementBO.getSettleName());
        List<StateSettlement> list1 = list(stateSettlementLQW);
        String taskId = UUID.randomUUID().toString().replace("-", "");
        Integer auditStatus = null;
        if (!CollectionUtils.isEmpty(list1)) {
            StateSettlement stateSettlementInDb = list1.stream().filter(Objects::nonNull).findFirst().get();
            if (com.zzg.common.utils.StringUtils.isNotBlank(stateSettlementInDb.getTaskId())) {
                taskId = stateSettlementInDb.getTaskId();
                if (ObjectUtil.isNotEmpty(stateSettlementInDb.getAuditStatus())) {
                    auditStatus = stateSettlementInDb.getAuditStatus();
                }
            }
        }
 
 
        for (StateSettlement e : stateSettlement) {
            e.setSettleName(importSettlementBO.getSettleName());
            e.setTaskId(taskId);
            if (ObjectUtil.isNotEmpty(auditStatus)) {
                e.setAuditStatus(auditStatus);
            }
        }
 
        saveOrUpdateBatch(stateSettlement);
    }
 
    private void importCurrency(ImportSettlementBO importSettlementBO) throws IOException {
        LambdaQueryWrapper<StateHousehold> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StateHousehold::getStateProjectId, importSettlementBO.getProjectId());
        List<StateHousehold> list = stateHouseholdMapper.selectList(lqw);
 
        List<StateSettlement> stateSettlementsInDb = settlementMapper.selectList(new LambdaQueryWrapper<StateSettlement>()
                .in(StateSettlement::getSettleName, importSettlementBO.getSettleName()));
        if (CollectionUtils.isEmpty(list)) {
            throw new GlobalException("不存在房产");
        }
        List<Map<Integer, String>> maps = readExcelHead(FileUtil.convertToFile(importSettlementBO.getFile()));
        if (!Objects.equals(maps.get(0).get(0), "*不动产权证号")
                || !Objects.equals(maps.get(0).get(1), "*结算金额")
                || !Objects.equals(maps.get(0).get(2), "*付款时间")
                || !Objects.equals(maps.get(0).get(3), "备注")
        ) {
            throw new GlobalException("Excel表头格式不对");
        }
 
        List<ImportSettlementTemplateCurrencyVO> dataList;
        try {
            dataList = EasyExcelFactory.read(FileUtil.convertToFile(importSettlementBO.getFile()))
                    .head(ImportSettlementTemplateCurrencyVO.class)
                    .sheet()
                    .doReadSync();
        } catch (IOException e) {
            throw new GlobalException("读取Excel文件失败");
        }
        if (CollectionUtils.isEmpty(dataList)) {
            throw new GlobalException("未解析出数据");
        }
        List<String> identifiersInDB = list.stream()
                .map(StateHousehold::getRealEstateCertificateNumber)
                .collect(Collectors.toList());
        List<ImportSettlementTemplateCurrencyVO> errorDateList = dataList.stream()
                .filter(obj -> (!identifiersInDB.contains(obj.getRealEstateCertificateNumber()))).collect(Collectors.toList());
 
        if (!CollectionUtils.isEmpty(errorDateList)) {
            String error = errorDateList.stream().map(ImportSettlementTemplateCurrencyVO::getRealEstateCertificateNumber).collect(Collectors.joining(","));
            throw new GlobalException(String.format("这些不动产号未存在:%s", error));
        }
 
 
        Map<String, StateHousehold> listMap = list.stream()
                .collect(Collectors.toMap(StateHousehold::getRealEstateCertificateNumber, x -> x));
        dataList.forEach(e -> {
            StateHousehold matchingObject = listMap.get(e.getRealEstateCertificateNumber());
            if (matchingObject != null) {
                if (!Objects.equals(matchingObject.getCompensationType(), importSettlementBO.getCompensationType())) {
                    errorDateList.add(e);
                }
            }
        });
 
        if (!CollectionUtils.isEmpty(errorDateList)) {
            String error = errorDateList.stream().map(ImportSettlementTemplateCurrencyVO::getRealEstateCertificateNumber).collect(Collectors.joining(","));
            throw new GlobalException(String.format("这些不动产号安置类型错误:%s", error));
        }
 
        Map<String, StateHousehold> stateHouseholdMap = list.stream().collect(Collectors.toMap(StateHousehold::getRealEstateCertificateNumber, Function.identity()));
        dataList.forEach(e -> {
            StateHousehold stateHousehold = stateHouseholdMap.get(e.getRealEstateCertificateNumber());
            if (Objects.nonNull(stateHousehold)) {
                e.setStateHouseholdId(stateHousehold.getId());
            }
        });
        List<String> settlementHoustIdInDB = stateSettlementsInDb.stream()
                .map(StateSettlement::getStateHouseholdId)
                .collect(Collectors.toList());
        List<ImportSettlementTemplateCurrencyVO> errorList = dataList.stream()
                .filter(obj -> (settlementHoustIdInDB.contains(obj.getStateHouseholdId()))).collect(Collectors.toList());
 
        if (!CollectionUtils.isEmpty(errorList)) {
            String error = errorList.stream().map(ImportSettlementTemplateCurrencyVO::getRealEstateCertificateNumber).collect(Collectors.joining(","));
            throw new GlobalException(String.format("这些不动产号已导入:%s", error));
        }
 
        List<StateSettlement> stateSettlement = StateProjectConvert.INSTANCE.templateCurrencyVOToEntity(dataList);
        LambdaQueryWrapper<StateSettlement> stateSettlementLQW = new LambdaQueryWrapper<>();
        stateSettlementLQW.eq(StateSettlement::getSettleName, importSettlementBO.getSettleName());
        List<StateSettlement> list1 = list(stateSettlementLQW);
        String taskId = UUID.randomUUID().toString().replace("-", "");
        Integer auditStatus = null;
        if (!CollectionUtils.isEmpty(list1)) {
            StateSettlement stateSettlementInDb = list1.stream().filter(Objects::nonNull).findFirst().get();
            if (com.zzg.common.utils.StringUtils.isNotBlank(stateSettlementInDb.getTaskId())) {
                taskId = stateSettlementInDb.getTaskId();
                if (ObjectUtil.isNotEmpty(stateSettlementInDb.getAuditStatus())) {
                    auditStatus = stateSettlementInDb.getAuditStatus();
                }
            }
        }
 
 
        for (StateSettlement e : stateSettlement) {
            e.setSettleName(importSettlementBO.getSettleName());
            e.setTaskId(taskId);
            if (ObjectUtil.isNotEmpty(auditStatus)) {
                e.setAuditStatus(auditStatus);
            }
        }
 
        saveOrUpdateBatch(stateSettlement);
    }
 
    /**
     * 计算签约、未签约比例数据
     * @param searchedPersons
     * @param notSearchedPersons
     * @param innerHouseId
     * @param signedVirtualPerson
     * @param notSignedVirtualPerson
     * @param projectVirtualExecutionSumVO
     */
    private void appendData(long searchedPersons, long notSearchedPersons, List<String> innerHouseId, long signedVirtualPerson, long notSignedVirtualPerson, ProjectExecutionSumVO projectVirtualExecutionSumVO) {
        projectVirtualExecutionSumVO.setSignedPersons(signedVirtualPerson);
        projectVirtualExecutionSumVO.setNotSignedPersons(notSignedVirtualPerson);
        // 计算 signedRate
        BigDecimal signedRate = BigDecimal.valueOf(signedVirtualPerson)
                .divide(BigDecimal.valueOf(innerHouseId.size()), 4, RoundingMode.HALF_UP) // 保留4位小数
                .multiply(BigDecimal.valueOf(100))
                .setScale(2, RoundingMode.HALF_UP); // 乘以100
        projectVirtualExecutionSumVO.setSignedRate(signedRate);
 
        //四舍五入保留2位小数 - 小数位数
 
        // 计算 notSignedRate
        BigDecimal notSignedRate = BigDecimal.valueOf(notSignedVirtualPerson)
                .divide(BigDecimal.valueOf(innerHouseId.size()), 4, RoundingMode.HALF_UP) // 保留4位小数
                .multiply(BigDecimal.valueOf(100))
                .setScale(2, RoundingMode.HALF_UP); // 乘以100
        projectVirtualExecutionSumVO.setNotSignedRate(notSignedRate);
 
        // 计算 signedProcessRate
        BigDecimal signedProcessRate = BigDecimal.valueOf(signedVirtualPerson)
                .divide(BigDecimal.valueOf(innerHouseId.size()), 4, RoundingMode.HALF_UP) // 保留4位小数
                .multiply(BigDecimal.valueOf(100))
                .setScale(2, RoundingMode.HALF_UP); // 乘以100
 
        projectVirtualExecutionSumVO.setSignedProcessRate(signedProcessRate);
        projectVirtualExecutionSumVO.setSearchedPersons(searchedPersons);
        projectVirtualExecutionSumVO.setNotSearchedPersons(notSearchedPersons);
        // 计算 searchProcessRate
        BigDecimal searched = BigDecimal.valueOf(searchedPersons);
        BigDecimal notSearched = BigDecimal.valueOf(notSearchedPersons);
        BigDecimal total = searched.add(notSearched);
 
        // 计算 searchProcessRate,保留4位小数
        BigDecimal searchProcessRate = BigDecimal.ZERO;
        if(total.compareTo(BigDecimal.ZERO) > 0) {
            searchProcessRate = searched.divide(total, 4, RoundingMode.HALF_UP)
                    .multiply(BigDecimal.valueOf(100))
                    .setScale(2, RoundingMode.HALF_UP);
        }
 
        projectVirtualExecutionSumVO.setSearchProcessRate(searchProcessRate);
    }
}