yanghb
2025-01-07 1ea7e38d7d2152012db3f49934e84d164a07d613
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
package com.zzg.system.service.state.impl;
 
import com.alibaba.excel.EasyExcelFactory;
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.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.StateHouseholdMapper;
import com.zzg.system.service.state.*;
import com.zzg.system.service.system.ISysDeptService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
 
import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
 
@Service
@RequiredArgsConstructor
public class StateHouseholdServiceImpl extends ServiceImpl<StateHouseholdMapper, StateHousehold> implements StateHouseholdService {
    @Lazy
    @Resource
    private StateProjectService stateProjectService;
    @Lazy
    @Resource
    private StateProjectInfoService stateProjectInfoService;
    @Lazy
    @Resource
    private StateHouseholdOwnerService stateHouseholdOwnerService;
    @Lazy
    @Resource
    private StateHouseholdService stateHouseholdService;
 
    @Lazy
    @Resource
    private StateAgreementService stateAgreementService;
 
    private final StateHouseholdMapper stateHouseholdMapper;
    private final StateProcessTemplateService processTemplateService;
    private final ISysDeptService deptService;
 
    @Override
    public HouseholdDetailVO queryList(HouseholdBO householdBOBody) {
        // 1. 获取所有数据并计算总人数、总面积
        List<HouseholdVO> householdVOS = this.getBaseMapper().listByConditions(householdBOBody);
        if (CollectionUtils.isEmpty(householdVOS)) {
            return new HouseholdDetailVO();
        }
 
        List<HouseholdVO> distinctList = new ArrayList<>(householdVOS.stream().filter(Objects::nonNull).collect(Collectors.toMap(HouseholdVO::getId, Function.identity(), (a, b) -> a)).values());
 
        long totalPersons = distinctList.size();
        List<HouseholdVO> agreeMoveOnes = distinctList.stream().filter(hv -> Objects.nonNull(hv) && Objects.nonNull(hv.getAgreeMove()) && (Objects.equals(hv.getAgreeMove(), HouseMoveEnum.AGREE_MOVE.getValue()))).collect(Collectors.toList());
 
        double totalArea = distinctList.stream().filter(hv -> Objects.nonNull(hv) && Objects.nonNull(hv.getHouseHoldArea())).mapToDouble(HouseholdVO::getHouseHoldArea).sum();
 
        long agreeMovePersons = agreeMoveOnes.size();
        double agreeMoveArea = agreeMoveOnes.stream().filter(hv -> Objects.nonNull(hv) && Objects.nonNull(hv.getHouseHoldArea())).mapToDouble(HouseholdVO::getHouseHoldArea).sum();
 
        //计算设计项目数量以及涉及房产数量
        Map<String, List<HouseholdVO>> stringListMap = distinctList.stream().collect(Collectors.groupingBy(HouseholdVO::getStateProjectId));
 
        Integer involvedProjects = stringListMap.keySet().size();
 
        Integer involvedHouses = stringListMap.values().stream().mapToInt(List::size)  // 获取每个 list 的大小
                .sum();
 
        //统计公用/私用房产
        Map<Integer, List<HouseholdVO>> useTypeHouseMap = distinctList.stream().collect(Collectors.groupingBy(HouseholdVO::getProductionType));
 
        long publicUsePersons = 0L;
        long privateUsePersons = 0L;
 
        double publicUseArea = 0D;
        double privateUseArea = 0D;
 
        for (Integer userType : useTypeHouseMap.keySet()) {
            List<HouseholdVO> innerList = useTypeHouseMap.get(userType);
            if (Objects.equals(userType, HouseProductionTypeEnum.PRIVATE_USE.getValue())) {
                privateUsePersons = innerList.size();
                privateUseArea = sumUsingArea(innerList);
            } else {
                publicUsePersons = innerList.size();
                publicUseArea = sumUsingArea(innerList);
            }
        }
 
        // 2. 启用分页并查询分页后的数据
        PageUtils.startPage();
        List<HouseholdVO> householdVoPage = this.getBaseMapper().pageByConditionsWithoutOwners(householdBOBody);
        PageInfo<HouseholdVO> householdVOPageInfo = new PageInfo<>(householdVoPage);
 
        householdVoPage = householdVoPage.stream().filter(Objects::nonNull).collect(Collectors.toList());
 
        LambdaQueryWrapper<StateHouseholdOwner> stateHouseholdOwnerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        stateHouseholdOwnerLambdaQueryWrapper.in(StateHouseholdOwner::getStateHouseholdId, householdVoPage.stream().map(StateHousehold::getId).collect(Collectors.toList()));
        if (com.zzg.common.utils.StringUtils.isNotBlank(householdBOBody.getOwnerName())) {
            stateHouseholdOwnerLambdaQueryWrapper.like(StateHouseholdOwner::getOwnerName, householdBOBody.getOwnerName());
        }
        List<StateHouseholdOwner> stateHouseholdOwners = stateHouseholdOwnerService.list(stateHouseholdOwnerLambdaQueryWrapper);
        Map<String, List<StateHouseholdOwner>> ownerMap = stateHouseholdOwners.stream().collect(Collectors.groupingBy(StateHouseholdOwner::getStateHouseholdId));
 
        if (!com.zzg.common.utils.StringUtils.isEmpty(householdBOBody.getOwnerName())) {
            householdVoPage = householdVoPage.stream().filter(data -> ownerMap.containsKey(data.getId())).collect(Collectors.toList());
        }
        householdVOPageInfo.setList(householdVoPage);
        // 3. 对分页后的数据进行分组和处理
        Map<String, HouseholdVO> householdMap = householdVoPage.stream().collect(Collectors.toMap(HouseholdVO::getId, Function.identity()));
        List<HouseholdVO> householdVoPageList = new ArrayList<>();
        for (String householdId : householdMap.keySet()) {
            HouseholdVO innerData = householdMap.get(householdId);
            if (ownerMap.containsKey(householdId)) {
                List<StateHouseholdOwner> stateHouseholdOwnerList = ownerMap.get(householdId);
                String ownerName = getFullName(stateHouseholdOwnerList);
                if (!Objects.equals(stateHouseholdOwnerList.size(), 1)) {
                    long countPersons = stateHouseholdOwnerList.stream().map(StateHouseholdOwner::getOwnerName).distinct().count();
                    innerData.setPersonNum(countPersons);
                } else if (Objects.equals(stateHouseholdOwnerList.size(), 1) && Objects.equals(stateHouseholdOwnerList.get(0).getOwnerType(), HouseOwnerTyeEnum.PERSONAL.getValue())) {
                    //当只有一个数据的时候只有权利人类型为私人的时候才计算数量
                    innerData.setPersonNum((long) stateHouseholdOwnerList.size());
                } else if (Objects.equals(stateHouseholdOwnerList.size(), 1) && Objects.equals(stateHouseholdOwnerList.get(0).getOwnerType(), HouseOwnerTyeEnum.COMPANY.getValue())) {
                    innerData.setPersonNum((long) stateHouseholdOwnerList.size());
                }
                innerData.setOwnerName(ownerName);
                innerData.setOwnerType(stateHouseholdOwnerList.get(0).getOwnerType());
            }
            if (Objects.nonNull(innerData.getProductionType())) {
                innerData.setProductionTypeStr(HouseProductionTypeEnum.getValueByKey(innerData.getProductionType()));
            }
            //原有的取的第一个数据 现在也直接取第一个权利人信息的类型
            innerData.setOwnerTypeStr(HouseOwnerTyeEnum.getValueByKey(innerData.getOwnerType()));
            householdVoPageList.add(innerData);
        }
        householdVoPageList.forEach(e -> e.setProjectStatusStr(StateProjectStatusEnum.getValueByKey(e.getProjectStatus())));
 
 
        //去除已经转为模拟征收的项目数据
        // TODO 明天测试确认忘记干啥的了
//        List<HouseholdVO> list = householdVoPageList.stream().filter(Objects::nonNull).filter(data -> !Objects.equals(data.getProjectStatus(), StateProjectStatusEnum.SIMULATE.getKey())).collect(Collectors.toList());
 
        //app端需要根据调查状态进行分类
        List<HouseholdVO> householdVOList = new ArrayList<>();
 
        if (Objects.nonNull(householdBOBody.getSearchStatus())) {
            if (Objects.equals(householdBOBody.getSearchStatus(), HouseSearchStatusEnum.SEARCHED.getValue())) {
                householdVOList.addAll(householdVoPageList.stream().filter(data -> Objects.nonNull(data) && Objects.equals(data.getSearchStatus(), HouseSearchStatusEnum.SEARCHED.getValue())).collect(Collectors.toList()));
            } else if (Objects.equals(householdBOBody.getSearchStatus(), HouseSearchStatusEnum.NOT_SEARCH.getValue())) {
                householdVOList.addAll(householdVoPageList.stream().filter(data -> Objects.nonNull(data) && Objects.equals(data.getSearchStatus(), HouseSearchStatusEnum.NOT_SEARCH.getValue())).collect(Collectors.toList()));
            } else if (Objects.equals(householdBOBody.getSearchStatus(), HouseSearchStatusEnum.COMPLETE_ASSESSMENT.getValue())) {
                householdVOList.addAll(householdVoPageList.stream().filter(data -> Objects.nonNull(data) && Objects.equals(data.getSearchStatus(), HouseSearchStatusEnum.COMPLETE_ASSESSMENT.getValue())).collect(Collectors.toList()));
            }
        } else {
            householdVOList.addAll(householdVoPageList);
        }
 
 
        List<String> deptIdList = householdVOList.stream().map(StateHousehold::getDeptId).collect(Collectors.toList());
        Map<String, SysDept> stringSysDeptMap = deptService.selectMapDeptById(deptIdList);
        householdVOList.forEach(e -> e.setDepartment(Optional.ofNullable(stringSysDeptMap.get(e.getDeptId())).orElse(new SysDept()).getDeptName()));
        // 4. 构建结果对象
        HouseholdDetailVO result = new HouseholdDetailVO();
        Optional<HouseholdVO> householdVO = householdVoPageList.stream().findFirst();
        result.setProjectName(householdVO.map(HouseholdVO::getProjectName).orElse(null));
        householdVOPageInfo.setList(householdVOList);
        result.setHouseholdVOS(householdVOPageInfo);
        result.setAllHouse(totalPersons);
        result.setAllArea(BigDecimal.valueOf(totalArea).setScale(2, RoundingMode.UP).doubleValue());
        result.setAgreeToMoveArea(BigDecimal.valueOf(agreeMoveArea).setScale(2, RoundingMode.UP).doubleValue());
        result.setAgreeToMovePersons(agreeMovePersons);
        result.setAgreeToMovePersonsRate(new BigDecimal(agreeMovePersons)
                .divide(new BigDecimal(totalPersons), 4, RoundingMode.UP).multiply(new BigDecimal("100"))
                .setScale(2, RoundingMode.UP).doubleValue());
 
        double moveAreaRate = agreeMoveArea / totalArea * 100;
        result.setAgreeToMoveAreaRate(BigDecimal.valueOf(moveAreaRate).setScale(2, RoundingMode.UP).doubleValue());
 
        result.setPrivateUseArea(BigDecimal.valueOf(privateUseArea).setScale(2, RoundingMode.UP).doubleValue());
        result.setPrivateUsePersons(privateUsePersons);
        result.setPublicUseArea(BigDecimal.valueOf(publicUseArea).setScale(2, RoundingMode.UP).doubleValue());
        result.setPublicUsePersons(publicUsePersons);
        result.setHouseCount(involvedHouses);
        result.setProjectCount(involvedProjects);
        return result;
    }
 
