mitao
2025-03-16 44c6754be97b8772a915f7bc54b44ac736c7673b
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
package com.panzhihua.sangeshenbian.service.impl;
 
import cn.hutool.core.bean.BeanUtil;
import cn.idev.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
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.deepoove.poi.XWPFTemplate;
import com.panzhihua.common.model.vos.LoginUserInfoVO;
import com.panzhihua.common.model.vos.sangeshenbian.SystemUserVo;
import com.panzhihua.sangeshenbian.model.dto.ComplaintCompletionDTO;
import com.panzhihua.sangeshenbian.model.dto.ComplaintProcessDTO;
import com.panzhihua.sangeshenbian.model.entity.Complaint;
import com.panzhihua.common.exceptions.ServiceException;
import com.panzhihua.sangeshenbian.enums.ReportTypeEnum;
import com.panzhihua.sangeshenbian.model.dto.*;
import com.panzhihua.sangeshenbian.model.entity.*;
import com.panzhihua.sangeshenbian.enums.ProcessStatusEnum;
import com.panzhihua.sangeshenbian.dao.ComplaintMapper;
import com.panzhihua.sangeshenbian.model.entity.ComplaintFlow;
import com.panzhihua.sangeshenbian.model.entity.ComplaintProgress;
import com.panzhihua.sangeshenbian.model.entity.SystemUser;
import com.panzhihua.sangeshenbian.model.excel.ComplaintExcel;
import com.panzhihua.sangeshenbian.model.excel.PartyMemberExcel;
import com.panzhihua.sangeshenbian.model.query.BasePage;
import com.panzhihua.sangeshenbian.model.query.ComplaintQuery;
import com.panzhihua.sangeshenbian.model.vo.ComplaintTodoVO;
import com.panzhihua.sangeshenbian.service.IComplaintFlowService;
import com.panzhihua.sangeshenbian.service.IComplaintProgressService;
import com.panzhihua.sangeshenbian.service.IComplaintService;
import com.panzhihua.sangeshenbian.model.vo.DispatchVO;
import com.panzhihua.sangeshenbian.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.panzhihua.sangeshenbian.model.vo.ComplaintVO;
import com.panzhihua.sangeshenbian.service.ISystemUserService;
import com.panzhihua.sangeshenbian.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
 
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;
 
    @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);
        Optional<SystemUser> systemUserOpt = systemUserService.getSystemUserAdminByPhone(loginUserInfoVO.getPhone());
        Integer accountLevel = 5;
        Long superiorId = null;
        if (systemUserOpt.isPresent()) {
            SystemUser systemUser = systemUserOpt.get();
            accountLevel = systemUser.getAccountLevel();
            switch (accountLevel) {
                case 1:
                    //市级
                    superiorId = 510400L;
                    break;
                case 2:
                    //区县级
                    superiorId = Long.parseLong(systemUser.getDistrictsCode());
                    break;
                case 3:
                    //街道
                    superiorId = Long.parseLong(systemUser.getStreetId());
                    break;
                case 4:
                    //社区
                    superiorId = systemUser.getCommunityId();
                    break;
                case 5:
                    //社区
                    superiorId = loginUserInfoVO.getUserId();
                    break;
            }
            complaint.setSuperiorType(accountLevel);
            complaint.setSuperiorId(superiorId);
        }else{
            superiorId = loginUserInfoVO.getUserId();
        }
        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);
        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(0);
        complaintAuditRecord.setAuditStatus(-1);
        complaintAuditRecord.setCreateBy(loginUserInfoVO.getUserId());
        complaintAuditRecord.setCreateTime(new Date(System.currentTimeMillis()));
        complaintAuditRecord.setUpdateBy(loginUserInfoVO.getUserId());
        complaintAuditRecord.setUpdateTime(new Date(System.currentTimeMillis()));
        complaintAuditRecord.setReportType(accountLevel);
        complaintAuditRecord.setSuperiorId(superiorId);
        complaintAuditRecord.setSort(count + 1);
        complaintAuditRecordService.save(complaintAuditRecord);
    }
 
    /**
     * @param query
     * @param loginUserInfoVO
     * @return
     */
    @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());
        String targetId = "";
        int isSuperior = 0;
        Integer accountLevel = 5;
        //上级
        if (systemUserByPhone.isPresent()) {
            SystemUser systemUser = systemUserByPhone.get();
            accountLevel = systemUser.getAccountLevel();
            switch (accountLevel) {
                case 1:
                    //市级
                    targetId = "510400";
                    break;
                case 2:
                    //区县级
                    targetId = systemUser.getDistrictsCode();
                    break;
                case 3:
                    //街道
                    targetId = systemUser.getStreetId().toString();
                    break;
                case 4:
                    //社区
                    targetId = systemUser.getCommunityId().toString();
                    break;
                case 5:
                    //党员
                    targetId = loginUserInfoVO.getUserId().toString();
                    break;
            }
            isSuperior = 1;
        } else {
            //党员
            targetId = loginUserInfoVO.getUserId().toString();
        }
        //查询对应诉求
        //page = baseMapper.selectComplaintPage(page, query, targetId, isSuperior);
        page = baseMapper.selectComplaintPage1(page, query, accountLevel, targetId);
        return page;
    }
 
    /**
     * 工单详情
     *
     * @param id
     * @return
     */
    @Override
    public ComplaintVO detail(Long id, LoginUserInfoVO loginUserInfoVO) {
        Optional<SystemUser> systemUserByPhone = systemUserService.getSystemUserAdminByPhone(loginUserInfoVO.getPhone());
        String targetId = "";
        int isSuperior = 0;
        Integer accountLevel = 5;
        //上级
        if (systemUserByPhone.isPresent()) {
            SystemUser systemUser = systemUserByPhone.get();
            accountLevel = systemUser.getAccountLevel();
            switch (accountLevel) {
                case 1:
                    //市级
                    targetId = "510400";
                    break;
                case 2:
                    //区县级
                    targetId = systemUser.getDistrictsCode();
                    break;
                case 3:
                    //街道
                    targetId = systemUser.getStreetId().toString();
                    break;
                case 4:
                    //社区
                    targetId = systemUser.getCommunityId().toString();
                    break;
                case 5:
                    //社区
                    targetId = loginUserInfoVO.getUserId().toString();
                    break;
            }
            isSuperior = 1;
        } else {
            //党员
            targetId = loginUserInfoVO.getUserId().toString();
        }
 
 
        ComplaintVO detail = baseMapper.getDetail(id,targetId, isSuperior);
        if (detail.getStatus().equals(0)) {
            List<ComplaintFlow> list = complaintFlowService.lambdaQuery().eq(ComplaintFlow::getComplaintId, id).orderByAsc(ComplaintFlow::getCreateTime).list();
            detail.setComplaintFlows(list);
        }
        //查询办理进度
        List<ComplaintProgress> list = complaintProgressService.lambdaQuery().eq(ComplaintProgress::getComplaintId, id)
                .orderByAsc(ComplaintProgress::getCreateTime).list();
        detail.setComplaintProgresses(list);
        detail.setAuditButtonStatus(1);
        Long superiorId = detail.getSuperiorId();
        Integer superiorType = detail.getSuperiorType();
        if((detail.getStatus() == 5 || detail.getStatus() == 7) && systemUserByPhone.isPresent()){
            if(superiorType.equals(accountLevel) && superiorId.toString().equals(targetId)){
                detail.setAuditButtonStatus(0);
            }
        }
 
        return detail;
    }
 
    /**
     * 办理进度录入
     *
     * @param dto
     * @param loginUserInfoVO
     */
    @Override
    public void saveProcess(ComplaintProcessDTO dto, LoginUserInfoVO loginUserInfoVO) {
        ComplaintProgress complaintProgress = BeanUtil.copyProperties(dto, ComplaintProgress.class);
        complaintProgress.setCreateTime(new Date());
        complaintProgress.setCreateBy(loginUserInfoVO.getUserId());
        complaintProgress.setCreateByName(loginUserInfoVO.getNickName());
        complaintProgressService.save(complaintProgress);
    }
 
    /**
     * 办理结果录入
     *
     * @param dto
     * @param loginUserInfoVO
     */
    @Override
    public void saveResult(ComplaintCompletionDTO dto, LoginUserInfoVO loginUserInfoVO) {
        Complaint complaint = BeanUtil.copyProperties(dto, Complaint.class);
        complaint.setUpdateTime(new Date());
        complaint.setCompletionUserId(loginUserInfoVO.getUserId());
        complaint.setCompletionUsername(loginUserInfoVO.getNickName());
        complaint.setCompletionUserPhone(loginUserInfoVO.getPhone());
        complaint.setCompletionTime(new Date());
        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) {
        log.info("用户登录数据----------------》" + JSON.toJSONString(loginUserInfoVO));
        String phone = loginUserInfoVO.getPhone();
 
        SystemUser adminUser = systemUserService.getOne(new LambdaQueryWrapper<SystemUser>()
                .eq(SystemUser::getPhone, phone)
                .eq(SystemUser::getIsAdmin, 1)
                .ne(SystemUser::getStatus, 3)
                .last("LIMIT 1"));
 
        Long superiorId;
        Long currentId;
        int reportType;
        if (adminUser == null) {
            superiorId = loginUserInfoVO.getCommunityId();
            currentId = 0L;
            if (Objects.isNull(superiorId)) {
                throw new ServiceException("上报失败,请绑定社区");
            }
            reportType = ReportTypeEnum.COMMUNITY.getCode();
            currentId = loginUserInfoVO.getUserId();
        } else {
            int accountLevel = adminUser.getAccountLevel(); // 改为基本类型
            if (accountLevel == 1) {
                throw new ServiceException("市级账号,无法上报!");
            }
            reportType = accountLevel - 1;
 
            // 使用基本类型比较并补充默认分支
            if (accountLevel == ReportTypeEnum.COMMUNITY.getCode()) {
                superiorId = Long.parseLong(adminUser.getStreetId());
                currentId = adminUser.getCommunityId();
            } else if (accountLevel == ReportTypeEnum.STREET.getCode()) {
                superiorId = Long.parseLong(adminUser.getDistrictsCode());
                currentId = Long.valueOf(adminUser.getStreetId());
            } else if (accountLevel == ReportTypeEnum.DISTRICT.getCode()) {
                superiorId = 510400L; // 攀枝花市
                currentId = Long.valueOf(adminUser.getDistrictsCode());
            } else if(accountLevel == ReportTypeEnum.PARTY.getCode()){
                superiorId = adminUser.getCommunityId();
                currentId = loginUserInfoVO.getUserId();
            } else {
                // 处理未预期的账号等级
                throw new ServiceException("未知的账号等级");
            }
        }
 
        Complaint complaint = getById(dto.getComplaintId());
        //complaint.setReportType(+);
        complaint.setSuperiorType(reportType);
        complaint.setSuperiorId(superiorId);
        if (complaint.getStatus() != 0) {
            complaint.setStatus(0);
        }
        updateById(complaint);
 
        // 标记最新
        complaintAuditRecordService.update(new LambdaUpdateWrapper<ComplaintAuditRecord>()
                .eq(ComplaintAuditRecord::getComplaintId, dto.getComplaintId())
                .set(ComplaintAuditRecord::getLatestFlag, false));
 
        // 添加审核记录
        //complaintAuditRecordService.createComplaintAuditRecord(dto.getComplaintId(), 2, dto.getComment(), loginUserInfoVO,adminUser);
        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(loginUserInfoVO.getNickName());
        complaintAuditRecord.setReportType(Objects.isNull(adminUser) ? 5 : adminUser.getAccountLevel());
        complaintAuditRecord.setSuperiorId(currentId);
        complaintAuditRecord.setComment(dto.getComment());
        complaintAuditRecord.setSort(count + 1);
        complaintAuditRecordService.save(complaintAuditRecord);
 
 
        ComplaintAuditRecord complaintAuditRecord2 = new ComplaintAuditRecord();
        complaintAuditRecord2.setComplaintId(complaint.getId());
        complaintAuditRecord2.setLatestFlag(true);
        complaintAuditRecord2.setAuditType(2);
        complaintAuditRecord2.setAuditStatus(0);
        complaintAuditRecord2.setCreateBy(loginUserInfoVO.getUserId());
        complaintAuditRecord2.setCreateTime(new Date());
        complaintAuditRecord2.setUpdateBy(loginUserInfoVO.getUserId());
        complaintAuditRecord2.setUpdateTime(new Date());
        complaintAuditRecord2.setReporter(loginUserInfoVO.getNickName());
        complaintAuditRecord2.setReportType(reportType);
        complaintAuditRecord2.setSuperiorId(superiorId);
        complaintAuditRecord2.setComment(dto.getComment());
        complaintAuditRecord2.setSort(count + 2);
        complaintAuditRecordService.save(complaintAuditRecord2);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDispatch(ComplaintDispatch dto, LoginUserInfoVO loginUserInfoVO) {
        String phone = loginUserInfoVO.getPhone();
        SystemUser adminUser = systemUserService.getOne(new LambdaQueryWrapper<SystemUser>()
                .eq(SystemUser::getPhone, phone)
                .eq(SystemUser::getIsAdmin, 1)
                .ne(SystemUser::getStatus, 3)
                .last("LIMIT 1"));
 
        if (adminUser == null) {
            throw new ServiceException("无权下派");
        }
 
        int accountLevel = adminUser.getAccountLevel(); // 改为基本类型
        if (accountLevel == 4) {
            throw new ServiceException("社区账号,无法下派!");
        }
        accountLevel++;
 
        Complaint complaint = getById(dto.getComplaintId());
        complaint.setSuperiorType(accountLevel);
        complaint.setSuperiorId(dto.getDispatchId());
        updateById(complaint);
        Long superiorOrgId = complaint.getSuperiorId();
        Integer superiorType = complaint.getSuperiorType();
        //查询当前单位审核记录表数据
        //查询上报审核记录
        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(0);
        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);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reportAudit(ComplaintReporAuditDTO complaintReporAuditDTO, LoginUserInfoVO loginUserInfoVO) {
        Optional<SystemUser> systemUserByPhone = systemUserService.getSystemUserAdminByPhone(loginUserInfoVO.getPhone());
        if (!systemUserByPhone.isPresent()) {
            throw new ServiceException("无权审核");
        }
 
        SystemUser systemUser = systemUserByPhone.get();
        Long superiorId = 0L;
        switch (systemUser.getAccountLevel()) {
            case 1:
                superiorId = 510400L;//默认市级
                break;
            case 2:
                superiorId = Long.parseLong(systemUser.getDistrictsCode());
                break;
            case 3:
                superiorId = Long.parseLong(systemUser.getStreetId());
                break;
            case 4:
                superiorId = systemUser.getCommunityId();
                break;
        }
 
        //查询上报审核记录
        ComplaintAuditRecord complaintAuditRecord = complaintAuditRecordService.lambdaQuery()
                .eq(ComplaintAuditRecord::getComplaintId, complaintReporAuditDTO.getId())
                .eq(ComplaintAuditRecord::getAuditType, 2)
                .eq(ComplaintAuditRecord::getLatestFlag, true)
                .eq(ComplaintAuditRecord::getReportType, systemUser.getAccountLevel())
                .eq(ComplaintAuditRecord::getSuperiorId, superiorId)
                .last("LIMIT 1").one();
        ComplaintAuditRecord lowLevelRecord = complaintAuditRecordService.lambdaQuery()
                .eq(ComplaintAuditRecord::getComplaintId, complaintReporAuditDTO.getId())
                .eq(ComplaintAuditRecord::getAuditType, 2)
                .eq(ComplaintAuditRecord::getLatestFlag, true)
                .eq(ComplaintAuditRecord::getReportType, systemUser.getAccountLevel()+1)
                .last("LIMIT 1").one();
        if (Objects.isNull(complaintAuditRecord)) {
            throw new ServiceException("上报申请记录不存在");
        }
        //查询待审核诉求
        //complaintAuditRecordService.audit(complaintAuditRecord,  loginUserInfoVO.getUserId(),
        //        complaintReporAuditDTO.getAuditResult(), complaintReporAuditDTO.getRejectReason());
 
        // 添加流转记录
        Complaint complaint = getById(complaintAuditRecord.getComplaintId());
 
        // 标记最新
        complaintAuditRecordService.update(new LambdaUpdateWrapper<ComplaintAuditRecord>()
                .eq(ComplaintAuditRecord::getComplaintId, complaintAuditRecord.getComplaintId())
                .set(ComplaintAuditRecord::getLatestFlag, false));
 
        if (complaintReporAuditDTO.getAuditResult().equals(1)) {
            int count = complaintAuditRecordService.count(new LambdaQueryWrapper<ComplaintAuditRecord>().eq(ComplaintAuditRecord::getComplaintId, complaint.getId()));
            ComplaintAuditRecord record = new ComplaintAuditRecord();
            record.setComplaintId(complaint.getId());
            record.setLatestFlag(true);
            record.setAuditorId(loginUserInfoVO.getUserId());
            record.setAuditType(2);
            record.setAuditStatus(1);
            record.setCreateBy(loginUserInfoVO.getUserId());
            record.setCreateTime(new Date());
            record.setUpdateBy(loginUserInfoVO.getUserId());
            record.setUpdateTime(new Date());
            record.setReporter(complaintAuditRecord.getReporter());
            record.setReportType(complaintAuditRecord.getReportType());
            record.setSuperiorId(superiorId);
            record.setSort(count + 1);
            complaintAuditRecordService.save(record);
            //创建流程
            complaintFlowService.createFlow(lowLevelRecord ,0, loginUserInfoVO.getUserId());
        } else {
 
            switch (systemUser.getAccountLevel() + 1) {
                case 1:
                    superiorId = 510400L;//默认市级
                    break;
                case 2:
                    superiorId = Long.parseLong(systemUser.getDistrictsCode());
                    break;
                case 3:
                    superiorId = Long.parseLong(systemUser.getStreetId());
                    break;
                case 4:
                    superiorId = systemUser.getCommunityId();
                    break;
                case 5:
                    superiorId = complaint.getCreateBy();
                    break;
            }
            int count = complaintAuditRecordService.count(new LambdaQueryWrapper<ComplaintAuditRecord>().eq(ComplaintAuditRecord::getComplaintId, complaint.getId()));
            ComplaintAuditRecord record2 = new ComplaintAuditRecord();
            record2.setComplaintId(complaint.getId());
            record2.setLatestFlag(true);
            record2.setAuditType(2);
            record2.setAuditorId(loginUserInfoVO.getUserId());
            record2.setAuditStatus(2);
            record2.setCreateBy(loginUserInfoVO.getUserId());
            record2.setCreateTime(new Date());
            record2.setUpdateBy(loginUserInfoVO.getUserId());
            record2.setUpdateTime(new Date());
            record2.setReporter(complaintAuditRecord.getReporter());
            record2.setReportType(systemUser.getAccountLevel() + 1);
            record2.setSuperiorId(superiorId);
            record2.setRejectReason(complaintReporAuditDTO.getRejectReason());
            record2.setSort(count + 1);
            complaintAuditRecordService.save(record2);
        }
    }
 
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDelay(ComplaintDelayDTO dto, LoginUserInfoVO loginUserInfoVO) {
        SystemUser systemUser = systemUserService.getSystemUserAdminByPhone(loginUserInfoVO.getPhone()).orElse(null);
        Long superiorId;
        Long currentId;
        int reportType;
        if (systemUser == null) {
            superiorId = loginUserInfoVO.getCommunityId();
            currentId = loginUserInfoVO.getUserId();
            if (Objects.isNull(superiorId)) {
                throw new ServiceException("上报失败,请绑定社区");
            }
            reportType = ReportTypeEnum.COMMUNITY.getCode();
        } else {
            int accountLevel = systemUser.getAccountLevel(); // 改为基本类型
            if (accountLevel == 1) {
                throw new ServiceException("市级账号,无法上报!");
            }
            reportType = accountLevel - 1;
 
            // 使用基本类型比较并补充默认分支
            if (accountLevel == ReportTypeEnum.COMMUNITY.getCode()) {
                superiorId = Long.parseLong(systemUser.getStreetId());
                currentId = systemUser.getCommunityId();
            } else if (accountLevel == ReportTypeEnum.STREET.getCode()) {
                superiorId = Long.parseLong(systemUser.getDistrictsCode());
                currentId = Long.parseLong(systemUser.getStreetId());
            } else if (accountLevel == ReportTypeEnum.DISTRICT.getCode()) {
                superiorId = 510400L; // 攀枝花市
                currentId = Long.parseLong(systemUser.getDistrictsCode());
            } else if (accountLevel == ReportTypeEnum.PARTY.getCode()) {
                superiorId = systemUser.getCommunityId();
                currentId = loginUserInfoVO.getUserId();
            } else {
                // 处理未预期的账号等级
                throw new ServiceException("未知的账号等级");
            }
        }
 
        Complaint complaint = getById(dto.getComplaintId());
        complaint.setSuperiorType(reportType);
        complaint.setSuperiorId(superiorId);
        updateById(complaint);
        // 添加审核记录
        //complaintAuditRecordService.createComplaintAuditRecord(dto.getComplaintId(), 1, dto.getComment(), loginUserInfoVO, systemUser);
 
        // 清除最新记录
        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 record1 = new ComplaintAuditRecord();
        record1.setComplaintId(complaint.getId());
        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(loginUserInfoVO.getNickName());
        record1.setReportType(Objects.isNull(systemUser) ? 5 : systemUser.getAccountLevel());
        record1.setSuperiorId(currentId);
        record1.setSort(count + 1);
        record1.setComment(dto.getComment());
        complaintAuditRecordService.save(record1);
 
        ComplaintAuditRecord record2 = new ComplaintAuditRecord();
        record2.setComplaintId(complaint.getId());
        record2.setLatestFlag(true);
        record2.setAuditType(1);
        record2.setAuditStatus(0);
        record2.setCreateBy(loginUserInfoVO.getUserId());
        record2.setCreateTime(new Date(System.currentTimeMillis()));
        record2.setUpdateBy(loginUserInfoVO.getUserId());
        record2.setUpdateTime(new Date(System.currentTimeMillis()));
        record2.setReporter(loginUserInfoVO.getNickName());
        record2.setReportType(reportType);
        record2.setSuperiorId(superiorId);
        record2.setSort(count + 2);
        record1.setComment(dto.getComment());
        complaintAuditRecordService.save(record2);
    }
 
 
    @Override
    public void delayAudit(ComplaintDelayAuditDTO dto, LoginUserInfoVO loginUserInfoVO) {
 
        SystemUser systemUser = systemUserService.getSystemUserAdminByPhone(loginUserInfoVO.getPhone()).orElse(null);
 
        int accountLevel = systemUser.getAccountLevel(); // 改为基本类型
        Long cunrrentId;
        // 使用基本类型比较并补充默认分支
        if (accountLevel == ReportTypeEnum.COMMUNITY.getCode()) {
            cunrrentId = systemUser.getCommunityId();
        } else if (accountLevel == ReportTypeEnum.STREET.getCode()) {
            cunrrentId = Long.parseLong(systemUser.getStreetId());
        } else if (accountLevel == ReportTypeEnum.DISTRICT.getCode()) {
            cunrrentId = Long.parseLong(systemUser.getDistrictsCode());
        } else {
            // 处理未预期的账号等级
            throw new ServiceException("未知的账号等级");
        }
 
 
        ComplaintAuditRecord complaintAuditRecord = complaintAuditRecordService.getOne(new LambdaQueryWrapper<ComplaintAuditRecord>()
                .eq(ComplaintAuditRecord::getAuditType, 1)
                .eq(ComplaintAuditRecord::getLatestFlag, 1)
                .eq(ComplaintAuditRecord::getAuditStatus, 0)
                .ne(ComplaintAuditRecord::getSuperiorId, cunrrentId)
                .eq(ComplaintAuditRecord::getReportType, accountLevel+1)
                .eq(ComplaintAuditRecord::getComplaintId, dto.getComplaintId())
                .last("LIMIT 1"));
 
 
        if (Objects.isNull(complaintAuditRecord)) {
            throw new ServiceException("诉求延期申请不存在");
        }
        //complaintAuditRecordService.audit(complaintAuditRecord, loginUserInfoVO.getUserId(),
        //        dto.getAuditResult(), dto.getRejectReason());
        //审核通过后,设置诉求延期
        if (complaintAuditRecord.getAuditType().equals(1) && complaintAuditRecord.getAuditStatus().equals(0) && dto.getAuditResult().equals(1)) {
            Complaint complaint = getById(complaintAuditRecord.getComplaintId());
            complaint.setStatus(1);
            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, dto.getId()));
        ComplaintAuditRecord record1 = new ComplaintAuditRecord();
        record1.setComplaintId(dto.getComplaintId());
        record1.setLatestFlag(true);
        record1.setAuditType(1);
        record1.setAuditorId(loginUserInfoVO.getUserId());
        record1.setAuditStatus(dto.getAuditResult());
        record1.setCreateBy(loginUserInfoVO.getUserId());
        record1.setCreateTime(new Date(System.currentTimeMillis()));
        record1.setUpdateBy(loginUserInfoVO.getUserId());
        record1.setUpdateTime(new Date(System.currentTimeMillis()));
        record1.setReporter(complaintAuditRecord.getReporter());
        record1.setReportType(complaintAuditRecord.getReportType());
        record1.setSuperiorId(complaintAuditRecord.getSuperiorId());
        record1.setSort(count + 1);
        record1.setRejectReason(dto.getRejectReason());
        complaintAuditRecordService.save(record1);
 
    }
 
    @Override
    public List<DispatchVO> getDispatchList(LoginUserInfoVO loginUserInfoVO) {
 
        String phone = loginUserInfoVO.getPhone();
        SystemUser adminUser = systemUserService.getOne(new LambdaQueryWrapper<SystemUser>()
                .eq(SystemUser::getPhone, phone)
                .eq(SystemUser::getIsAdmin, 1)
                .ne(SystemUser::getStatus, 3)
                .last("LIMIT 1"));
 
        if (adminUser == null) {
            throw new ServiceException("无权下派");
        }
        int accountLevel = adminUser.getAccountLevel(); // 改为基本类型
      /*  if (accountLevel == 1) {
            throw new ServiceException("市级账号,无法上报!");
        }*/
 
        // 使用基本类型比较并补充默认分支
        List<DispatchVO> dispatchVOList = new ArrayList<>();
        if (accountLevel == ReportTypeEnum.STREET.getCode()) {
            String streetId = adminUser.getStreetId();
            List<ComAct> list = comActService.list(new LambdaQueryWrapper<ComAct>().eq(ComAct::getStreetId, streetId).eq(ComAct::getState, 0));
            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 = adminUser.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) {
        Optional<SystemUser> systemUserByPhone = systemUserService.getSystemUserAdminByPhone(loginUserInfo.getPhone());
        String targetId = "";
        int isSuperior = 0;
        //上级
        if (systemUserByPhone.isPresent()) {
            SystemUser systemUser = systemUserByPhone.get();
            Integer accountLevel = systemUser.getAccountLevel();
            switch (accountLevel) {
                case 1:
                    //市级
                    targetId = "510400";
                    break;
                case 2:
                    //区县级
                    targetId = systemUser.getDistrictsCode();
                    break;
                case 3:
                    //街道
                    targetId = systemUser.getStreetId().toString();
                    break;
                case 4:
                    //社区
                    targetId = systemUser.getCommunityId().toString();
                    break;
            }
            isSuperior = 1;
        } else {
            //党员
            targetId = loginUserInfo.getUserId().toString();
        }
        Page<ComplaintTodoVO> page = baseMapper.getTodoList(new Page<>(basePage.getPageNum(), basePage.getPageSize()), targetId, isSuperior);
        return page;
    }
 
    /**
     * 延期情况说明
     *
     * @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(ComplaintQuery 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).orderByAsc(ComplaintProgress::getCreateTime).list();
        complaintVO.setComplaintProgresses(complaintProgresses);
        //查询诉求流转记录
        List<ComplaintFlow> complaintFlows = complaintFlowService.lambdaQuery().eq(ComplaintFlow::getComplaintId, id).orderByAsc(ComplaintFlow::getCreateTime).list();
        complaintVO.setComplaintFlows(complaintFlows);
        //查询评价
        ComplaintComment comment = complaintCommentService.lambdaQuery().eq(ComplaintComment::getComplaintId, id).last("LIMIT 1").one();
        complaintVO.setComplaintComment(comment);
        return complaintVO;
    }
 
    /**
     * 诉求列表导出
     * @param query
     * @param loginUserInfo
     */
    @Override
    public void export(ComplaintQuery 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(), PartyMemberExcel.class)
                .sheet("诉求数据")
                .doWrite(complaintExcels);
    }
 
    @Override
    public void communityProblem(Long id) throws IOException {
        //Complaint complaint = getById(id);
        //TODO 查询真实数据
        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", "处理中");
        response.setContentType("application/octet-stream");
        String fileName = URLEncoder.encode("社区问题单", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition","attachment;filename=\""+fileName+".docx"+"\"");
        String fileTemplateName = FileUtil.getPath() + "template/社区问题单.docx";
        XWPFTemplate.compile(fileTemplateName).render(map).writeAndClose(response.getOutputStream());
    }
    /**
     * 问题处理单
     * @param id
     */
    @Override
    public void problemHandle(Long id) {
 
    }
    /**
     * 协调通知
     * @param id
     */
    @Override
    public void coordinationNotice(Long id) {
 
    }
 
    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\\社区问题单.docx").render(map).writeToFile("F:\\DeskTop\\社区.docx");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}