mitao
2025-05-09 135090721ee50abef2577e61617d3f2b2e15bb4a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
package com.panzhihua.sangeshenbian.service.impl;
 
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.idev.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deepoove.poi.XWPFTemplate;
import com.panzhihua.common.exceptions.ServiceException;
import com.panzhihua.common.model.vos.LoginUserInfoVO;
import com.panzhihua.common.model.vos.sangeshenbian.SystemUserVo;
import com.panzhihua.common.redis.RedisUtils;
import com.panzhihua.common.utlis.DateUtils;
import com.panzhihua.common.utlis.StringUtils;
import com.panzhihua.sangeshenbian.config.AutoColumnWidthStrategy;
import com.panzhihua.sangeshenbian.dao.ComplaintMapper;
import com.panzhihua.sangeshenbian.enums.*;
import com.panzhihua.sangeshenbian.model.dto.*;
import com.panzhihua.sangeshenbian.model.entity.*;
import com.panzhihua.sangeshenbian.model.excel.ComplaintExcel;
import com.panzhihua.sangeshenbian.model.query.AnalyticStatisticsQuery;
import com.panzhihua.sangeshenbian.model.query.BasePage;
import com.panzhihua.sangeshenbian.model.query.ComplaintQuery;
import com.panzhihua.sangeshenbian.model.vo.*;
import com.panzhihua.sangeshenbian.service.*;
import com.panzhihua.sangeshenbian.warpper.IdentityInformation;
import com.panzhihua.sangeshenbian.warpper.MgtComplaintQuery;
import com.panzhihua.sangeshenbian.warpper.PermissionsVO;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
 
import static cn.hutool.core.util.ObjectUtil.isNull;
 