    @Override
    public void sumHouseholdData(String stateProjectId) {
 
    }
 
    @Override
    public PageInfo<HouseholdVO> pageByProjectId(List<String> projectIdList, String street) {
        PageUtils.startPage();
        return new PageInfo<>(this.getBaseMapper().pageByProjectId(projectIdList, street));
    }
 
    @Override
    public StateHouseholdVO getStateHouseholdInfo(String id) {
        StateHousehold household = this.getById(id);
        String stateProjectId = household.getStateProjectId();
        StateHouseholdVO vo = StateProjectConvert.INSTANCE.toStateHouseholdVO(household);
        StateProject projectById = stateProjectService.getProjectById(stateProjectId);
        if (Objects.nonNull(projectById)) {
            vo.setProjectName(projectById.getProjectName());
            vo.setProjectStatus(projectById.getStatus());
            vo.setProjectStatusStr(StateProjectStatusEnum.getValue(projectById.getStatus()));
        }
        if (StringUtils.isNoneBlank(household.getAppendData())) {
            CalculateCompensationBO calculateCompensationBO = JSON.parseObject(household.getAppendData(), CalculateCompensationBO.class);
            calculateCompensationBO.setStateHouseholdId(id);
            vo.setAppendData(JSON.toJSONString(stateHouseholdOwnerService.calculateCompensation(calculateCompensationBO)));
        }
        return vo;
    }
 
    @Override
    @Transactional
    public Boolean importStateHousehold(MultipartFile file, String projectId) {
        List<StateHouseholdImportVO> dataList;
        StateProject stateHouseholds = stateProjectService.getProjectById(projectId);
        if (Objects.isNull(stateHouseholds)) {
            throw new GlobalException("未查询到相应房产");
        }
        List<String> streetList = Arrays.asList(stateHouseholds.getStreet().split(","));
 
        try {
            dataList = EasyExcelFactory.read(FileUtil.convertToFile(file)).head(StateHouseholdImportVO.class).sheet().doReadSync();
        } catch (Exception e) {
            throw new GlobalException("导入失败,房产导入模板错误");
        }
        dataList.forEach(e -> {
            if (Objects.isNull(e.getStreet()) || Objects.isNull(e.getDoorNumber()) || Objects.isNull(e.getRealEstateCertificateNumber()) || Objects.isNull(e.getHouseHoldArea()) || Objects.isNull(e.getBelongingStreetTown())) {
                throw new GlobalException("街道、门牌、不动产权证号、面积、房产所属镇街 其中某个字段为空");
            }
            if (!streetList.contains(e.getBelongingStreetTown())) {
                throw new GlobalException(String.format("该所属街道不属于本项目:%s", e.getBelongingStreetTown()));
            }
            Integer value = HouseUsingTypeEnum.getValue(e.getHouseUsingTypeStr());
            if (value == 0) {
                throw new GlobalException("房屋用途数据填写错误");
            }
            Integer productionType = HouseProductionTypeEnum.getValue(e.getProductionTypeStr());
            if (productionType == 0) {
                throw new GlobalException("产别数据填写错误");
            }
            e.setHouseUsingType(value);
            e.setProductionType(productionType);
        });
        List<HouseholdVO> householdVOS = StateProjectConvert.INSTANCE.importOrExportToHouseholdVO(dataList);
 
        List<StateHousehold> householdList = new ArrayList<>();
 
        String deptId = SecurityUtils.getLoginUser().getUser().getDept().getDeptId();
        StateHousehold stateHousehold;
        for (HouseholdVO e : householdVOS) {
            stateHousehold = StateProjectConvert.INSTANCE.householdVOToStateHouseholdPO(e);
            stateHousehold.setStateProjectId(projectId);
            stateHousehold.setDeptId(deptId);
            householdList.add(stateHousehold);
        }
        List<String> realEstateCertificateNumberList = householdList.stream().map(StateHousehold::getRealEstateCertificateNumber).collect(Collectors.toList());
        LambdaQueryWrapper<StateHousehold> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(StateHousehold::getRealEstateCertificateNumber, realEstateCertificateNumberList);
        List<StateHousehold> list = list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            String msg = list.stream().map(StateHousehold::getRealEstateCertificateNumber).collect(Collectors.joining(","));
            throw new GlobalException(String.format("不动产号重复:%s", msg));
        }
 
 
//        this.saveBatch(householdList);
//        List<StateHouseholdOwner> ownerList = new ArrayList<>();
//        for (int i = 0; i < householdVOS.size(); i++) {
//            StateHousehold stateHousehold = householdList.get(i); // 已保存的 StateHousehold,具有 ID
//            HouseholdVO e = householdVOS.get(i);
//
//            // 根据业主名称拆分成多个 StateHouseholdOwner 对象
//            List<HouseholdVO> voList = splitFullName(e.getOwnerName());
//            voList.forEach(x -> {
//                StateHouseholdOwner stateHouseholdOwner = new StateHouseholdOwner();
//                stateHouseholdOwner.setOwnerName(x.getOwnerName());
//                stateHouseholdOwner.setStateHouseholdId(stateHousehold.getId()); // 设置保存后的 ID
//                stateHouseholdOwner.setOwnerType(e.getOwnerType());
//                ownerList.add(stateHouseholdOwner);
//            });
//        }
 
//        stateHouseholdOwnerService.saveBatch(ownerList);
 
 
        boolean updateOperation = this.saveBatch(householdList);
 