/**
 * <p>
 * 问题报告表 服务实现类
 * </p>
 *
 * @author
 * @since 2025-02-22
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class ComplaintServiceImpl extends ServiceImpl<ComplaintMapper, Complaint> implements IComplaintService {
    private final ISystemUserService systemUserService;
    private final IComplaintFlowService complaintFlowService;
    private final IComplaintProgressService complaintProgressService;
 
    private final IComplaintAuditRecordService complaintAuditRecordService;
    private final IBcRegionService bcRegionService;
    private final IComStreetService comStreetService;
    private final IComActService comActService;
    private final IWorkOrderItemConfigService workOrderItemConfigService;
    private final IComplaintCommentService complaintCommentService;
    private final HttpServletResponse response;
    private final IPartyMemberService partyMemberService;
    private final IdentityInformationService identityInformationService;
    private final RedisUtils redisUtils;
 
    @Override
    public void saveComplaint(Complaint complaint, LoginUserInfoVO loginUserInfoVO) {
        // 获取当前日期(年月日)
        String datePrefix = new SimpleDateFormat("yyyyMMdd").format(new Date());
 
        // 查询当前日期的最大流水号
        Complaint lastComplaint = getOne(new LambdaQueryWrapper<Complaint>()
                .likeRight(Complaint::getSerialNumber, datePrefix) // 查询以当前日期开头的流水号
                .orderByDesc(Complaint::getSerialNumber)
                .last("limit 1"));
 
        String serialNumber;
        if (isNull(lastComplaint)) {
            // 如果当天没有记录,从 0001 开始
            serialNumber = datePrefix + "0001";
        } else {
            // 获取当前日期的最大流水号,并递增
            String lastSerialNumber = lastComplaint.getSerialNumber();
            int num = Integer.parseInt(lastSerialNumber.substring(lastSerialNumber.length() - 4)); // 提取后4位数字
            serialNumber = datePrefix + String.format("%04d", num + 1); // 递增并格式化为4位
        }
 
        // 设置流水号
        complaint.setSerialNumber(serialNumber);
        Integer accountLevel = 5;
        //获取当前身份
        IdentityInformation identityInformationVO = identityInformationService.getCurrentIdentityInformation(loginUserInfoVO);
        //1=党员,2=管理员
        SystemUser systemUser = identityInformationVO.getSystemUser();
        Integer identity = identityInformationVO.getIdentity();
        if (identity == 2) {
            SystemUserLevel systemUserLevel = identityInformationVO.getSystemUserLevel();
            accountLevel = systemUserLevel.getLevel();
            switch (accountLevel) {
                case 1:
                    //市级
                    complaint.setCityCode(510400);
                    complaint.setReportUserName(systemUser.getName());
                    complaint.setReportUserPhone(systemUser.getPhone());
                    break;
                case 2:
                    //区县级
                    complaint.setCityCode(510400);
                    complaint.setDistrictsCode(Integer.valueOf(systemUserLevel.getDistrictsCode()));
                    complaint.setReportUserName(systemUser.getName());
                    complaint.setReportUserPhone(systemUser.getPhone());
                    break;
                case 3:
                    //街道
                    complaint.setCityCode(510400);
                    complaint.setDistrictsCode(Integer.valueOf(systemUserLevel.getDistrictsCode()));
                    complaint.setStreetId(Long.valueOf(systemUserLevel.getStreetId()));
                    complaint.setReportUserName(systemUser.getName());
                    complaint.setReportUserPhone(systemUser.getPhone());
                    break;
                case 4:
                    //社区
                    complaint.setCityCode(510400);
                    complaint.setDistrictsCode(Integer.valueOf(systemUserLevel.getDistrictsCode()));
                    complaint.setStreetId(Long.valueOf(systemUserLevel.getStreetId()));
                    complaint.setCommunityId(systemUserLevel.getCommunityId());
                    complaint.setReportUserName(systemUser.getName());
                    complaint.setReportUserPhone(systemUser.getPhone());
                    break;
                case 5:
                    //党员
                    complaint.setCityCode(510400);
                    complaint.setDistrictsCode(Integer.valueOf(systemUserLevel.getDistrictsCode()));
                    complaint.setStreetId(Long.valueOf(systemUserLevel.getStreetId()));
                    complaint.setCommunityId(systemUserLevel.getCommunityId());
                    PartyMember partyMember = partyMemberService.getPartyMemberByPhone(loginUserInfoVO.getPhone());
                    complaint.setPartyMemberId(partyMember.getId());
                    complaint.setReportUserName(partyMember.getName());
                    complaint.setReportUserPhone(partyMember.getPhone());
                    break;
            }
        } else {
            PartyMember partyMember = partyMemberService.getPartyMemberByPhone(loginUserInfoVO.getPhone());
            //党员
            complaint.setCityCode(510400);
            complaint.setDistrictsCode(Integer.valueOf(partyMember.getDistrictsCode()));
            complaint.setStreetId(Long.valueOf(partyMember.getStreetId()));
            complaint.setCommunityId(partyMember.getCommunityId());
            complaint.setPartyMemberId(partyMember.getId());
            complaint.setReportUserName(partyMember.getName());
            complaint.setReportUserPhone(partyMember.getPhone());
        }
        complaint.setReportType(accountLevel);
        // 设置其他字段
        complaint.setStatus(ProcessStatusEnum.PROCESSING.getCode());
        complaint.setCreateTime(new Date(System.currentTimeMillis()));
        complaint.setCreateBy(loginUserInfoVO.getUserId());
        complaint.setUpdateBy(loginUserInfoVO.getUserId());
        complaint.setUpdateTime(new Date(System.currentTimeMillis()));
        //查询系统配置诉求处理期限,设置截止日期
        WorkOrderItemConfig config = workOrderItemConfigService.lambdaQuery().orderByDesc(WorkOrderItemConfig::getId).last("LIMIT 1").one();
        if (Objects.isNull(config)) {
            throw new ServiceException("工单事项未配置,请联系管理员");
        }
        complaint.setClosingTime(new Date(System.currentTimeMillis() + config.getDemandProcessingTime() * 24 * 60 * 60 * 1000));
        // 保存诉求记录
        save(complaint);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAndReport(ComplaintVO complaintVO, LoginUserInfoVO loginUserInfo) {
        Complaint complaint = new Complaint();
        BeanUtil.copyProperties(complaintVO, complaint);
        saveComplaint(complaint, loginUserInfo);
        ComplaintReportDTO dto = new ComplaintReportDTO();
        dto.setComplaintId(complaint.getId());
        dto.setComment(complaintVO.getComment());
        saveReport(dto, loginUserInfo);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAndComplete(ComplaintSaveAndCompleteDTO complaintVO, LoginUserInfoVO loginUserInfo) {
        Complaint complaint = new Complaint();
        BeanUtil.copyProperties(complaintVO, complaint);
        saveComplaint(complaint, loginUserInfo);
 
        ComplaintCompletionDTO complaintCompletionDTO = complaintVO.getComplaintCompletionDTO();
        complaintCompletionDTO.setComplaintId(complaint.getId());
        complaintCompletionDTO.setId(complaint.getId());
        saveResult(complaintCompletionDTO, loginUserInfo);
    }
 
    @Override
    public Page<ComplaintVO> complaintList(ComplaintQuery query, LoginUserInfoVO loginUserInfoVO) {
 
 
        Page<ComplaintVO> page = new Page<>(query.getPageNum(), query.getPageSize());
        //判断当前登录用户级别,查询对应工单
        Optional<SystemUser> systemUserByPhone = systemUserService.getSystemUserAdminByPhone(loginUserInfoVO.getPhone());
        Long targetId = null;
        Integer accountLevel = 5;
        //获取当前身份,1=党员,2=管理员
        IdentityInformation identityInformation = identityInformationService.getCurrentIdentityInformation(loginUserInfoVO);
        Integer identity = identityInformation.getIdentity();
        query.setUserId(loginUserInfoVO.getUserId());
        //上级
        if (systemUserByPhone.isPresent() && null != identity && identity == 2) {
            SystemUser systemUser = systemUserByPhone.get();
            SystemUserLevel systemUserLevel = identityInformation.getSystemUserLevel();
            accountLevel = systemUserLevel.getLevel();
            switch (accountLevel) {
                case 1:
                    //市级
                    targetId = 510400L;
                    break;
                case 2:
                    //区县级
                    targetId = Long.valueOf(systemUserLevel.getDistrictsCode());
                    break;
                case 3:
                    //街道
                    targetId = Long.valueOf(systemUserLevel.getStreetId());
                    break;
                case 4:
                    //社区
                    targetId = systemUserLevel.getCommunityId();
                    break;
                case 5:
                    //党员
                    PartyMember partyMember = partyMemberService.getPartyMemberByPhone(loginUserInfoVO.getPhone());
                    targetId = partyMember.getId();
                    break;
            }
        } else {
            //党员
            PartyMember partyMember = partyMemberService.getPartyMemberByPhone(loginUserInfoVO.getPhone());
            targetId = partyMember.getId();
        }
        //查询对应诉求
        //page = baseMapper.selectComplaintPage(page, query, targetId, isSuperior);
        page = baseMapper.selectComplaintPage1(page, query, accountLevel, targetId);
 
        for (ComplaintVO s : page.getRecords()) {
            buttonPermission(s, systemUserByPhone, loginUserInfoVO);
            Integer auditButtonStatus = s.getAuditButtonStatus();
 
            Long reporterId = s.getReporterId();
            Long superiorId = s.getSuperiorId2();
            if (!targetId.equals(reporterId) && !targetId.equals(superiorId) && (s.getStatus() == 5)) {
                s.setStatus(0);
            }
        }
        return page;
    }
 
 
    /**
     * 列表按钮权限
     */
    public void buttonPermission(ComplaintVO vo, Optional<SystemUser> systemUserByPhone, LoginUserInfoVO loginUserInfo) {
        vo.setListControlsButtonStatus(1);
        vo.setEvaluateButtonStatus(1);
        vo.setAuditButtonStatus(1);
        // 获取身份
        IdentityInformation currentIdentityInformation = identityInformationService.getCurrentIdentityInformation(loginUserInfo);
        Integer identity = currentIdentityInformation.getIdentity();
        SystemUserLevel systemUserLevel = currentIdentityInformation.getSystemUserLevel();
        SystemUser systemUser1 = currentIdentityInformation.getSystemUser();
        ComplaintAuditRecord one = complaintAuditRecordService.getOne(new LambdaQueryWrapper<ComplaintAuditRecord>()
                .eq(ComplaintAuditRecord::getComplaintId, vo.getId())
//                .ne(ComplaintAuditRecord::getAuditType, 1)
                .orderByDesc(ComplaintAuditRecord::getSort)
                .last(" limit 0, 1"));
        //没有审核数据,且正在办理,则按钮权限是添加人员的
        if (null == one && (vo.getStatus() == 0 || vo.getStatus() == 1 || vo.getStatus() == 2)) {
      /*      if (systemUserByPhone.isPresent()) {
                SystemUser systemUser = systemUserByPhone.get();
                Integer accountLevel = systemUser.getAccountLevel();
                //当前身份是管理员
                if (2 == identity && accountLevel.compareTo(vo.getReportType()) == 0 && (accountLevel != 5)) {
                    vo.setListControlsButtonStatus(0);
                }
                //如果当前身份是党员
                if (1 == identity && 5 == vo.getReportType()) {
                    vo.setListControlsButtonStatus(0);
                }
            } else {
                if (vo.getReportType() == 5) {
                    vo.setListControlsButtonStatus(0);
                }
            }*/
            //当前身份是管理员
            if (2 == identity && systemUserLevel.getLevel().compareTo(vo.getReportType()) == 0 && (systemUserLevel.getLevel() != 5)) {
                vo.setListControlsButtonStatus(0);
            }
            //如果当前身份是党员
            if (1 == identity && 5 == vo.getReportType()) {
                vo.setListControlsButtonStatus(0);
            }
        }
        //有审核数据,且正在办理
        if (null != one && (vo.getStatus() == 0 || vo.getStatus() == 1 || vo.getStatus() == 2 || vo.getStatus() == 6)) {
            //区分是上报数据还是下派数据
            if (one.getAuditType() == 2 || one.getAuditType() == 1) {
                //判断当前审核状态
                if (one.getAuditStatus() == 1) {
                    //审核状态为通过,则权限给到上报审核的这一层
                /*    if (systemUserByPhone.isPresent() && identity == 2) {
                        SystemUser systemUser = systemUserByPhone.get();
                        Integer accountLevel = systemUser.getAccountLevel();
                        //非党员用户,必须是管理员有权限
                        if (accountLevel.compareTo(one.getReportType()) == 0) {
                            vo.setListControlsButtonStatus(0);
                        }
                    }*/
                    if (identity == 2) {
                        //非党员用户,必须是管理员有权限
                        if (systemUserLevel.getLevel().compareTo(one.getReportType()) == 0) {
                            vo.setListControlsButtonStatus(0);
                        }
                    }
                } else {
                    //没有审核通过,则需要查询上一条审核通过的数据,如果没有则给到添加诉求的人
                    ComplaintAuditRecord one1 = complaintAuditRecordService.getOne(new LambdaQueryWrapper<ComplaintAuditRecord>()
                            .eq(ComplaintAuditRecord::getComplaintId, vo.getId())
                            .eq(ComplaintAuditRecord::getAuditType, 2)
                            .eq(ComplaintAuditRecord::getAuditStatus, 1)
                            .orderByDesc(ComplaintAuditRecord::getSort)
                            .last(" limit 0, 1"));
                    if (null != one1) {
                        //非党员用户,必须是管理员有权限
                        if (identity == 2 && systemUserLevel.getLevel().compareTo(one1.getReportType()) == 0 && systemUserLevel.getLevel() != 5) {
                            vo.setListControlsButtonStatus(0);
                        }
                        /*if (systemUserByPhone.isPresent()) {
                            SystemUser systemUser = systemUserByPhone.get();
                            Integer accountLevel = systemUser.getAccountLevel();
                            Integer isAdmin = systemUser.getIsAdmin();
                            //非党员用户,必须是管理员有权限
                            if (accountLevel.compareTo(one1.getReportType()) == 0 && accountLevel != 5 && 1 == isAdmin) {
                                vo.setListControlsButtonStatus(0);
                            }
                        }*/
                    } else {
                        //没有上一层审核通过的数据,则权限给到添加人
                        /*if (systemUserByPhone.isPresent()) {
                            SystemUser systemUser = systemUserByPhone.get();
                            Integer accountLevel = systemUser.getAccountLevel();
                            Integer isAdmin = systemUser.getIsAdmin();
                            //当前身份是管理员
                            if (2 == identity && accountLevel.compareTo(vo.getReportType()) == 0 && (accountLevel != 5 && 1 == isAdmin)) {
                                vo.setListControlsButtonStatus(0);
                            }
                            //如果当前身份是党员
                            if (1 == identity && 5 == vo.getReportType()) {
                                vo.setListControlsButtonStatus(0);
                            }
                        } else {
                            if (vo.getReportType() == 5) {
                                vo.setListControlsButtonStatus(0);
                            }
                        }*/
                        //当前身份是管理员
                        if (2 == identity && systemUserLevel.getLevel().compareTo(vo.getReportType()) == 0 && (systemUserLevel.getLevel() != 5)) {
                            vo.setListControlsButtonStatus(0);
                        }
                        //如果当前身份是党员
                        if (1 == identity && 5 == vo.getReportType()) {
                            vo.setListControlsButtonStatus(0);
                        }
                    }
                }
            }
 
            //下派数据
            if (one.getAuditType() == 3) {
                //判断当前审核状态
                if (one.getAuditStatus() == 1) {
                    //审核状态为通过,则权限给到下报审核的这一层
                    /*if (systemUserByPhone.isPresent()) {
                        SystemUser systemUser = systemUserByPhone.get();
                        Integer accountLevel = systemUser.getAccountLevel();
                        Integer isAdmin = systemUser.getIsAdmin();
                        //非党员用户,必须是管理员有权限
                        if (accountLevel.compareTo(one.getReportType()) == 0 && 1 == isAdmin && 2 == identity) {
                            vo.setListControlsButtonStatus(0);
                        }
                    }*/
                    if (2 == identity && systemUserLevel.getLevel().compareTo(one.getReportType()) == 0) {
                        vo.setListControlsButtonStatus(0);
                    }
                }
            }
        }
 
        //有审核数据,且为审核中
        //审核状态为待审核,需要授权审核按钮
        if (null != one && (vo.getStatus() == 5 || vo.getStatus() == 7) && identity == 2) {
            SystemUser systemUser = systemUserByPhone.get();
            String targetId = "";
            Integer accountLevel = 5;
            //获取当前身份,1=党员,2=管理员
            accountLevel = systemUserLevel.getLevel();
            switch (accountLevel) {
                case 1:
                    //市级
                    targetId = "510400";
                    break;
                case 2:
                    //区县级
                    targetId = systemUserLevel.getDistrictsCode();
                    break;
                case 3:
                    //街道
                    targetId = systemUserLevel.getStreetId().toString();
                    break;
                case 4:
                    //社区
                    targetId = systemUserLevel.getCommunityId().toString();
                    break;
                case 5:
                    //党员
                    PartyMember partyMember = partyMemberService.getPartyMemberByPhone(systemUser.getPhone());
                    targetId = partyMember.getId().toString();
                    break;
            }
 
            ComplaintAuditRecord one2 = complaintAuditRecordService.getOne(new LambdaQueryWrapper<ComplaintAuditRecord>()
                    .eq(ComplaintAuditRecord::getComplaintId, vo.getId())
                    .eq(ComplaintAuditRecord::getLatestFlag, 1));
            if (one2.getReportType().equals(accountLevel) && one2.getSuperiorId().toString().equals(targetId)) {
                vo.setAuditButtonStatus(0);
            }
        }
 
 
        //状态为已办结,判断评价按钮
        int count = complaintCommentService.count(new LambdaQueryWrapper<ComplaintComment>().eq(ComplaintComment::getComplaintId, vo.getId()).eq(ComplaintComment::getDelFlag, 0));
        if ((vo.getStatus() == 3 || vo.getStatus() == 8) && 0 == count) {
         /*   if (systemUserByPhone.isPresent()) {
                SystemUser systemUser = systemUserByPhone.get();
                Integer accountLevel = systemUser.getAccountLevel();
                Integer isAdmin = systemUser.getIsAdmin();
                //当前不是党员身份,需要是管理员才有权限
                if (2 == identity && accountLevel.compareTo(vo.getReportType()) == 0 && accountLevel != 5 && 1 == isAdmin) {
                    vo.setEvaluateButtonStatus(0);
                }
                //当前是党员身份,只有是以党员身份提交的数据才有权限
                if (1 == identity && vo.getReportType() == 5) {
                    vo.setEvaluateButtonStatus(0);
                }
            } else {
                if (vo.getReportType() == 5) {
                    vo.setEvaluateButtonStatus(0);
                }
            }*/
            //当前不是党员身份,需要是管理员才有权限
            if (2 == identity && systemUserLevel.getLevel().compareTo(vo.getReportType()) == 0 && systemUserLevel.getLevel() != 5) {
                vo.setEvaluateButtonStatus(0);
            }
            //当前是党员身份,只有是以党员身份提交的数据才有权限
            if (1 == identity && vo.getReportType() == 5) {
                vo.setEvaluateButtonStatus(0);
            }
        }
 
        Long auditCreateBy = vo.getAuditCreateBy();
        Long userId = loginUserInfo.getUserId();
        if (null != auditCreateBy && auditCreateBy.compareTo(userId) == 0 && vo.getStatus() == 5) {
            vo.setWithdrawButtonStatus(0);
        } else {
            vo.setWithdrawButtonStatus(1);
        }
 
 
    }
 
 
    /**
     * 工单详情
     *
     * @param id
     * @return
     */
    @Override
    public ComplaintVO detail(Long id, LoginUserInfoVO loginUserInfoVO) {
        Optional<SystemUser> systemUserByPhone = systemUserService.getSystemUserAdminByPhone(loginUserInfoVO.getPhone());
        String targetId = "";
        Integer accountLevel = 5;
        //获取当前身份,1=党员,2=管理员
        IdentityInformation identityInformation = identityInformationService.getCurrentIdentityInformation(loginUserInfoVO);
        Integer identity = identityInformation.getIdentity();
        //上级
        if (identity == 2) {
            SystemUserLevel systemUserLevel = identityInformation.getSystemUserLevel();
            accountLevel = systemUserLevel.getLevel();
            switch (accountLevel) {
                case 1:
                    //市级
                    targetId = "510400";
                    break;
                case 2:
                    //区县级
                    targetId = systemUserLevel.getDistrictsCode();
                    break;
                case 3:
                    //街道
                    targetId = systemUserLevel.getStreetId().toString();
                    break;
                case 4:
                    //社区
                    targetId = systemUserLevel.getCommunityId().toString();
                    break;
                case 5:
                    //党员
                    PartyMember partyMember = partyMemberService.getPartyMemberByPhone(loginUserInfoVO.getPhone());
                    targetId = partyMember.getId().toString();
                    break;
            }
        } else {
            //党员
            PartyMember partyMember = partyMemberService.getPartyMemberByPhone(loginUserInfoVO.getPhone());
            targetId = partyMember.getId().toString();
        }
        ComplaintVO detail = baseMapper.getDetail(id);
        if (detail.getStatus().equals(0)) {
            List<ComplaintFlow> list = complaintFlowService.lambdaQuery().eq(ComplaintFlow::getComplaintId, id).orderByAsc(ComplaintFlow::getSort).list();
            detail.setComplaintFlows(list);
        }
        //查询办理进度
        List<ComplaintProgress> list = complaintProgressService.lambdaQuery().eq(ComplaintProgress::getComplaintId, id)
                .orderByAsc(ComplaintProgress::getCreateTime).list();
        detail.setComplaintProgresses(list);
 
 
        buttonPermission(detail, systemUserByPhone, loginUserInfoVO);
        Long reporterId = detail.getReporterId();
        Long superiorId = detail.getSuperiorId2();
        if (!String.valueOf(reporterId).equals(targetId) && !String.valueOf(superiorId).equals(targetId) && detail.getStatus() == 5) {
            detail.setStatus(0);
        }
 
 
//        if (auditButtonStatus == 1 && detail.getStatus() == 5 && !Objects.equals(detail.getAuditCreateBy(), loginUserInfoVO.getUserId())){
//            detail.setStatus(0);
//        }
 
 
 
 
//        //已办结,显示评价按钮
//        int count = complaintCommentService.count(new LambdaQueryWrapper<ComplaintComment>().eq(ComplaintComment::getComplaintId, detail.getId()).eq(ComplaintComment::getDelFlag, 0));
//        if(detail.getStatus() == 3 && 0 == count){
//            if(systemUserByPhone.isPresent()){
//                SystemUser systemUser = systemUserByPhone.get();
//                Integer isAdmin = systemUser.getIsAdmin();
//                if(accountLevel.compareTo(detail.getReportType()) == 0 && ((accountLevel != 5 && 1 == isAdmin) || accountLevel == 5)){
//                    detail.setEvaluateButtonStatus(0);
//                }
//            }else{
//                if(detail.getReportType() == 5){
//                    detail.setEvaluateButtonStatus(0);
//                }
//            }
//        }
        return detail;
    }
 
    /**
     * 办理进度录入
     *
     * @param dto
     * @param loginUserInfoVO
     */
    @Override
    public void saveProcess(ComplaintProcessDTO dto, LoginUserInfoVO loginUserInfoVO) {
        //获取当前身份
        IdentityInformation identityInformationVO = identityInformationService.getCurrentIdentityInformation(loginUserInfoVO);
 
        List<PermissionsVO> permissions = identityInformationVO.getPermissions();
        if (permissions.isEmpty()) {
            throw new ServiceException("请先完善个人信息");
        }
        //上级
        String name = "";
        if (identityInformationVO.getIdentity() == 2) {
            //1=党员,2=管理员
            SystemUser systemUser = identityInformationVO.getSystemUser();
            name = systemUser.getName();
        } else if (identityInformationVO.getIdentity() == 1) {
            PartyMember partyMember = identityInformationVO.getPartyMember();
            name = partyMember.getName();
        }
        ComplaintProgress complaintProgress = BeanUtil.copyProperties(dto, ComplaintProgress.class);
        complaintProgress.setCreateTime(new Date());
        complaintProgress.setCreateBy(loginUserInfoVO.getUserId());
        complaintProgress.setCreateByName(name);
        complaintProgressService.save(complaintProgress);
    }
 
    /**
     * 办理结果录入
     *
     * @param dto
     * @param loginUserInfoVO
     */
    @Override
    public void saveResult(ComplaintCompletionDTO dto, LoginUserInfoVO loginUserInfoVO) {
        //获取当前身份
        IdentityInformation identityInformationVO = identityInformationService.getCurrentIdentityInformation(loginUserInfoVO);
 
        List<PermissionsVO> permissions = identityInformationVO.getPermissions();
        if (permissions.isEmpty()) {
            throw new ServiceException("请先完善个人信息");
        }
        Integer accountLevel = null;
        String name = "";
        //上级
        if (identityInformationVO.getIdentity() == 2) {
            //1=党员,2=管理员
            SystemUser systemUser = identityInformationVO.getSystemUser();
            SystemUserLevel systemUserLevel = identityInformationVO.getSystemUserLevel();
            accountLevel = systemUserLevel.getLevel();
            name = systemUser.getName();
        } else if (identityInformationVO.getIdentity() == 1) {
            accountLevel = 5;
            PartyMember partyMember = identityInformationVO.getPartyMember();
            name = partyMember.getName();
        }
        Complaint complaint = BeanUtil.copyProperties(dto, Complaint.class);
        complaint.setUpdateTime(new Date());
        complaint.setCompletionUserId(loginUserInfoVO.getUserId());
        complaint.setCompletionUsername(name);
        complaint.setCompletionUserPhone(loginUserInfoVO.getPhone());
        complaint.setCompletionTime(new Date());
        complaint.setCompletionUserLevel(accountLevel);
        // 计算处理时间
        Date createTime = complaint.getCreateTime();
        long l = Duration.between(createTime.toInstant(), complaint.getCompletionTime().toInstant()).getSeconds() / 3600;
        double handlingDay = new BigDecimal(l).divide(new BigDecimal("24"), 2, RoundingMode.HALF_UP).doubleValue();
        complaint.setHandlingDay(handlingDay);
        this.updateById(complaint);
    }
 
    /**
     * 办理进度列表
     *
     * @param complaintId
     * @return
     */
    @Override
    public List<ComplaintProgress> progress(Long complaintId) {
        //查询办理进度
        return complaintProgressService.lambdaQuery().eq(ComplaintProgress::getComplaintId, complaintId)
                .orderByAsc(ComplaintProgress::getCreateTime).list();
    }
 
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveReport(ComplaintReportDTO dto, LoginUserInfoVO loginUserInfoVO) {
        String phone = loginUserInfoVO.getPhone();
        IdentityInformation identityInformationVO = identityInformationService.getCurrentIdentityInformation(loginUserInfoVO);
        SystemUser adminUser = identityInformationVO.getSystemUser();
        SystemUserLevel systemUserLevel = identityInformationVO.getSystemUserLevel();
 
        Long superiorId;
        int reportType;
        int reporterLevel;
        Long reporterId = null;
        String departmentName = "";
        String reporter = "";
        if (identityInformationVO.getIdentity() == 1) {
            PartyMember partyMember = partyMemberService.getPartyMemberByPhone(phone);
            superiorId = partyMember.getCommunityId();
            reporterId = partyMember.getId();
            reportType = 4;
            reporterLevel = 5;
            departmentName = partyMember.getDistricts() + "-" + partyMember.getStreet() + "-" + partyMember.getCommunity();
            reporter = partyMember.getName();
        } else if (identityInformationVO.getIdentity() == 2) {
            int accountLevel = systemUserLevel.getLevel(); // 改为基本类型
            if (accountLevel == 1) {
                throw new ServiceException("市级账号,无法上报!");
            }
            reportType = accountLevel - 1;
            reporterLevel = accountLevel;
            reporter = adminUser.getName();
 
            // 使用基本类型比较并补充默认分支
            if (accountLevel == ReportTypeEnum.COMMUNITY.getCode()) {
                superiorId = Long.parseLong(systemUserLevel.getStreetId());
                reporterId = systemUserLevel.getCommunityId();
            } else if (accountLevel == ReportTypeEnum.STREET.getCode()) {
                superiorId = Long.parseLong(systemUserLevel.getDistrictsCode());
                reporterId = Long.parseLong(systemUserLevel.getStreetId());
            } else if (accountLevel == ReportTypeEnum.DISTRICT.getCode()) {
                superiorId = 510400L; // 攀枝花市
                reporterId = Long.parseLong(systemUserLevel.getDistrictsCode());
            } else if (accountLevel == ReportTypeEnum.PARTY.getCode()) {
                superiorId = systemUserLevel.getCommunityId();
            } else {
                // 处理未预期的账号等级
                throw new ServiceException("未知的账号等级");
            }
            //查询社区信息
            switch (accountLevel) {
                case 2:
                    BcRegion region = bcRegionService.getDistrictByCode(systemUserLevel.getDistrictsCode().toString());
                    if (Objects.nonNull(region)) {
                        departmentName = region.getRegionName();
                    }
                    break;
                case 3:
                    ComStreet street = comStreetService.getById(systemUserLevel.getStreetId().toString());
                    if (Objects.nonNull(street)) {
                        BcRegion district = bcRegionService.getDistrictByCode(street.getAreaCode().toString());
                        departmentName = Objects.nonNull(district) ? district.getRegionName() + "-" + street.getName() : street.getName();
                    }
                    break;
                case 4:
                    ComAct act = comActService.getById(systemUserLevel.getCommunityId());
                    if (Objects.nonNull(act)) {
                        ComStreet street2 = comStreetService.getById(adminUser.getStreetId().toString());
                        BcRegion district = bcRegionService.getDistrictByCode(act.getAreaCode());
                        departmentName = Objects.nonNull(district) && Objects.nonNull(street2) ?
                                district.getRegionName() + "-" + street2.getName() + "-" + act.getName() : act.getName();
                    }
                    break;
            }
        } else {
            throw new ServiceException("未知的账号等级");
        }
 
        Complaint complaint = getById(dto.getComplaintId());
        if (complaint.getStatus() != 0) {
            complaint.setStatus(0);
        }
        updateById(complaint);
 
        // 标记最新
        complaintAuditRecordService.update(new LambdaUpdateWrapper<ComplaintAuditRecord>()
                .eq(ComplaintAuditRecord::getComplaintId, dto.getComplaintId())
                .set(ComplaintAuditRecord::getLatestFlag, false));
 
        // 添加审核记录
        int count = complaintAuditRecordService.count(new LambdaQueryWrapper<ComplaintAuditRecord>().eq(ComplaintAuditRecord::getComplaintId, complaint.getId()));
        ComplaintAuditRecord complaintAuditRecord = new ComplaintAuditRecord();
        complaintAuditRecord.setComplaintId(complaint.getId());
        complaintAuditRecord.setLatestFlag(true);
        complaintAuditRecord.setAuditType(2);
        complaintAuditRecord.setAuditStatus(0);
        complaintAuditRecord.setCreateBy(loginUserInfoVO.getUserId());
        complaintAuditRecord.setCreateTime(new Date());
        complaintAuditRecord.setUpdateBy(loginUserInfoVO.getUserId());
        complaintAuditRecord.setUpdateTime(new Date());
        complaintAuditRecord.setReporter(reporter);
        complaintAuditRecord.setReportType(reportType);
        complaintAuditRecord.setSuperiorId(superiorId);
        complaintAuditRecord.setComment(dto.getComment());
        complaintAuditRecord.setSort(count + 1);
        complaintAuditRecord.setDepartmentName(departmentName);
        complaintAuditRecord.setReporterLevel(reporterLevel);
        complaintAuditRecord.setReporterId(reporterId);
        complaintAuditRecord.setApplyName(reporter);
        complaintAuditRecordService.save(complaintAuditRecord);
    }
 
    @Override
    public void reportWithdraw(ComplaintReportWithdrawDTO dto, LoginUserInfoVO loginUserInfoVO) {
        ComplaintAuditRecord complaintAuditRecord = complaintAuditRecordService.getOne(new LambdaQueryWrapper<ComplaintAuditRecord>()
                .eq(ComplaintAuditRecord::getComplaintId, dto.getComplaintId())
                .eq(ComplaintAuditRecord::getAuditType, 2)
                .eq(ComplaintAuditRecord::getLatestFlag, true));
        if (Objects.isNull(complaintAuditRecord)) {
            throw new ServiceException("未找到相关记录");
        }
        complaintAuditRecord.setAuditStatus(3);
        complaintAuditRecord.setUpdateBy(loginUserInfoVO.getUserId());
        complaintAuditRecord.setUpdateTime(new Date());
        complaintAuditRecord.setLatestFlag(false);
        complaintAuditRecordService.updateById(complaintAuditRecord);
 
        // 获取上一条记录
        ComplaintAuditRecord lastRecord = complaintAuditRecordService.getOne(new LambdaQueryWrapper<ComplaintAuditRecord>()
                .ne(ComplaintAuditRecord::getId, complaintAuditRecord.getId())
                .eq(ComplaintAuditRecord::getComplaintId, dto.getComplaintId())
                .eq(ComplaintAuditRecord::getAuditType, 2)
                .eq(ComplaintAuditRecord::getLatestFlag, false)
                .orderByDesc(ComplaintAuditRecord::getSort)
        );
        if (Objects.nonNull(lastRecord)) {
            // 复制上一条记录
            ComplaintAuditRecord newRecord = new ComplaintAuditRecord();
            BeanUtils.copyProperties(lastRecord, newRecord);
            newRecord.setId(null);
            newRecord.setLatestFlag(true);
            newRecord.setUpdateBy(loginUserInfoVO.getUserId());
            newRecord.setUpdateTime(new Date());
            complaintAuditRecordService.save(newRecord);
        }
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDispatch(ComplaintDispatch dto, LoginUserInfoVO loginUserInfoVO) {
        IdentityInformation identityInformation = identityInformationService.getCurrentIdentityInformation(loginUserInfoVO);
        if (identityInformation.getIdentity() != 2) {
            throw new ServiceException("无权下派");
        }
 
        SystemUserLevel systemUserLevel = identityInformation.getSystemUserLevel();
        int accountLevel = systemUserLevel.getLevel(); // 改为基本类型
        if (accountLevel == 4) {
            throw new ServiceException("社区账号,无法下派!");
        }
        accountLevel++;
 
        Complaint complaint = getById(dto.getComplaintId());
        //查询当前单位审核记录表数据
        //查询上报审核记录
//        ComplaintAuditRecord complaintAuditRecord = complaintAuditRecordService.lambdaQuery()
//                .eq(ComplaintAuditRecord::getComplaintId, dto.getComplaintId())
//                .eq(ComplaintAuditRecord::getAuditType, 0)
//                .eq(ComplaintAuditRecord::getLatestFlag, true)
//                .eq(ComplaintAuditRecord::getReportType, adminUser.getAccountLevel())
//                .last("LIMIT 1").one();
        // 添加流转记录
//        complaintFlowService.createFlow(complaintAuditRecord, 1,loginUserInfoVO.getUserId());
        // 标记最新
        complaintAuditRecordService.update(new LambdaUpdateWrapper<ComplaintAuditRecord>()
                .eq(ComplaintAuditRecord::getComplaintId, dto.getComplaintId())
                .set(ComplaintAuditRecord::getLatestFlag, false));
        int count = complaintAuditRecordService.count(new LambdaQueryWrapper<ComplaintAuditRecord>().eq(ComplaintAuditRecord::getComplaintId, complaint.getId()));
        ComplaintAuditRecord record = new ComplaintAuditRecord();
        record.setComplaintId(complaint.getId());
        record.setLatestFlag(true);
        record.setAuditType(3);
        record.setAuditStatus(1);
        record.setCreateBy(loginUserInfoVO.getUserId());
        record.setCreateTime(new Date(System.currentTimeMillis()));
        record.setUpdateBy(loginUserInfoVO.getUserId());
        record.setUpdateTime(new Date(System.currentTimeMillis()));
        record.setReporter(loginUserInfoVO.getNickName());
        record.setReportType(accountLevel);
        record.setSuperiorId(dto.getDispatchId());
        record.setSort(count + 1);
        complaintAuditRecordService.save(record);
        ComplaintAuditRecord complaintAuditRecord = new ComplaintAuditRecord();
        complaintAuditRecord.setComplaintId(complaint.getId());
        complaintAuditRecord.setReportType(systemUserLevel.getLevel());
        Long superiorId = null;
        switch (systemUserLevel.getLevel()) {
            case 1:
                superiorId = 510400L;//默认市级
                break;
            case 2:
                superiorId = Long.parseLong(systemUserLevel.getDistrictsCode());
                break;
            case 3:
                superiorId = Long.parseLong(systemUserLevel.getStreetId());
                break;
            case 4:
                superiorId = systemUserLevel.getCommunityId();
                break;
        }
        complaintAuditRecord.setSuperiorId(superiorId);
        complaintFlowService.createFlow(complaintAuditRecord, 1, loginUserInfoVO.getUserId());
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reportAudit(ComplaintReporAuditDTO complaintReporAuditDTO, LoginUserInfoVO loginUserInfoVO) {
 
        IdentityInformation identityInformation = identityInformationService.getCurrentIdentityInformation(loginUserInfoVO);
 
        SystemUser systemUser = identityInformation.getSystemUser();
        SystemUserLevel systemUserLevel = identityInformation.getSystemUserLevel();
        if (identityInformation.getIdentity() != 2) {
            throw new ServiceException("无权审核");
        }
 
        Long superiorId = 0L;
        switch (systemUserLevel.getLevel()) {
            case 1:
                superiorId = 510400L;//默认市级
                break;
            case 2:
                superiorId = Long.parseLong(systemUserLevel.getDistrictsCode());
                break;
            case 3:
                superiorId = Long.parseLong(systemUserLevel.getStreetId());
                break;
            case 4:
                superiorId = systemUserLevel.getCommunityId();
                break;
        }
 
        //查询上报审核记录
        ComplaintAuditRecord complaintAuditRecord = complaintAuditRecordService.lambdaQuery()
                .eq(ComplaintAuditRecord::getComplaintId, complaintReporAuditDTO.getId())
                .eq(ComplaintAuditRecord::getAuditType, 2)
                .eq(ComplaintAuditRecord::getLatestFlag, true)
                .eq(ComplaintAuditRecord::getReportType, systemUserLevel.getLevel())
                .eq(ComplaintAuditRecord::getSuperiorId, superiorId)
                .last("LIMIT 1").one();
        if (Objects.isNull(complaintAuditRecord)) {
            throw new ServiceException("上报申请记录不存在");
        }
        complaintAuditRecord.setAuditorName(systemUser.getName());
        complaintAuditRecord.setAuditorPhone(systemUser.getPhone());
        complaintAuditRecord.setAuditTime(new Date());
        if (complaintReporAuditDTO.getAuditResult().equals(1)) {
            complaintAuditRecord.setAuditStatus(1);
            complaintAuditRecord.setAuditorId(loginUserInfoVO.getUserId());
            complaintAuditRecordService.updateById(complaintAuditRecord);
            //创建流程
            ComplaintAuditRecord complaintAuditRecord2 = new ComplaintAuditRecord();
            complaintAuditRecord2.setComplaintId(complaintReporAuditDTO.getId());
            complaintAuditRecord2.setSuperiorId(complaintAuditRecord.getReporterId());
            complaintAuditRecord2.setReportType(complaintAuditRecord.getReporterLevel());
            complaintFlowService.createFlow(complaintAuditRecord2, 0, loginUserInfoVO.getUserId());
        } else {
            complaintAuditRecord.setRejectReason(complaintReporAuditDTO.getRejectReason());
            complaintAuditRecord.setAuditStatus(2);
            complaintAuditRecord.setAuditorId(loginUserInfoVO.getUserId());
            complaintAuditRecordService.updateById(complaintAuditRecord);
        }
    }
 
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDelay(ComplaintDelayDTO dto, LoginUserInfoVO loginUserInfoVO) {
        IdentityInformation identityInformation = identityInformationService.getCurrentIdentityInformation(loginUserInfoVO);
 
        SystemUser systemUser = identityInformation.getSystemUser();
        SystemUserLevel systemUserLevel = identityInformation.getSystemUserLevel();
        Long superiorId;
        int reportType;
        String departmentName = "";
        String reporter = "";
        if (identityInformation.getIdentity() == 1) {
            PartyMember partyMember = partyMemberService.getPartyMemberByPhone(loginUserInfoVO.getPhone());
            superiorId = partyMember.getCommunityId();
            if (Objects.isNull(superiorId)) {
                throw new ServiceException("延期申请失败,请绑定社区");
            }
            reportType = ReportTypeEnum.COMMUNITY.getCode();
            departmentName = partyMember.getDistricts() + "-" + partyMember.getStreet() + "-" + partyMember.getCommunity();
            reporter = partyMember.getName();
        } else if (identityInformation.getIdentity() == 2) {
            int accountLevel = systemUserLevel.getLevel(); // 改为基本类型
            if (accountLevel == 1) {
                throw new ServiceException("市级账号,无法延期申请!");
            }
            reportType = accountLevel - 1;
            reporter = systemUser.getName();
 
            // 使用基本类型比较并补充默认分支
            if (accountLevel == ReportTypeEnum.COMMUNITY.getCode()) {
                superiorId = Long.parseLong(systemUserLevel.getStreetId());
            } else if (accountLevel == ReportTypeEnum.STREET.getCode()) {
                superiorId = Long.parseLong(systemUserLevel.getDistrictsCode());
            } else if (accountLevel == ReportTypeEnum.DISTRICT.getCode()) {
                superiorId = 510400L; // 攀枝花市
            } else if (accountLevel == ReportTypeEnum.PARTY.getCode()) {
                superiorId = systemUserLevel.getCommunityId();
            } else {
                // 处理未预期的账号等级
                throw new ServiceException("未知的账号等级");
            }
            //查询社区信息
            switch (accountLevel) {
                case 2:
                    BcRegion region = bcRegionService.getDistrictByCode(systemUserLevel.getDistrictsCode().toString());
                    if (Objects.nonNull(region)) {
                        departmentName = region.getRegionName();
                    }
                    break;
                case 3:
                    ComStreet street = comStreetService.getById(systemUserLevel.getStreetId().toString());
                    if (Objects.nonNull(street)) {
                        BcRegion district = bcRegionService.getDistrictByCode(street.getAreaCode().toString());
                        departmentName = Objects.nonNull(district) ? district.getRegionName() + "-" + street.getName() : street.getName();
                    }
                    break;
                case 4:
                    ComAct act = comActService.getById(systemUserLevel.getCommunityId());
                    if (Objects.nonNull(act)) {
                        ComStreet street2 = comStreetService.getById(systemUserLevel.getStreetId().toString());
                        BcRegion district = bcRegionService.getDistrictByCode(act.getAreaCode());
                        departmentName = Objects.nonNull(district) && Objects.nonNull(street2) ?
                                district.getRegionName() + "-" + street2.getName() + "-" + act.getName() : act.getName();
                    }
                    break;
            }
        } else {
            throw new ServiceException("无权申请");
        }
 
        // 清除最新记录
        complaintAuditRecordService.update(new LambdaUpdateWrapper<ComplaintAuditRecord>()
                .eq(ComplaintAuditRecord::getComplaintId, dto.getComplaintId())
                .set(ComplaintAuditRecord::getLatestFlag, false));
        int count = complaintAuditRecordService.count(new LambdaQueryWrapper<ComplaintAuditRecord>().eq(ComplaintAuditRecord::getComplaintId, dto.getComplaintId()));
        ComplaintAuditRecord record1 = new ComplaintAuditRecord();
        record1.setComplaintId(dto.getComplaintId());
        record1.setLatestFlag(true);
        record1.setAuditType(1);
        record1.setAuditStatus(0);
        record1.setCreateBy(loginUserInfoVO.getUserId());
        record1.setCreateTime(new Date(System.currentTimeMillis()));
        record1.setUpdateBy(loginUserInfoVO.getUserId());
        record1.setUpdateTime(new Date(System.currentTimeMillis()));
        record1.setReporter(reporter);
        record1.setReportType(reportType);
        record1.setSuperiorId(superiorId);
        record1.setSort(count + 1);
        record1.setComment(dto.getComment());
        record1.setDepartmentName(departmentName);
        // 冗余申请人名称
        record1.setApplyName(reporter);
        complaintAuditRecordService.save(record1);
    }
 
 
    @Override
    public void delayAudit(ComplaintDelayAuditDTO dto, LoginUserInfoVO loginUserInfoVO) {
        IdentityInformation identityInformation = identityInformationService.getCurrentIdentityInformation(loginUserInfoVO);
        SystemUser systemUser = identityInformation.getSystemUser();
        SystemUserLevel systemUserLevel = identityInformation.getSystemUserLevel();
        if (identityInformation.getIdentity() != 2) {
            throw new ServiceException("无权审核");
        }
 
        int accountLevel = systemUserLevel.getLevel(); // 改为基本类型
        Long superiorId;
        // 使用基本类型比较并补充默认分支
        if (accountLevel == ReportTypeEnum.COMMUNITY.getCode()) {
            superiorId = systemUserLevel.getCommunityId();
        } else if (accountLevel == ReportTypeEnum.STREET.getCode()) {
            superiorId = Long.parseLong(systemUserLevel.getStreetId());
        } else if (accountLevel == ReportTypeEnum.DISTRICT.getCode()) {
            superiorId = Long.parseLong(systemUserLevel.getDistrictsCode());
        } else if (accountLevel == ReportTypeEnum.CITY.getCode()) {
            superiorId = 510400L;
        } else {
            // 处理未预期的账号等级
            throw new ServiceException("未知的账号等级");
        }
 
 
        ComplaintAuditRecord complaintAuditRecord = complaintAuditRecordService.getOne(new LambdaQueryWrapper<ComplaintAuditRecord>()
                .eq(ComplaintAuditRecord::getAuditType, 1)
                .eq(ComplaintAuditRecord::getLatestFlag, 1)
                .eq(ComplaintAuditRecord::getAuditStatus, 0)
                .eq(ComplaintAuditRecord::getSuperiorId, superiorId)
                .eq(ComplaintAuditRecord::getReportType, accountLevel)
                .eq(ComplaintAuditRecord::getComplaintId, dto.getComplaintId())
                .last("LIMIT 1"));
 
 
        if (Objects.isNull(complaintAuditRecord)) {
            throw new ServiceException("诉求延期申请不存在");
        }
        complaintAuditRecord.setAuditorName(systemUser.getName());
        complaintAuditRecord.setAuditorPhone(systemUser.getPhone());
        complaintAuditRecord.setAuditTime(new Date());
        //审核通过后,设置诉求延期
        if (complaintAuditRecord.getAuditType().equals(1) && complaintAuditRecord.getAuditStatus().equals(0) && dto.getAuditResult().equals(1)) {
            Complaint complaint = getById(complaintAuditRecord.getComplaintId());
            complaint.setStatus(1);
            updateById(complaint);
 
            complaintAuditRecord.setAuditStatus(1);
            complaintAuditRecord.setAuditorId(loginUserInfoVO.getUserId());
            complaintAuditRecordService.updateById(complaintAuditRecord);
        }
        //审核不通过
        if (complaintAuditRecord.getAuditType().equals(1) && complaintAuditRecord.getAuditStatus().equals(0) && dto.getAuditResult().equals(2)) {
            complaintAuditRecord.setRejectReason(dto.getRejectReason());
            complaintAuditRecord.setAuditStatus(2);
            complaintAuditRecord.setAuditorId(loginUserInfoVO.getUserId());
            complaintAuditRecordService.updateById(complaintAuditRecord);
        }
    }
 
    @Override
    public List<DispatchVO> getDispatchList(LoginUserInfoVO loginUserInfoVO) {
 
        IdentityInformation identityInformation = identityInformationService.getCurrentIdentityInformation(loginUserInfoVO);
 
        SystemUser adminUser = identityInformation.getSystemUser();
        SystemUserLevel systemUserLevel = identityInformation.getSystemUserLevel();
 
        if (identityInformation.getIdentity() != 2) {
            throw new ServiceException("无权下派");
        }
        int accountLevel = systemUserLevel.getLevel(); // 改为基本类型
      /*  if (accountLevel == 1) {
            throw new ServiceException("市级账号,无法上报!");
        }*/
 
        // 使用基本类型比较并补充默认分支
        List<DispatchVO> dispatchVOList = new ArrayList<>();
        if (accountLevel == ReportTypeEnum.STREET.getCode()) {
            String streetId = systemUserLevel.getStreetId();
            List<ComAct> list = comActService.list(new LambdaQueryWrapper<ComAct>().eq(ComAct::getStreetId, streetId));
            for (ComAct comAct : list) {
                DispatchVO dispatchVO = new DispatchVO();
                dispatchVO.setId(comAct.getCommunityId().toString());
                dispatchVO.setName(comAct.getName());
                dispatchVOList.add(dispatchVO);
            }
        } else if (accountLevel == ReportTypeEnum.DISTRICT.getCode()) {
            String districtsCode = systemUserLevel.getDistrictsCode();
            List<ComStreet> list = comStreetService.list(new LambdaQueryWrapper<ComStreet>().eq(ComStreet::getAreaCode, districtsCode));
            for (ComStreet street : list) {
                DispatchVO dispatchVO = new DispatchVO();
                dispatchVO.setId(street.getStreetId().toString());
                dispatchVO.setName(street.getName());
                dispatchVOList.add(dispatchVO);
            }
        } else if (accountLevel == ReportTypeEnum.CITY.getCode()) {
            List<BcRegion> list = bcRegionService.list(new LambdaQueryWrapper<BcRegion>()
                    .eq(BcRegion::getHierarchyOrder, 3).eq(BcRegion::getParentId, 510400));//获取攀枝花市下的区县
            for (BcRegion region : list) {
                DispatchVO dispatchVO = new DispatchVO();
                dispatchVO.setId(region.getRegionCode());
                dispatchVO.setName(region.getRegionName());
                dispatchVOList.add(dispatchVO);
            }
        } else {
            // 处理未预期的账号等级
            throw new ServiceException("未知的账号等级");
        }
        return dispatchVOList;
    }
 
    /**
     * 获取待办诉求
     *
     * @param basePage
     * @param loginUserInfo
     * @return
     */
    @Override
    public Page<ComplaintTodoVO> getTodoList(BasePage basePage, LoginUserInfoVO loginUserInfo) {
        IdentityInformation identityInformation = identityInformationService.getCurrentIdentityInformation(loginUserInfo);
        SystemUserLevel systemUserLevel = identityInformation.getSystemUserLevel();
        String targetId = "";
        int isSuperior = 0;
        //上级
        if (identityInformation.getIdentity() == 2) {
            Integer accountLevel = systemUserLevel.getLevel();
            switch (accountLevel) {
                case 1:
                    //市级
                    targetId = "510400";
                    break;
                case 2:
                    //区县级
                    targetId = systemUserLevel.getDistrictsCode();
                    break;
                case 3:
                    //街道
                    targetId = systemUserLevel.getStreetId();
                    break;
                case 4:
                    //社区
                    targetId = systemUserLevel.getCommunityId().toString();
                    break;
            }
            isSuperior = 1;
        } else {
            //党员
            targetId = loginUserInfo.getUserId().toString();
        }
        return baseMapper.getTodoList(new Page<>(basePage.getPageNum(), basePage.getPageSize()), targetId, isSuperior);
    }
 
    /**
     * 延期情况说明
     *
     * @param complaintId
     * @return
     */
    @Override
    public ComplaintAuditRecord delayDetail(Long complaintId) {
        return complaintAuditRecordService.lambdaQuery().eq(ComplaintAuditRecord::getComplaintId, complaintId)
                .eq(ComplaintAuditRecord::getAuditType, 1)
                .eq(ComplaintAuditRecord::getLatestFlag, true)
                .last("LIMIT 1").one();
    }
 
    /**
     * 管理后台-诉求列表
     *
     * @param query
     * @param loginUserInfo
     * @return
     */
    @Override
    public Page<ComplaintVO> pageList(MgtComplaintQuery query, SystemUserVo loginUserInfo) {
        return baseMapper.pageList(new Page<>(query.getPageNum(), query.getPageSize()), query, loginUserInfo);
    }
 
    @Override
    public ComplaintVO getDetailMgt(Long id) {
        Complaint complaint = getById(id);
        ComplaintVO complaintVO = BeanUtil.copyProperties(complaint, ComplaintVO.class);
        //查询办理进度
        List<ComplaintProgress> complaintProgresses = complaintProgressService.lambdaQuery()
                .eq(ComplaintProgress::getComplaintId, id).orderByDesc(ComplaintProgress::getCreateTime).list();
        complaintVO.setComplaintProgresses(complaintProgresses);
        //查询诉求流转记录
        List<ComplaintFlow> complaintFlows = complaintFlowService.lambdaQuery()
                .eq(ComplaintFlow::getComplaintId, id)
                .orderByAsc(ComplaintFlow::getSort)
                .list();
        complaintVO.setComplaintFlows(complaintFlows);
        //查询评价
        ComplaintComment comment = complaintCommentService.lambdaQuery().eq(ComplaintComment::getComplaintId, id).last("LIMIT 1").one();
        complaintVO.setComplaintComment(comment);
        ArrayList<String> voiceFileList = new ArrayList<>();
        String voiceFile = complaint.getVoiceFile();
        if(StringUtils.isNotEmpty(voiceFile)){
            for (String file :voiceFile.split(",")) {
                voiceFileList.add(file);
            }
        }
 
        complaintVO.setVoiceFileList(voiceFileList);
        return complaintVO;
    }
 
    /**
     * 诉求列表导出
     *
     * @param query
     * @param loginUserInfo
     */
    @Override
    public void export(MgtComplaintQuery query, SystemUserVo loginUserInfo) throws IOException {
        List<ComplaintVO> list = baseMapper.getList(query, loginUserInfo);
        List<ComplaintExcel> complaintExcels = BeanUtil.copyToList(list, ComplaintExcel.class);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("诉求数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ComplaintExcel.class)
                .sheet("诉求数据")
                .registerWriteHandler(new AutoColumnWidthStrategy())
                .doWrite(complaintExcels);
    }
 
    @Override
    public String downloadFile(Long id, Integer type, SystemUserVo loginUserInfo) throws IOException {
        Complaint complaint = baseMapper.getDetailBg(id);
        if (Objects.isNull(complaint)) {
            throw new ServiceException("该诉求不存在");
        }
        //查询社区信息
        Integer reportType = complaint.getReportType();
        String community = "";
        switch (reportType) {
            case 1:
                community = "攀枝花市";
                break;
            case 2:
                BcRegion region = bcRegionService.getDistrictByCode(complaint.getDistrictsCode().toString());
                if (Objects.nonNull(region)) {
                    community = region.getRegionName();
                }
                break;
            case 3:
                ComStreet street = comStreetService.getById(complaint.getStreetId().toString());
                if (Objects.nonNull(street)) {
                    BcRegion district = bcRegionService.getDistrictByCode(street.getAreaCode().toString());
                    community = Objects.nonNull(district) ? district.getRegionName() + "-" + street.getName() : street.getName();
                }
                break;
            case 4:
                ComAct act = comActService.getById(complaint.getCommunityId());
                if (Objects.nonNull(act)) {
                    ComStreet street2 = comStreetService.getById(complaint.getStreetId().toString());
                    BcRegion district = bcRegionService.getDistrictByCode(act.getAreaCode());
                    community = Objects.nonNull(district) && Objects.nonNull(street2) ? district.getRegionName() + "-" + street2.getName() + "-" + act.getName() : act.getName();
                }
                break;
            case 5:
                ComAct act2 = comActService.getById(complaint.getCommunityId());
                if (Objects.nonNull(act2)) {
                    ComStreet street2 = comStreetService.getById(complaint.getStreetId().toString());
                    BcRegion district = bcRegionService.getDistrictByCode(act2.getAreaCode());
                    community = Objects.nonNull(district) && Objects.nonNull(street2) ? district.getRegionName() + "-" + street2.getName() + "-" + act2.getName() : act2.getName();
                }
                break;
        }
 
        PartyMember partyMember = null;
        if (Objects.nonNull(complaint.getPartyMemberId())) {
            partyMember = partyMemberService.getById(complaint.getPartyMemberId());
        }
        String fileName = "";
        switch (type) {
            case 1:
                fileName = "community_question.docx";
                break;
            case 2:
                fileName = "question_handle.docx";
                if (Objects.nonNull(partyMember)) {
                    if (StringUtil.isNotBlank(partyMember.getServiceTarget())) {
                        community = community + "-" + partyMember.getServiceTarget();
                    }
                }
                reportType = complaint.getCompletionUserLevel();
                break;
            case 3:
                //如果上报或下派了,取当前操作人的层级
                ComplaintAuditRecord record = complaintAuditRecordService.lambdaQuery().eq(ComplaintAuditRecord::getComplaintId, complaint.getId())
                        .in(ComplaintAuditRecord::getAuditType, 2, 3)
                        .eq(ComplaintAuditRecord::getAuditStatus, AuditStatusEnum.APPROVED.getCode())
                        .eq(ComplaintAuditRecord::getLatestFlag, true)
                        .last("LIMIT 1").one();
                if (Objects.nonNull(record)) {
                    reportType = record.getReportType();
                }
                fileName = "notice.docx";
                break;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("community", community);
        map.put("problemType", complaint.getProblemType());
        map.put("descriptionContent", complaint.getDescriptionContent());
        map.put("reportType", reportType == null ? "" : ReportTypeEnum.getDescriptionByCode(reportType));
        if (Objects.nonNull(partyMember)) {
            map.put("partyOrganization", StringUtil.isNotBlank(partyMember.getPartyOrganization()) ? partyMember.getPartyOrganization() : "");
        }
        map.put("name", complaint.getName());
        map.put("contactNumber", complaint.getContactNumber());
        map.put("nickname", complaint.getReportUserName());
        map.put("phone", complaint.getReportUserPhone());
        List<ComplaintProgress> list = complaintProgressService.lambdaQuery().eq(ComplaintProgress::getComplaintId, id).orderByAsc(ComplaintProgress::getCreateTime).list();
        StringBuilder sb = new StringBuilder();
        if (CollUtil.isNotEmpty(list)) {
            int rowNum = 1;
            list.forEach(item -> {
                sb.append(rowNum).append("、 ");
                sb.append(item.getDescribe()).append("\n");
            });
        }
        // 在文本中直接使用换行符
        map.put("complaintProgress", sb.toString());
        map.put("status", ComplaintExportEnum.getEnumByCode(complaint.getStatus()).getDesc());
        if (2 == type) {
            //查询诉求评价
            ComplaintComment complaintComment = complaintCommentService.lambdaQuery().eq(ComplaintComment::getComplaintId, id).last("LIMIT 1").one();
            if (Objects.nonNull(complaintComment)) {
                map.put("rateStr", RateEnum.getEnumByCode(complaintComment.getRate()).getDesc());
            }
            //map.put("departmentLevel", ReportTypeEnum.getDescriptionByCode(loginUserInfo.getAccountLevel()) + "级");
        }
        response.setContentType("application/octet-stream");
        String fileNameEncode = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename=\"" + fileNameEncode + ".docx" + "\"");
        InputStream resourceAsStream = this.getClass().getResourceAsStream("/template/" + fileName);
        XWPFTemplate.compile(resourceAsStream).render(map).writeAndClose(response.getOutputStream());
        return complaint.getName();
    }
 
 
//    public static void main(String[] args) {
//        try {
//            /*文本*/
//            Map<String, Object> map = new HashMap<>();
//            map.put("community", "社区社区");
//            map.put("problemType", "就业");
//            map.put("descriptionContent", "描述内容");
//            map.put("reportType", "党员");
//            map.put("partyOrganization", "石羊党群");
//            map.put("name", "张三");
//            map.put("contactNumber", "1888888888");
//            map.put("nickname", "李四");
//            map.put("phone", "17777777777");
//            // 在文本中直接使用换行符
//            String content = "第一行内容\n第二行内容\n第三行内容";
//            map.put("complaintProgress", content);
//            map.put("status", "处理中");
//            XWPFTemplate.compile("F:\\DeskTop\\zhihuishequ\\springcloud_k8s_panzhihuazhihuishequ\\service_sangeshenbian\\src\\main\\resources\\template\\community_question.docx").render(map).writeToFile("F:\\DeskTop\\社区.docx");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
 
 
    /**
     * 获取超时未评价的数据
     *
     * @return
     */
    @Override
    public List<Complaint> getTimeoutAndNotComment() {
        return this.baseMapper.getTimeoutAndNotComment();
    }
 
    /**
     *  修改办理进度
     * @param dto
     */
    @Override
    public void updateProgress(ComplaintProcessUpdateDto dto) {
        complaintProgressService.update(new LambdaUpdateWrapper<ComplaintProgress>().eq(ComplaintProgress::getId, dto.getId())
                .set(ComplaintProgress::getDescribe, dto.getDescribe()).set(ComplaintProgress::getImgUrl, dto.getImgUrl())
                .set(ComplaintProgress::getVideo, dto.getVideo()) )  ;
    }
 
    /**
     *  删除办理进度
     * @param
     */
    @Override
    public void delProgress(Long id) {
       complaintProgressService.removeById(id);
    }
 
    @Override
    public AnalyticStatisticsOneVo analyticStatisticsOne(AnalyticStatisticsQuery query,List<Complaint> complaints, SimpleDateFormat simpleDateFormat) {
        String nowYearMonth;
        String lastYearMonth;
        int value = LocalDate.now().getMonth().getValue();
        if(value<10){
            nowYearMonth = LocalDate.now().getYear() + "-0" + LocalDate.now().getMonth().getValue();
        }else {
            nowYearMonth = LocalDate.now().getYear() + "-" + LocalDate.now().getMonth().getValue();
        }
        int value1 = LocalDate.now().minusMonths(1).getMonth().getValue();
        if(value1<10){
            lastYearMonth = LocalDate.now().minusMonths(1).getYear() + "-0" + LocalDate.now().minusMonths(1).getMonth().getValue();
        }else {
            lastYearMonth = LocalDate.now().minusMonths(1).getYear() + "-" + LocalDate.now().minusMonths(1).getMonth().getValue();
        }
 
 
        AnalyticStatisticsOneVo vo = new AnalyticStatisticsOneVo();
 
        // 诉求单量总计
        vo.setAllTotal(complaints.size());
 
        // 诉求单量本月
        int thisMonthTotal = (int)complaints.stream().filter(e -> simpleDateFormat.format(e.getCreateTime()).contains(nowYearMonth)).count();
        vo.setThisMonthTotal( thisMonthTotal);
 
        // 诉求单量同比上月
        int lastMonthTotal = (int)complaints.stream().filter(e -> simpleDateFormat.format(e.getCreateTime()).contains(lastYearMonth)).count();
        vo.setLastMonthCompareTotal(thisMonthTotal- lastMonthTotal);
 
        // 正在办理
        int nowTransactTotal = (int) complaints.stream().filter(e -> e.getStatus() == 0).count();
        vo.setNowTransactTotal(nowTransactTotal);
 
        // 审核中
        int auditTransactTotal = (int) complaints.stream().filter(e -> e.getStatus() == 5 || e.getStatus() == 7).count();
        vo.setAuditTransactTotal(auditTransactTotal);
 
        // 延期办理
        int postponeTransactTotal = (int) complaints.stream().filter(e -> e.getStatus() == 1).count();
        vo.setPostponeTransactTotal(postponeTransactTotal);
 
        // 已办结
        int completeTransactTotal = (int) complaints.stream().filter(e -> e.getStatus() == 3).count();
        vo.setCompleteTransactTotal(completeTransactTotal);
 
        // 超时办理总量
        List<Complaint> overtimeComplaints = complaints.stream().filter(e -> e.getStatus() == 2).collect(Collectors.toList());
        vo.setOvertimeTransactTotal(overtimeComplaints.size());
 
        // 超时办理本月
        int thisMonthOvertimeTransactTotal = (int) overtimeComplaints.stream().filter(e -> simpleDateFormat.format(e.getCreateTime()).contains(nowYearMonth)).count();
        vo.setThisMonthOvertimeTransactTotal(thisMonthOvertimeTransactTotal);
 
        // 超时办理同比上月
        int lastMonthOvertimeTransactTotal = (int) overtimeComplaints.stream().filter(e -> simpleDateFormat.format(e.getCreateTime()).contains(lastYearMonth)).count();
        vo.setLastMonthOvertimeTransactCompareTotal(thisMonthOvertimeTransactTotal-lastMonthOvertimeTransactTotal);
 
        // 平均处理时长
        if(complaints.size()>0) {
            double averageDay = complaints.stream().mapToDouble(v -> v.getHandlingDay() == null ? 0 : v.getHandlingDay()).average().getAsDouble();
            averageDay = BigDecimal.valueOf(averageDay).setScale(2, RoundingMode.HALF_UP).doubleValue();
            vo.setAverageTime(averageDay);
 
            List<Complaint> thisMonthAverageTimeComplaints = complaints.stream().filter(e -> simpleDateFormat.format(e.getCreateTime()).contains(nowYearMonth)).collect(Collectors.toList());
            if(thisMonthAverageTimeComplaints.size()>0){
                double thisMonthAverageTime = thisMonthAverageTimeComplaints.stream().mapToDouble(v -> v.getHandlingDay() == null ? 0 : v.getHandlingDay()).average().getAsDouble();
                thisMonthAverageTime = BigDecimal.valueOf(thisMonthAverageTime).setScale(2, RoundingMode.HALF_UP).doubleValue();
                vo.setThisMonthAverageTime(thisMonthAverageTime);
            }
            List<Complaint> lastMonthAverageTimeComplaints = complaints.stream().filter(e -> simpleDateFormat.format(e.getCreateTime()).contains(lastYearMonth)).collect(Collectors.toList());
            if(lastMonthAverageTimeComplaints.size()>0){
                double lastMonthAverageTime = lastMonthAverageTimeComplaints.stream().mapToDouble(v -> v.getHandlingDay() == null ? 0 : v.getHandlingDay()).average().getAsDouble();
                lastMonthAverageTime = BigDecimal.valueOf(lastMonthAverageTime).setScale(2, RoundingMode.HALF_UP).doubleValue();
                vo.setAverageTime(vo.getThisMonthAverageTime() - lastMonthAverageTime);
            }
 
        }
        // 获取评价了的诉求
        List<Complaint> commentRateComplaints = complaints.stream().filter(e -> e.getCommentRate() != null).collect(Collectors.toList());
        long count = commentRateComplaints.stream().filter(e -> e.getCommentRate() > 1).count();
        int size = commentRateComplaints.size();
        if(size>0){
            BigDecimal multiply = BigDecimal.valueOf(count).divide(new BigDecimal(size), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));
            vo.setSatisfactionRate(multiply.doubleValue());
 
            List<Complaint> nowMonth = commentRateComplaints.stream().filter(e -> simpleDateFormat.format(e.getCreateTime()).contains(nowYearMonth)).collect(Collectors.toList());
            // 当月满意
            long count1 = nowMonth.stream().filter(e -> e.getCommentRate() > 1).count();
            // 当月的评价数
            int nowMonthSize = nowMonth.size();
            if(nowMonthSize>0){
                BigDecimal multiply1 = BigDecimal.valueOf(count1).divide(new BigDecimal(nowMonthSize), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));
                vo.setThisMonthSatisfactionRate(multiply1.doubleValue());
            }
 
            List<Complaint> lastMonth = commentRateComplaints.stream().filter(e -> simpleDateFormat.format(e.getCreateTime()).contains(nowYearMonth)).collect(Collectors.toList());
            // 当月满意
            long count2 = lastMonth.stream().filter(e -> e.getCommentRate() > 1).count();
            // 当月的评价数
            int lastMonthSize = lastMonth.size();
            if(lastMonthSize>0){
                BigDecimal multiply2 = BigDecimal.valueOf(count2).divide(new BigDecimal(lastMonthSize), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));
                vo.setLastMonthCompareSatisfactionRate(vo.getThisMonthSatisfactionRate()-multiply2.doubleValue());
            }
        }
        return vo;
    }
 
    @Override
    public List<AnalyticStatisticsTwoVo> analyticStatisticsTwo(AnalyticStatisticsQuery query, List<Complaint> complaints, SimpleDateFormat simpleDateFormat) {
        ArrayList<AnalyticStatisticsTwoVo> list = new ArrayList<>();
        try {
            if (StringUtils.isNotEmpty(query.getTime())) {
                String[] split = query.getTime().split(" - ");
                Date parse = simpleDateFormat.parse(split[0] + " 00:00:00");
                Date parse1 = simpleDateFormat.parse(split[1] + " 23:59:59");
                complaints = complaints.stream().filter(e -> e.getCreateTime().getTime() <= parse1.getTime() && e.getCreateTime().getTime() >= parse.getTime()).collect(Collectors.toList());
                int day = DateUtils.getDay(parse, parse1);
                if(day>30){
                    throw new ServiceException("时间范围不能超过30天");
                }
 
                for (int i = 0; i <= day; i++) {
                    AnalyticStatisticsTwoVo analyticStatisticsTwoVo = new AnalyticStatisticsTwoVo();
                    if(i==0){
                        List<Complaint> collect = complaints.stream().filter(e -> simpleDateFormat.format(e.getCreateTime()).contains(split[0])).collect(Collectors.toList());
                        analyticStatisticsTwoVo.setTime(split[0]);
                        analyticStatisticsTwoVo.setAllTotal(collect.size());
                        int count = (int) collect.stream().filter(e -> e.getStatus() == 3).count();
                        analyticStatisticsTwoVo.setCompleteTotal(count);
                        list.add(analyticStatisticsTwoVo);
                    }else {
                        String nextDay = DateUtils.getNextDay(parse, i);
                        List<Complaint> collect = complaints.stream().filter(e -> simpleDateFormat.format(e.getCreateTime()).contains(nextDay)).collect(Collectors.toList());
                        analyticStatisticsTwoVo.setTime(nextDay);
                        analyticStatisticsTwoVo.setAllTotal(collect.size());
                        int count = (int) collect.stream().filter(e -> e.getStatus() == 3).count();
                        analyticStatisticsTwoVo.setCompleteTotal(count);
                        list.add(analyticStatisticsTwoVo);
                    }
                }
 
            } else {
                String time = DateUtils.getBeforeDay(6) + " 00:00:00";
                Date parse = simpleDateFormat.parse(time);
                // 近7天数据
                complaints = complaints.stream().filter(e -> e.getCreateTime().getTime() <= new Date().getTime() && e.getCreateTime().getTime() >= parse.getTime()).collect(Collectors.toList());
 
                for (int i = 6; i > 0; i--) {
                    // 获取前7天的时间
                    String day = DateUtils.getBeforeDay(i);
                    List<Complaint> complaintList = complaints.stream().filter(e -> simpleDateFormat.format(e.getCreateTime()).contains(day)).collect(Collectors.toList());
                    AnalyticStatisticsTwoVo analyticStatisticsTwoVo = new AnalyticStatisticsTwoVo();
                    analyticStatisticsTwoVo.setTime(day);
                    analyticStatisticsTwoVo.setAllTotal(complaintList.size());
                    int count = (int) complaintList.stream().filter(e -> e.getStatus() == 3).count();
                    analyticStatisticsTwoVo.setCompleteTotal(count);
                    list.add(analyticStatisticsTwoVo);
                }
 
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return list;
    }
 
    @Override
    public List<AnalyticStatisticsThreeVo> analyticStatisticsThree(AnalyticStatisticsQuery query, List<Complaint> complaints) {
        Map<String, List<Complaint>> groupedByProblemType = complaints.stream()
                .collect(Collectors.groupingBy(Complaint::getProblemType));
        List<AnalyticStatisticsThreeVo> analyticStatisticsThreeVos = groupedByProblemType.entrySet().stream()
                .map(entry -> {
                    AnalyticStatisticsThreeVo analyticStatisticsThreeVo = new AnalyticStatisticsThreeVo();
                    analyticStatisticsThreeVo.setName(entry.getKey());
                    analyticStatisticsThreeVo.setAllTotal(entry.getValue().size());
                    return analyticStatisticsThreeVo;
                })
                .collect(Collectors.toList());
        analyticStatisticsThreeVos = analyticStatisticsThreeVos.stream().sorted(Comparator.comparing(AnalyticStatisticsThreeVo::getAllTotal).reversed()).collect(Collectors.toList());
        if(query.getRank()==null){
            return analyticStatisticsThreeVos;
        }else if(query.getRank()==5){
           return analyticStatisticsThreeVos.stream().limit(5).collect(Collectors.toList());
        }else if(query.getRank()==10){
            return analyticStatisticsThreeVos.stream().limit(10).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }
 
    @Override
    public AnalyticStatisticsFourVo analyticStatisticsFour(List<Complaint> complaints) {
        AnalyticStatisticsFourVo vo = new AnalyticStatisticsFourVo();
        // 0:不满意 1:一般 2:满意 3:非常满意
        long count = complaints.stream().filter(e -> e.getCommentRate() != null && e.getCommentRate() == 0).count();
        long count1 = complaints.stream().filter(e -> e.getCommentRate() != null && e.getCommentRate() == 1).count();
        long count2 = complaints.stream().filter(e -> e.getCommentRate() != null && e.getCommentRate() == 2).count();
        long count3 = complaints.stream().filter(e -> e.getCommentRate() != null && e.getCommentRate() == 3).count();
        vo.setDissatisfactionRate(BigDecimal.valueOf(count).divide(BigDecimal.valueOf(complaints.size()), 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100")).doubleValue());
        vo.setGeneralSatisfactionRate(BigDecimal.valueOf(count1).divide(BigDecimal.valueOf(complaints.size()), 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100")).doubleValue());
        vo.setSatisfactionRate(BigDecimal.valueOf(count2).divide(BigDecimal.valueOf(complaints.size()), 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100")).doubleValue());
        vo.setGreatSatisfactionRate(BigDecimal.valueOf(count3).divide(BigDecimal.valueOf(complaints.size()), 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100")).doubleValue());
 
        return vo;
    }
 
 
}