        List<StateAgreement> agreements = new ArrayList<>();
        householdList.forEach(house -> {
            // 存储协议数据
            List<StateAgreement> agreementFileTypeList = new ArrayList<>();
            for (AgreementTypeEnum type : AgreementTypeEnum.values()) {
                if (type.getValue() > 4) {
                    break;
                }
                // 只存储前四个模板数据
                StateAgreement agreement = new StateAgreement();
                agreement.setStateHouseholdId(house.getId());
                agreement.setAgreementFileType(type.getValue());
                agreementFileTypeList.add(agreement);
            }
            agreements.addAll(agreementFileTypeList);
        });
        stateAgreementService.saveOrUpdateBatch(agreements);
        return updateOperation;
    }
 
    @Override
    public PageInfo<HouseQueryVO> queryData(HouseQueryBO houseQueryBO) {
        PageUtils.startPage();
 
        List<HouseQueryVO> houseQueryVOS = stateHouseholdMapper.listBySearchCondition(houseQueryBO);
        if (CollectionUtils.isEmpty(houseQueryVOS)) {
            return new PageInfo<>();
        }
        PageInfo<HouseQueryVO> houseQueryVOPageInfo = new PageInfo<>(houseQueryVOS);
        List<String> projectIdList = houseQueryVOPageInfo.getList().stream().map(HouseQueryVO::getProjectId).collect(Collectors.toList());
        LambdaQueryWrapper<StateHousehold> stateHouseholdLambdaQueryWrapper = new LambdaQueryWrapper<>();
        stateHouseholdLambdaQueryWrapper.in(StateHousehold::getStateProjectId, projectIdList);
        List<StateHousehold> stateHouseholds = stateHouseholdMapper.selectList(stateHouseholdLambdaQueryWrapper);
        if (CollectionUtils.isEmpty(stateHouseholds)) {
            return new PageInfo<>(houseQueryVOS);
        }
        Map<String, List<StateHousehold>> stringListMap = stateHouseholds.stream().collect(Collectors.groupingBy(StateHousehold::getStateProjectId));
        //设置总人数 总面积 同意搬迁人数 同意搬迁面积  同意搬迁人数占比  同意搬迁面积占比
        houseQueryVOS.forEach(data -> {
            if (stringListMap.containsKey(data.getProjectId())) {
                List<StateHousehold> householdList = stringListMap.get(data.getProjectId());
                Integer totalPerson = householdList.size();
 
                Double totalArea = householdList.stream().filter(house -> Objects.nonNull(house.getHouseHoldArea())).mapToDouble(StateHousehold::getHouseHoldArea).sum();
 
                Integer agreeMovePersons = (int) householdList.stream().filter(house -> Objects.nonNull(house.getAgreeMove()) && Objects.equals(house.getAgreeMove(), HouseMoveEnum.AGREE_MOVE.getValue())).count();
 
                Double agreeMoveArea = householdList.stream().filter(house -> Objects.nonNull(house.getAgreeMove()) && Objects.equals(house.getAgreeMove(), HouseMoveEnum.AGREE_MOVE.getValue())).mapToDouble(StateHousehold::getHouseHoldArea).sum();
 
                data.setAllHouse(totalPerson);
                data.setAllArea(BigDecimal.valueOf(totalArea).setScale(2, BigDecimal.ROUND_HALF_UP));
                data.setAgreeToMoveArea(BigDecimal.valueOf(agreeMoveArea).setScale(2, BigDecimal.ROUND_HALF_UP));
                data.setAgreeToMovePersons(agreeMovePersons);
 
                data.setAgreeToMovePersonsRate(new BigDecimal(agreeMovePersons).divide(new BigDecimal(totalPerson), 2, RoundingMode.UP).multiply(new BigDecimal("100")));
                data.setAgreeToMoveAreaRate(BigDecimal.valueOf(agreeMoveArea / totalArea * 100).setScale(2, BigDecimal.ROUND_HALF_UP));
            }
        });
        houseQueryVOPageInfo.setList(houseQueryVOS);
        return houseQueryVOPageInfo;
    }
 
    @Override
    public HouseAgreeMoveRateBO currentProjectRate(String projectId) {
        LambdaQueryWrapper<StateHousehold> stateHouseholdLambdaQueryWrapper = new LambdaQueryWrapper<>();
 
        stateHouseholdLambdaQueryWrapper.eq(StateHousehold::getStateProjectId, projectId);
 
        List<StateHousehold> stateHouseholds = this.list(stateHouseholdLambdaQueryWrapper);
        if (CollectionUtils.isEmpty(stateHouseholds)) {
            return new HouseAgreeMoveRateBO();
        }
        List<StateHousehold> agreeList = stateHouseholds.stream().filter(data -> Objects.nonNull(data.getAgreeMove()) && Objects.equals(HouseMoveEnum.AGREE_MOVE.getValue(), data.getAgreeMove())).collect(Collectors.toList());
        Double personRate = (double) agreeList.size() / stateHouseholds.size() * 100;
 
        Double areaRate = agreeList.stream().filter(innerHouse -> Objects.nonNull(innerHouse.getHouseHoldArea())).mapToDouble(StateHousehold::getHouseHoldArea).sum() / stateHouseholds.stream().filter(innerHouse -> Objects.nonNull(innerHouse.getHouseHoldArea())).mapToDouble(StateHousehold::getHouseHoldArea).sum() * 100;
 
        HouseAgreeMoveRateBO houseAgreeMoveRateBO = new HouseAgreeMoveRateBO();
        houseAgreeMoveRateBO.setAreaAgreeMoveRate(areaRate);
        houseAgreeMoveRateBO.setPersonAgreeMoveRate(personRate);
        return houseAgreeMoveRateBO;
    }
 
    @Transactional
    @Override
    public void submitHouseHoldAudit(String projectId, Integer category) {
 
        LambdaQueryWrapper<StateHousehold> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StateHousehold::getStateProjectId, projectId);
        List<StateHousehold> stateHouseholdList = this.list(queryWrapper);
 
        StateProject one = stateProjectService.getProjectById(projectId);
        StateProjectInfo stateProjectInfo = stateProjectInfoService.getById(projectId);
        if (Objects.isNull(one)) {
            throw new GlobalException("错误数据");
        }
        ProcessCategoryEnum categoryEnum = ProcessCategoryEnum.getEnumByKey(category);
        switch (categoryEnum) {
            case CATEGORY1:
                //入户调查
                initiateWorkflow(projectId, stateHouseholdList, one, stateProjectInfo, categoryEnum);
                one.setAuditStatus(SubmitStatusEnum.PENDING_REVIEW.getValue());
                stateProjectService.saveOrUpdate(one);
                break;
            case CATEGORY2: {
                //价格评估
                initiateWorkflow(projectId, stateHouseholdList, one, stateProjectInfo, categoryEnum);
                one.setPriceStatus(SubmitStatusEnum.PENDING_REVIEW.getValue());
                stateProjectService.saveOrUpdate(one);
                //房产状态修改
                stateHouseholdService.updateHouseHoldStatus(one.getId(), SubmitStatusEnum.PENDING_REVIEW.getValue());
                break;
            }
            default:
                throw new GlobalException("错误审核类型");
 
        }
 
 
    }
 
    private void initiateWorkflow(String projectId, List<StateHousehold> stateHouseholdList, StateProject one, StateProjectInfo stateProjectInfo, ProcessCategoryEnum categoryEnum) {
        ProcessStartBO processStartBO = new ProcessStartBO();
        processStartBO.setCategory(categoryEnum.getValue().toString());
        processStartBO.setName(one.getProjectName());
        processStartBO.setModuleName(categoryEnum.getText());
        Map<String, Object> variable = new HashMap<>();
        variable.put("projectId", projectId);
        processStartBO.setVariable(variable);
        Map<String, SysDept> stringSysDeptMap = deptService.selectMapDeptById(Arrays.asList(stateProjectInfo.getCollectionEnforcementDepartment().split(",")));
        String remake = String.format("【镇/街】:%s,【征收实施单位】:%s,【调查户数】:%s", one.getStreet(), stringSysDeptMap.values().stream().map(SysDept::getDeptName).collect(Collectors.joining(",")), stateHouseholdList.size());
        processStartBO.setRemark(remake);
        if (categoryEnum.getValue() == 1) {
            processStartBO.setModuleName("入户调查");
        } else {
            processStartBO.setModuleName("价格评估");
        }
        processTemplateService.start(processStartBO);
 
        this.updateHouseHoldStatus(projectId, SubmitStatusEnum.PENDING_REVIEW.getValue());
    }
 
    @Override
    public void updateHouseHoldStatus(String projectId, Integer status) {
        LambdaUpdateWrapper<StateHousehold> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(StateHousehold::getStateProjectId, projectId).set(StateHousehold::getStatus, status);
        this.update(updateWrapper);
    }
 
    @Override
    public void updateHouseHoldAgreementStatus(String stateHouseholdId, Integer status) {
        LambdaUpdateWrapper<StateHousehold> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(StateHousehold::getId, stateHouseholdId).set(StateHousehold::getAgreementStatus, status);
        this.update(updateWrapper);
    }
 
    @Override
    @Transactional
    public StateHouseholdBO createAndUpdateHouse(StateHouseholdBO household) {
 
        boolean updateOperation = Objects.isNull(household.getId());
 
        String stateProjectId = household.getStateProjectId();
//        StateProject projectById = stateProjectService.getProjectById(stateProjectId);
//        if (Objects.nonNull(projectById) && Objects.nonNull(projectById.getAuditStatus()) && (Objects.equals(projectById.getStatus(), StateProjectStatusEnum.LEVY.getKey()))
//                && !Objects.equals(projectById.getIsNeedEvaluate(), 1)
//        ) {
//            throw new GlobalException("项目已在征收阶段,不可新增房产");
//        }
 
        StateHousehold existingHousehold = null;
        if (!updateOperation) {
            existingHousehold = getById(household.getId());
        }
 
        // 校验 realEstateCertificateNumber 是否唯一(新增或更新且该字段被修改时)
        if (updateOperation || (!Objects.equals(household.getRealEstateCertificateNumber(), existingHousehold.getRealEstateCertificateNumber()))) {
            boolean isRealEstateNumberExists = existsByRealEstateCertificateNumber(household.getRealEstateCertificateNumber());
            if (isRealEstateNumberExists) {
                throw new GlobalException("不动产权证号已存在,不能重复");
            }
        }
 
        // 构建 householdLocation
 
        String location = household.getStreet();
        if (Objects.nonNull(household.getDoorNumber())) {
            location += household.getDoorNumber();
        }
        if (Objects.nonNull(household.getApartmentNumber())) {
            location += household.getApartmentNumber();
        }
        if (Objects.nonNull(household.getBuildingNumber())) {
            location += household.getBuildingNumber();
        }
        if (Objects.nonNull(household.getUnit())) {
            location += household.getUnit();
        }
        if (Objects.nonNull(household.getFloor())) {
            location += household.getFloor();
        }
        if (Objects.nonNull(household.getRoomNumber())) {
            location += household.getRoomNumber();
        }
        household.setHouseholdLocation(location);
 
 
        // 设置文件URL
        if (Objects.nonNull(household.getFileBOList()) && !org.springframework.util.CollectionUtils.isEmpty(household.getFileBOList())) {
            household.setFileUrl(JSON.toJSONString(household.getFileBOList()));
        }
 
        if (Objects.nonNull(household.getId())) {
            LambdaQueryWrapper<StateHouseholdOwner> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StateHouseholdOwner::getStateHouseholdId, household.getId());
 
//            if (stateHouseholdOwnerService.count(queryWrapper) == 0) {
//                throw new GlobalException("需要至少一个权利人");
//            }
        }
 
        saveOrUpdate(household);
        // 设置附加数据
        if (Objects.nonNull(household.getAppendData()) && StringUtils.isNotBlank(household.getAppendData())) {
            String appendDataStr = household.getAppendData();
            CalculateCompensationBO calculateCompensationBO = JSON.parseObject(appendDataStr, CalculateCompensationBO.class);
            household.setAgreeMove(Optional.ofNullable(calculateCompensationBO.getSurveyResultRegistrationBO()).orElse(new SurveyResultRegistrationBO()).getIsAgree());
            // 存储 JSON 字段的补偿方式以及备注
            if (Objects.nonNull(calculateCompensationBO.getHomeCompensationBO()) && Objects.nonNull(calculateCompensationBO.getHomeCompensationBO().getHomeCompensationType())) {
                household.setCompensationType(calculateCompensationBO.getHomeCompensationBO().getHomeCompensationType());
            }
            //添加是是否同意搬迁
            if (Objects.nonNull(calculateCompensationBO.getSurveyResultRegistrationBO()) && Objects.nonNull(calculateCompensationBO.getSurveyResultRegistrationBO().getIsAgree())) {
                household.setAgreeMove(calculateCompensationBO.getSurveyResultRegistrationBO().getIsAgree());
            }
            calculateCompensationBO.setIsFirst(null);
            calculateCompensationBO.setStateHouseholdId(household.getId());
            CalculateCompensationVO calculateCompensationVO = stateHouseholdOwnerService.calculateCompensation(calculateCompensationBO);
            household.setAppendData(JSON.toJSONString(calculateCompensationVO));
        }
 
        String deptId = SecurityUtils.getLoginUser().getUser().getDept().getDeptId();
        household.setDeptId(deptId);
 
 
        saveOrUpdate(household);
 
        // 存储协议数据
        List<StateAgreement> agreementFileTypeList = new ArrayList<>();
        if (updateOperation) {
            for (AgreementTypeEnum type : AgreementTypeEnum.values()) {
                if (type.getValue() > 4) {
                    break;
                }
                // 只存储前四个模板数据
                StateAgreement agreement = new StateAgreement();
                agreement.setStateHouseholdId(household.getId());
                agreement.setAgreementFileType(type.getValue());
                agreementFileTypeList.add(agreement);
            }
        }
        stateAgreementService.saveOrUpdateBatch(agreementFileTypeList);
 
        return household;
    }
 
    public boolean existsByRealEstateCertificateNumber(String realEstateCertificateNumber) {
        // 创建 QueryWrapper 来封装查询条件
        LambdaQueryWrapper<StateHousehold> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StateHousehold::getRealEstateCertificateNumber, realEstateCertificateNumber).eq(StateHousehold::getDelFlag, 0);  // 如果有逻辑删除标记
        return count(queryWrapper) > 0L;
    }
 
    @Override
    public List<JSONObject> listStreet(String projectId) {
 
        StateProject stateHouseholds = stateProjectService.getProjectById(projectId);
        if (Objects.isNull(stateHouseholds)) {
            return new ArrayList<>();
        }
        List<String> streetList = Arrays.asList(stateHouseholds.getStreet().split(","));
 
        List<JSONObject> result = new ArrayList<>();
        streetList.forEach(data -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("street", data);
            result.add(jsonObject);
        });
        return result;
    }
 
    @Override
    public Boolean mobileBack(String houseId) {
        StateHousehold stateHousehold = this.getById(houseId);
        if (Objects.isNull(stateHousehold)) {
            throw new GlobalException("该房产数据不存在");
        }
        CalculateCompensationBO calculateCompensationBO = new CalculateCompensationBO();
        if (Objects.nonNull(stateHousehold.getAppendData()) && StringUtils.isNotBlank(stateHousehold.getAppendData())) {
            calculateCompensationBO = JSON.parseObject(stateHousehold.getAppendData(), CalculateCompensationBO.class);
            if (Objects.nonNull(calculateCompensationBO.getSurveyResultRegistrationBO())) {
                calculateCompensationBO.getSurveyResultRegistrationBO().setIsAgree(null);
                calculateCompensationBO.getSurveyResultRegistrationBO().setIsConfirm(null);
            }
        }
 
        LambdaUpdateWrapper<StateHousehold> stateHouseholdUpdateWrapper = new LambdaUpdateWrapper<>();
        stateHouseholdUpdateWrapper.eq(StateHousehold::getId, houseId);
        stateHouseholdUpdateWrapper.set(StateHousehold::getSearchStatus, HouseSearchStatusEnum.NOT_SEARCH.getValue());
        stateHouseholdUpdateWrapper.set(StateHousehold::getAgreeMove, null);
        stateHouseholdUpdateWrapper.set(StateHousehold::getAppendData, JSON.toJSONString(calculateCompensationBO));
        if (Objects.equals(stateHousehold.getStage(), StateHouseholdStageEnums.SIMULATE_SUCCESS.getValue())) {
            stateHouseholdUpdateWrapper.set(StateHousehold::getStage, StateHouseholdStageEnums.SIMULATE.getValue());
        } else if (Objects.equals(stateHousehold.getStage(), StateHouseholdStageEnums.LEVY_SUCCESS.getValue())) {
            stateHouseholdUpdateWrapper.set(StateHousehold::getStage, StateHouseholdStageEnums.LEVY.getValue());
        }
        return this.update(stateHouseholdUpdateWrapper);
    }
 
    private String getFullName(List<StateHouseholdOwner> householdVOS) {
 
        List<String> uniqueOwnerNames = householdVOS.stream().map(StateHouseholdOwner::getOwnerName).distinct().collect(Collectors.toList());
        return String.join("|", uniqueOwnerNames);
    }
 
    private List<HouseholdVO> splitFullName(String fullName) {
        // 分割竖线分隔的字符串为数组
        String[] ownerNames = fullName.split("\\|");
 
        // 创建 HouseholdVO 对象列表
        List<HouseholdVO> householdVOS = new ArrayList<>();
 
        // 将每个 ownerName 转换为 HouseholdVO 对象,并添加到列表中
        for (String ownerName : ownerNames) {
            HouseholdVO householdVO = new HouseholdVO();
            householdVO.setOwnerName(ownerName);
            householdVOS.add(householdVO);
        }
 
        return householdVOS;
    }
 
    private Double sumUsingArea(List<HouseholdVO> innerList) {
        return CollectionUtils.isNotEmpty(innerList) ? innerList.stream().filter(e -> Objects.nonNull(e) && Objects.nonNull(e.getHouseHoldArea())).mapToDouble(StateHousehold::getHouseHoldArea).sum() : 0;
 
    }
}