liusheng
2026-10-10 87b79ea739ec32bd7d0e493a6ea8525212f6c763
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
package com.smartor.service.impl;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
 
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.SysUserDept;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.Arith;
import com.ruoyi.common.utils.ArrayListUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DtoConversionUtils;
import com.smartor.domain.*;
import com.smartor.domain.DTO.ServiceSubtaskDetailDTO;
import com.smartor.domain.VO.PatSatisfactionReqVO;
import com.smartor.domain.VO.PatSatisfactionResVO;
import com.smartor.domain.entity.PatSatisfactionDetailEntity;
import com.smartor.domain.entity.SatisfactionStatQuery;
import com.smartor.domain.entity.ServiceSubtaskSatisfactionEntity;
import com.smartor.mapper.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.smartor.service.IPatSatisfactionService;
 
import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;
 
/**
 * 患者满意度Service业务层处理
 *
 * @author lihu
 * @date 2025-06-30
 */
@Service
public class PatSatisfactionServiceImpl implements IPatSatisfactionService {
    @Autowired
    private PatSatisfactionMapper patSatisfactionMapper;
 
    @Autowired
    private ServiceSubtaskMapper serviceSubtaskMapper;
 
    @Autowired
    private ServiceSubtaskDetailMapper serviceSubtaskDetailMapper;
 
    @Autowired
    private IvrLibaTemplateScriptMapper ivrLibaTemplateScriptMapper;
 
    @Autowired
    private IvrLibaScriptAssortMapper ivrLibaScriptAssortMapper;
 
    @Autowired
    private SvyLibScriptCategoryMapper svyLibScriptCategoryMapper;
 
    @Autowired
    private IvrLibaTemplateTargetoptionMapper ivrLibaTemplateTargetoptionMapper;
 
    @Autowired
    private SvyLibTemplateTargetoptionMapper svyLibTemplateTargetoptionMapper;
 
    @Autowired
    private SvyLibTemplateScriptMapper svyLibTemplateScriptMapper;
 
    /**
     * 查询患者满意度
     *
     * @param id 患者满意度主键
     * @return 患者满意度
     */
    @Override
    public PatSatisfaction selectPatSatisfactionById(Long id) {
        PatSatisfaction ps = patSatisfactionMapper.selectPatSatisfactionById(id);
        double total = ps.getDoctorSatisfaction() + ps.getAuthenticity() + ps.getWeekFinish() + ps.getStandard() + ps.getTimeliness() + ps.getLibrary() + ps.getEnvironment() + ps.getNurseSatisfaction();
        ps.setTotal(total);
        return ps;
    }
 
    /**
     * 查询患者满意度列表
     *
     * @param patSatisfaction 患者满意度
     * @return 患者满意度
     */
    @Override
    public List<PatSatisfaction> selectPatSatisfactionList(PatSatisfaction patSatisfaction) {
        List<PatSatisfaction> patSatisfactions = patSatisfactionMapper.selectPatSatisfactionList(patSatisfaction);
        if (CollectionUtils.isNotEmpty(patSatisfactions)) {
            patSatisfactions.forEach(ps -> {
                double total = ps.getDoctorSatisfaction() + ps.getAuthenticity() + ps.getWeekFinish() + ps.getStandard() + ps.getTimeliness() + ps.getLibrary() + ps.getEnvironment() + ps.getNurseSatisfaction();
                ps.setTotal(total);
            });
        }
        return patSatisfactions;
    }
 
    /**
     * 新增患者满意度
     *
     * @param patSatisfaction 患者满意度
     * @return 结果
     */
    @Override
    public int insertPatSatisfaction(PatSatisfaction patSatisfaction) {
        patSatisfaction.setCreateTime(DateUtils.getNowDate());
        patSatisfaction.setUpdateTime(DateUtils.getNowDate());
        return patSatisfactionMapper.insertPatSatisfaction(patSatisfaction);
    }
 
    /**
     * 新增患者满意度
     *
     * @param patSatisfactions 患者满意度
     * @return 结果
     */
    @Override
    public int batchInsert(List<PatSatisfaction> patSatisfactions) {
        if(CollectionUtils.isEmpty(patSatisfactions)){
            return 0;
        }
        List<Long> ids = patSatisfactions.stream().map(PatSatisfaction::getId).
                distinct().collect(Collectors.toList());
        List<PatSatisfaction> patSatisfactionsOld = new ArrayList<>();
        PatSatisfaction patSatisfactionVo = new PatSatisfaction();
        patSatisfactionVo.setIds(ids);
        patSatisfactionsOld = patSatisfactionMapper.selectPatSatisfactionList(patSatisfactionVo);
        Map<String, List<PatSatisfaction>> maps = ArrayListUtils.splitListsById(patSatisfactions,
                patSatisfactionsOld, PatSatisfaction::getId);
        //只在patSatisfactions的数据,执行新增操作
        List<PatSatisfaction> addItems = maps.get("onlyIn1");
        //只在patSatisfactionsOld的数据,执行删除操作
//        List<PatSatisfaction> delItems = maps.get("onlyIn2");
        //重叠的数据,执行更新操作
        List<PatSatisfaction> editItems = maps.get("common");
        Integer count = 0;
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();
        for (PatSatisfaction patSatisfaction0 : editItems) {
            patSatisfaction0.setUpdateBy(user.getNickName());
            patSatisfaction0.setUpdateTime(DateUtils.getNowDate());
            count = count + patSatisfactionMapper.updatePatSatisfaction(patSatisfaction0);
        }
 
        for (PatSatisfaction patSatisfaction1 : addItems) {
            patSatisfaction1.setCreateBy(user.getNickName());
            patSatisfaction1.setOrgid(user.getOrgid());
            patSatisfaction1.setCreateTime(DateUtils.getNowDate());
            patSatisfaction1.setUpdateTime(DateUtils.getNowDate());
            count = count + patSatisfactionMapper.insertPatSatisfaction(patSatisfaction1);
        }
        return count;
    }
 
    /**
     * 修改患者满意度
     *
     * @param patSatisfaction 患者满意度
     * @return 结果
     */
    @Override
    public int updatePatSatisfaction(PatSatisfaction patSatisfaction) {
        patSatisfaction.setUpdateTime(DateUtils.getNowDate());
        return patSatisfactionMapper.updatePatSatisfaction(patSatisfaction);
    }
 
    /**
     * 批量删除患者满意度
     *
     * @param ids 需要删除的患者满意度主键
     * @return 结果
     */
    @Override
    public int deletePatSatisfactionByIds(Long[] ids) {
        return patSatisfactionMapper.deletePatSatisfactionByIds(ids);
    }
 
    /**
     * 删除患者满意度信息
     *
     * @param id 患者满意度主键
     * @return 结果
     */
    @Override
    public int deletePatSatisfactionById(Long id) {
        return patSatisfactionMapper.deletePatSatisfactionById(id);
    }
 
    /**
     * 患者满意度统计
     *
     * @param patSatisfactionReqVO 患者满意度统计条件
     * @return 患者满意度统计结果
     */
    @Override
    public PatSatisfactionResVO statistics(PatSatisfactionReqVO patSatisfactionReqVO) {
        //定义返参
        PatSatisfactionResVO result = new PatSatisfactionResVO();
        //患者满意度统详情
        List<PatSatisfactionDetailEntity> patSatisfactionDetailEntities = new ArrayList<>();
        // [0]=答题总人数(已经回答问题的) [1]=总人数(包含未回答的)
        int[] personTotals = new int[2];
 
        // 只查本次条件下实际存在哪些 type(原来是把接近全表的上百个字段查回来,仅用于判断下面两个分支是否为空)
        List<String> types = serviceSubtaskMapper.selectSatisfactionSubtaskTypes(patSatisfactionReqVO);
        boolean hasVoice = types != null && types.contains("1");
        boolean hasQuestionnaire = types != null && types.contains("2");
 
        if (hasVoice) {
            //1. 先获取ivr_liba_script_assort的满意度分类ID
            IvrLibaScriptAssort ivrLibaScriptAssort = new IvrLibaScriptAssort();
            ivrLibaScriptAssort.setOrgid(patSatisfactionReqVO.getOrgid());
            List<IvrLibaScriptAssort> ivrLibaScriptAssorts = ivrLibaScriptAssortMapper.selectIvrLibaScriptAssortList(ivrLibaScriptAssort);
            List<Long> mydIdList = ivrLibaScriptAssorts.stream().filter(item -> item.getType() != null && item.getType().contains("myd")).map(IvrLibaScriptAssort::getId).collect(Collectors.toList());
 
            //2 再获取该问题满意度分类下的IvrLibaTemplateScript的集合
            List<IvrLibaTemplateScript> ivrLibaTemplateScripts = ivrLibaTemplateScriptMapper.queryLibTemplateIds(mydIdList);
 
            //3 一次统计全部问题的发送量/填报量/选项分值(原来是每个问题各查 3 次)
            List<SatScriptRef> scriptRefs = new ArrayList<>();
            for (IvrLibaTemplateScript ivrLibaTemplateScript : ivrLibaTemplateScripts) {
                scriptRefs.add(new SatScriptRef(ivrLibaTemplateScript.getTemplateid(), ivrLibaTemplateScript.getScriptid(), ivrLibaTemplateScript.getScriptContent()));
            }
            buildSatisfactionDetailEntities(patSatisfactionReqVO, "1", true, scriptRefs, patSatisfactionDetailEntities, personTotals);
        }
 
        if (hasQuestionnaire) {
            //1. 先获取svy_lib_script_category的满意度分类ID
            SvyLibScriptCategory svyLibScriptCategory = new SvyLibScriptCategory();
            svyLibScriptCategory.setOrgid(patSatisfactionReqVO.getOrgid());
            List<SvyLibScriptCategory> svyLibScriptCategories = svyLibScriptCategoryMapper.selectSvyLibScriptCategoryList(svyLibScriptCategory);
            List<Long> mydIdList = svyLibScriptCategories.stream().filter(item -> item.getType() != null && item.getType().contains("myd")).map(SvyLibScriptCategory::getId).collect(Collectors.toList());
 
            //2 再获取该问题满意度分类下的IvrLibaTemplateScript的集合
            List<SvyLibTemplateScript> svyLibTemplateScripts = svyLibTemplateScriptMapper.querySvyLibTemplateIds(mydIdList);
 
            //3 一次统计全部问题的发送量/填报量/选项分值(原来是每个问题各查 3 次)
            List<SatScriptRef> scriptRefs = new ArrayList<>();
            for (SvyLibTemplateScript svyLibTemplateScript : svyLibTemplateScripts) {
                // 问卷的选项表按 svy_lib_template_script 的主键关联
                scriptRefs.add(new SatScriptRef(svyLibTemplateScript.getSvyid(), svyLibTemplateScript.getId(), svyLibTemplateScript.getScriptContent()));
            }
            buildSatisfactionDetailEntities(patSatisfactionReqVO, "2", false, scriptRefs, patSatisfactionDetailEntities, personTotals);
        }
        result.setTotalAnswerRate(Arith.div(personTotals[0], personTotals[1]));
        result.setPatSatisfactionDetailEntities(patSatisfactionDetailEntities);
        result.setTotalPerson(personTotals[0]);
 
        return result;
    }
 
    /**
     * 患者满意度统计(维度)
     *
     * @param patSatisfactionReqVO 患者满意度统计条件
     * @return 患者满意度统计结果
     */
    @Override
    public PatSatisfactionResVO statisticsByDimension(PatSatisfactionReqVO patSatisfactionReqVO) {
        //定义返参
        PatSatisfactionResVO result = new PatSatisfactionResVO();
        //患者满意度统详情
        List<PatSatisfactionDetailEntity> patSatisfactionDetailEntities = new ArrayList<>();
        // [0]=答题总人数(已经回答问题的) [1]=总人数(包含未回答的)
        int[] personTotals = new int[2];
 
        // 只查本次条件下实际存在哪些 type(原来是把接近全表的上百个字段查回来,仅用于判断下面两个分支是否为空)
        List<String> types = serviceSubtaskMapper.selectSatisfactionSubtaskTypes(patSatisfactionReqVO);
        boolean hasVoice = types != null && types.contains("1");
        boolean hasQuestionnaire = types != null && types.contains("2");
 
        if (hasVoice) {
            //1. 先获取入参中的维护集合
            IvrLibaTemplateScript iltscript = new IvrLibaTemplateScript();
            iltscript.setDimensionList(patSatisfactionReqVO.getDimensionList());
 
            //2 再获取该问题满意度分类下的IvrLibaTemplateScript的集合
            List<IvrLibaTemplateScript> ivrLibaTemplateScripts = ivrLibaTemplateScriptMapper.selectILTSBydimension(iltscript);
            if (CollectionUtils.isNotEmpty(ivrLibaTemplateScripts)) {
                //3 一次统计全部问题的发送量/填报量/选项分值(原来是每个问题各查 3 次)
                List<SatScriptRef> scriptRefs = new ArrayList<>();
                for (IvrLibaTemplateScript ivrLibaTemplateScript : ivrLibaTemplateScripts) {
                    scriptRefs.add(new SatScriptRef(ivrLibaTemplateScript.getTemplateid(), ivrLibaTemplateScript.getScriptid(), ivrLibaTemplateScript.getScriptContent()));
                }
                buildSatisfactionDetailEntities(patSatisfactionReqVO, "1", true, scriptRefs, patSatisfactionDetailEntities, personTotals);
            }
        }
 
        if (hasQuestionnaire) {
            //1. 先获取入参中的满意度维度
            SvyLibTemplateScriptVO svyLibTemplateScriptVO = new SvyLibTemplateScriptVO();
            svyLibTemplateScriptVO.setDimensionList(patSatisfactionReqVO.getDimensionList());
            //2 再获取该问题满意度分类下的IvrLibaTemplateScript的集合
            List<SvyLibTemplateScript> svyLibTemplateScripts = svyLibTemplateScriptMapper.selectSLTScriptListBydimension(svyLibTemplateScriptVO);
            if (CollectionUtils.isNotEmpty(svyLibTemplateScripts)) {
                //3 一次统计全部问题的发送量/填报量/选项分值(原来是每个问题各查 3 次)
                List<SatScriptRef> scriptRefs = new ArrayList<>();
                for (SvyLibTemplateScript svyLibTemplateScript : svyLibTemplateScripts) {
                    // 问卷的选项表按 svy_lib_template_script 的主键关联
                    scriptRefs.add(new SatScriptRef(svyLibTemplateScript.getSvyid(), svyLibTemplateScript.getId(), svyLibTemplateScript.getScriptContent()));
                }
                buildSatisfactionDetailEntities(patSatisfactionReqVO, "2", false, scriptRefs, patSatisfactionDetailEntities, personTotals);
            }
        }
        result.setTotalAnswerRate(Arith.div(personTotals[0], personTotals[1]));
        result.setPatSatisfactionDetailEntities(patSatisfactionDetailEntities);
        result.setTotalPerson(personTotals[0]);
 
        return result;
    }
 
    @Override
    public Map<String, Object> satisfactionGraph(PatSatisfactionReqVO patSatisfactionReqVO) {
        //用来记录柱状图信息(key=满意度分类名称,value=满意度分类下的总人数和填报人数)
        Map<String, Object> zzt = new HashMap<>();
 
        // 记录一下每种分类的填报情况(只记分值与条数,不再把明细行全部查回 Java)
        Map<String, List<ScoreCount>> assortNameFillCountMap = new HashMap<>();
 
        if (patSatisfactionReqVO.getType() == null || patSatisfactionReqVO.getType() == 1) {
            //1. 先获取ivr_liba_script_assort的满意度分类ID
            IvrLibaScriptAssort ivrLibaScriptAssort = new IvrLibaScriptAssort();
            ivrLibaScriptAssort.setOrgid(patSatisfactionReqVO.getOrgid());
            List<IvrLibaScriptAssort> ivrLibaScriptAssorts = ivrLibaScriptAssortMapper.selectIvrLibaScriptAssortList(ivrLibaScriptAssort);
            List<Long> mydIdList = ivrLibaScriptAssorts.stream().filter(item -> item.getType() != null && item.getType().contains("myd")).map(IvrLibaScriptAssort::getId).collect(Collectors.toList());
 
            //2 再获取该问题满意度分类下的IvrLibaTemplateScript的集合
            List<IvrLibaTemplateScript> ivrLibaTemplateScripts = ivrLibaTemplateScriptMapper.queryLibTemplateIds(mydIdList);
 
            //2.1 一次性把本次请求全部模板的发送量、回收人数查回来(原来是每个模板问题各查两次)
            SatisfactionStatQuery statQuery = buildSatisfactionStatQuery(patSatisfactionReqVO, "1",
                    ivrLibaTemplateScripts.stream().map(IvrLibaTemplateScript::getTemplateid).collect(Collectors.toList()));
            Map<Long, Long> sendCountMap = mapSatisfactionSendCount(statQuery);
            SatisfactionFillStat fillStat = querySatisfactionFillStat(statQuery);
            Map<Long, Long> fillPersonCountMap = mapSatisfactionFillPersonCount(statQuery);
 
            //3 按scriptAssortname分组,并获取每个集合进行遍历,计算每个分类的总人数和填报人数
            Map<String, List<IvrLibaTemplateScript>> scriptGroupByAssortName = ivrLibaTemplateScripts.stream().filter(item -> item.getScriptAssortname() != null).collect(Collectors.groupingBy(IvrLibaTemplateScript::getScriptAssortname));
            if (scriptGroupByAssortName != null && !scriptGroupByAssortName.isEmpty()) {
                for (String assortNameKey : scriptGroupByAssortName.keySet()) {
                    // 该分类涉及的去重模板:发送人数/回收人数都按模板统计,
                    // 按题目循环累加会把同一个模板的量重复计成「题量」
                    Set<Long> categoryTemplateIds = new LinkedHashSet<>();
                    //获取该分类的填报总数量(只用于算平均分,按题目聚合的行数)
                    List<ScoreCount> allFillCountList = new ArrayList<>();
 
                    List<IvrLibaTemplateScript> ivrLibaTemplateScriptList = scriptGroupByAssortName.get(assortNameKey);
                    for (IvrLibaTemplateScript ivrLibaTemplateScript : ivrLibaTemplateScriptList) {
                        Long templateId = ivrLibaTemplateScript.getTemplateid();
                        if (templateId != null) {
                            categoryTemplateIds.add(templateId);
                        }
                        //获取填报分值分布(只用于平均分)
                        List<ScoreCount> fillCount = fillStat.get(templateId, ivrLibaTemplateScript.getScriptContent());
                        if (CollectionUtils.isNotEmpty(fillCount)) allFillCountList.addAll(fillCount);
                    }
 
                    //记录发送总人数、回收总人数
                    Double subidAll = 0.0;
                    Double fillCountAll = 0.0;
                    for (Long templateId : categoryTemplateIds) {
                        subidAll += sendCountMap.getOrDefault(templateId, 0L);
                        fillCountAll += fillPersonCountMap.getOrDefault(templateId, 0L);
                    }
 
                    // 这里先记录一下每个分类的总人数和填报人数
                    Map<String, Object> personCount = new HashMap<>();
                    personCount.put("fillCountAll", fillCountAll);
                    personCount.put("subidAll", subidAll);
                    personCount.put("receiveRate", Arith.div(fillCountAll, subidAll));
                    personCount.put("averageScore", averageScoreByStat(allFillCountList));
                    zzt.put(assortNameKey, personCount);
                    assortNameFillCountMap.put(assortNameKey, allFillCountList);
                }
            }
        }
 
        if (patSatisfactionReqVO.getType() == null || patSatisfactionReqVO.getType() == 2) {
            //1. 先获取svy_lib_script_category的满意度分类ID
            SvyLibScriptCategory svyLibScriptCategory = new SvyLibScriptCategory();
            svyLibScriptCategory.setOrgid(patSatisfactionReqVO.getOrgid());
            List<SvyLibScriptCategory> svyLibScriptCategories = svyLibScriptCategoryMapper.selectSvyLibScriptCategoryList(svyLibScriptCategory);
            List<Long> mydIdList = svyLibScriptCategories.stream().filter(item -> item.getType() != null && item.getType().contains("myd")).map(SvyLibScriptCategory::getId).collect(Collectors.toList());
 
            //2 再获取该问题满意度分类下的IvrLibaTemplateScript的集合
            List<SvyLibTemplateScript> svyLibTemplateScripts = svyLibTemplateScriptMapper.querySvyLibTemplateIds(mydIdList);
 
            //2.1 一次性把本次请求全部模板的发送量、回收人数查回来(原来是每个模板问题各查两次)
            SatisfactionStatQuery statQuery = buildSatisfactionStatQuery(patSatisfactionReqVO, "2",
                    svyLibTemplateScripts.stream().map(SvyLibTemplateScript::getSvyid).collect(Collectors.toList()));
            Map<Long, Long> sendCountMap = mapSatisfactionSendCount(statQuery);
            SatisfactionFillStat fillStat = querySatisfactionFillStat(statQuery);
            Map<Long, Long> fillPersonCountMap = mapSatisfactionFillPersonCount(statQuery);
 
            //3 按scriptAssortname分组,并获取每个集合进行遍历,计算每个分类的总人数和填报人数
            Map<String, List<SvyLibTemplateScript>> scriptGroupByatCegoryName = svyLibTemplateScripts.stream().filter(item -> item.getCategoryName() != null).collect(Collectors.groupingBy(SvyLibTemplateScript::getCategoryName));
            if (scriptGroupByatCegoryName != null && !scriptGroupByatCegoryName.isEmpty()) {
                for (String categoryNameKey : scriptGroupByatCegoryName.keySet()) {
                    // 该分类涉及的去重模板:发送人数/回收人数都按模板统计,
                    // 按题目循环累加会把同一个模板的量重复计成「题量」
                    Set<Long> categoryTemplateIds = new LinkedHashSet<>();
                    //获取该分类的填报总数量(只用于算平均分,按题目聚合的行数)
                    List<ScoreCount> allFillCountList = new ArrayList<>();
 
                    List<SvyLibTemplateScript> svyLibTemplateScriptList = scriptGroupByatCegoryName.get(categoryNameKey);
                    for (SvyLibTemplateScript svyLibTemplateScript : svyLibTemplateScriptList) {
                        Long templateId = svyLibTemplateScript.getSvyid();
                        if (templateId != null) {
                            categoryTemplateIds.add(templateId);
                        }
                        //获取填报分值分布(只用于平均分)
                        List<ScoreCount> fillCount = fillStat.get(templateId, svyLibTemplateScript.getScriptContent());
                        if (CollectionUtils.isNotEmpty(fillCount)) allFillCountList.addAll(fillCount);
                    }
 
                    //记录发送总人数、回收总人数
                    Double subidAll = 0.0;
                    Double fillCountAll = 0.0;
                    for (Long templateId : categoryTemplateIds) {
                        subidAll += sendCountMap.getOrDefault(templateId, 0L);
                        fillCountAll += fillPersonCountMap.getOrDefault(templateId, 0L);
                    }
 
 
                    // 这里先记录一下每个分类的总人数和填报人数
                    Map<String, Object> personCount = (Map<String, Object>) zzt.get(categoryNameKey);
                    if (!Objects.isNull(personCount)) {
                        Double fillCountAll2 = (Double) personCount.get("fillCountAll");
                        Double subidAll2 = (Double) personCount.get("subidAll");
                        personCount.put("fillCountAll", fillCountAll2 + fillCountAll);
                        personCount.put("subidAll", subidAll2 + subidAll);
                        personCount.put("receiveRate", Arith.div((Double) personCount.get("fillCountAll"), (Double) personCount.get("subidAll")));
 
                        //看一下之前有没有该分类的填报量
                        List<ScoreCount> serviceSubtaskDetailDTOS = assortNameFillCountMap.get(categoryNameKey);
                        if (CollectionUtils.isNotEmpty(serviceSubtaskDetailDTOS))
                            allFillCountList.addAll(serviceSubtaskDetailDTOS);
                        personCount.put("averageScore", averageScoreByStat(allFillCountList));
                    } else {
                        personCount = new HashMap<>();
                        personCount.put("fillCountAll", fillCountAll);
                        personCount.put("subidAll", subidAll);
                        personCount.put("receiveRate", Arith.div(fillCountAll, subidAll));
                        personCount.put("averageScore", averageScoreByStat(allFillCountList));
                        zzt.put(categoryNameKey, personCount);
                    }
                }
            }
        }
        return zzt;
    }
 
 
    @Override
    public Map<String, Object> satisfactionGraphDimension(PatSatisfactionReqVO patSatisfactionReqVO) {
        //用来记录柱状图信息(key=满意度维度名称,value=该维度下的总人数和填报人数)
        Map<String, Object> zzt = new HashMap<>();
 
        // 记录一下每个维度的填报情况(只记分值与条数,不再把明细行全部查回 Java)
        Map<String, List<ScoreCount>> assortNameFillCountMap = new HashMap<>();
 
        if (patSatisfactionReqVO.getType() == null || patSatisfactionReqVO.getType() == 1) {
            //1. 从入参中获取满意度维维度
            IvrLibaTemplateScript ivrLibaTemplateScript2 = new IvrLibaTemplateScript();
            ivrLibaTemplateScript2.setDimensionList(patSatisfactionReqVO.getDimensionList());
 
            //2 再获取该问题满意度分类下的IvrLibaTemplateScript的集合
            List<IvrLibaTemplateScript> ivrLibaTemplateScripts = ivrLibaTemplateScriptMapper.selectILTSBydimension(ivrLibaTemplateScript2);
            if (ivrLibaTemplateScripts != null && !ivrLibaTemplateScripts.isEmpty()) {
                //3 按dimension维度分组,并获取每个集合进行遍历,计算每个分类的总人数和填报人数
                List<IvrLibaTemplateScript> dimensionScripts = ivrLibaTemplateScripts.stream().filter(item -> item.getDimension() != null).collect(Collectors.toList());
                Map<String, List<IvrLibaTemplateScript>> groupByDimension = dimensionScripts.stream().collect(Collectors.groupingBy(IvrLibaTemplateScript::getDimension));
 
                if (groupByDimension != null && !groupByDimension.isEmpty()) {
                    //3.1 一次性把本次请求全部模板的发送量、回收人数查回来(原来是每个模板问题各查两次)
                    SatisfactionStatQuery statQuery = buildSatisfactionStatQuery(patSatisfactionReqVO, "1",
                            dimensionScripts.stream().map(IvrLibaTemplateScript::getTemplateid).collect(Collectors.toList()));
                    Map<Long, Long> sendCountMap = mapSatisfactionSendCount(statQuery);
                    SatisfactionFillStat fillStat = querySatisfactionFillStat(statQuery);
                    Map<Long, Long> fillPersonCountMap = mapSatisfactionFillPersonCount(statQuery);
 
                    for (String dimension : groupByDimension.keySet()) {
                        // 该维度涉及的去重模板:发送人数/回收人数都按模板统计,按题目累加会变成题量
                        Set<Long> dimensionTemplateIds = new LinkedHashSet<>();
                        //获取该维度的填报分值分布(只用于算平均分)
                        List<ScoreCount> allFillCountList = new ArrayList<>();
 
                        List<IvrLibaTemplateScript> ivrLibaTemplateScriptList = groupByDimension.get(dimension);
                        for (IvrLibaTemplateScript ivrLibaTemplateScript : ivrLibaTemplateScriptList) {
                            Long templateId = ivrLibaTemplateScript.getTemplateid();
                            if (templateId != null) {
                                dimensionTemplateIds.add(templateId);
                            }
                            //获取填报分值分布(只用于平均分)
                            List<ScoreCount> fillCount = fillStat.get(templateId, ivrLibaTemplateScript.getScriptContent());
                            if (CollectionUtils.isNotEmpty(fillCount)) allFillCountList.addAll(fillCount);
                        }
 
                        //记录发送总人数、回收总人数
                        Double subidAll = 0.0;
                        Double fillCountAll = 0.0;
                        for (Long templateId : dimensionTemplateIds) {
                            subidAll += sendCountMap.getOrDefault(templateId, 0L);
                            fillCountAll += fillPersonCountMap.getOrDefault(templateId, 0L);
                        }
 
                        // 这里先记录一下每个分类的总人数和填报人数
                        Map<String, Object> personCount = new HashMap<>();
                        personCount.put("fillCountAll", fillCountAll);
                        personCount.put("subidAll", subidAll);
                        personCount.put("receiveRate", Arith.div(fillCountAll, subidAll));
                        personCount.put("averageScore", averageScoreByStat(allFillCountList));
                        zzt.put(dimension, personCount);
                        assortNameFillCountMap.put(dimension, allFillCountList);
                    }
                }
            }
        }
 
        if (patSatisfactionReqVO.getType() == null || patSatisfactionReqVO.getType() == 2) {
            //1.  从入参中获取满意度维维度
            SvyLibTemplateScriptVO svyLibTemplateScriptVO = new SvyLibTemplateScriptVO();
            svyLibTemplateScriptVO.setDimensionList(patSatisfactionReqVO.getDimensionList());
 
            //2 再获取该问题满意度分类下的IvrLibaTemplateScript的集合
            List<SvyLibTemplateScript> svyLibTemplateScripts = svyLibTemplateScriptMapper.selectSLTScriptListBydimension(svyLibTemplateScriptVO);
            if (svyLibTemplateScripts != null && !svyLibTemplateScripts.isEmpty()) {
                //3 按dimension维度分组,并获取每个集合进行遍历,计算每个分类的总人数和填报人数
                List<SvyLibTemplateScript> dimensionScripts = svyLibTemplateScripts.stream().filter(item -> item.getDimension() != null).collect(Collectors.toList());
                Map<String, List<SvyLibTemplateScript>> groupByDimension = dimensionScripts.stream().collect(Collectors.groupingBy(SvyLibTemplateScript::getDimension));
                if (groupByDimension != null && !groupByDimension.isEmpty()) {
                    //3.1 一次性把本次请求全部模板的发送量、回收人数查回来(原来是每个模板问题各查两次)
                    SatisfactionStatQuery statQuery = buildSatisfactionStatQuery(patSatisfactionReqVO, "2",
                            dimensionScripts.stream().map(SvyLibTemplateScript::getSvyid).collect(Collectors.toList()));
                    Map<Long, Long> sendCountMap = mapSatisfactionSendCount(statQuery);
                    SatisfactionFillStat fillStat = querySatisfactionFillStat(statQuery);
                    Map<Long, Long> fillPersonCountMap = mapSatisfactionFillPersonCount(statQuery);
 
                    for (String dimension : groupByDimension.keySet()) {
                        // 该维度涉及的去重模板:发送人数/回收人数都按模板统计,按题目累加会变成题量
                        Set<Long> dimensionTemplateIds = new LinkedHashSet<>();
                        //获取该分类的填报分值分布(只用于算平均分)
                        List<ScoreCount> allFillCountList = new ArrayList<>();
 
                        List<SvyLibTemplateScript> svyLibTemplateScriptList = groupByDimension.get(dimension);
                        for (SvyLibTemplateScript svyLibTemplateScript : svyLibTemplateScriptList) {
                            Long templateId = svyLibTemplateScript.getSvyid();
                            if (templateId != null) {
                                dimensionTemplateIds.add(templateId);
                            }
                            //获取填报分值分布(只用于平均分)
                            List<ScoreCount> fillCount = fillStat.get(templateId, svyLibTemplateScript.getScriptContent());
                            if (CollectionUtils.isNotEmpty(fillCount)) allFillCountList.addAll(fillCount);
                        }
 
                        //记录发送总人数、回收总人数
                        Double subidAll = 0.0;
                        Double fillCountAll = 0.0;
                        for (Long templateId : dimensionTemplateIds) {
                            subidAll += sendCountMap.getOrDefault(templateId, 0L);
                            fillCountAll += fillPersonCountMap.getOrDefault(templateId, 0L);
                        }
 
 
                        // 这里先记录一下每个分类的总人数和填报人数
                        Map<String, Object> personCount = (Map<String, Object>) zzt.get(dimension);
                        if (!Objects.isNull(personCount)) {
                            Double fillCountAll2 = (Double) personCount.get("fillCountAll");
                            Double subidAll2 = (Double) personCount.get("subidAll");
                            personCount.put("fillCountAll", fillCountAll2 + fillCountAll);
                            personCount.put("subidAll", subidAll2 + subidAll);
                            personCount.put("receiveRate", Arith.div((Double) personCount.get("fillCountAll"), (Double) personCount.get("subidAll")));
 
                            //看一下之前有没有该分类的填报量
                            List<ScoreCount> serviceSubtaskDetailDTOS = assortNameFillCountMap.get(dimension);
                            if (CollectionUtils.isNotEmpty(serviceSubtaskDetailDTOS))
                                allFillCountList.addAll(serviceSubtaskDetailDTOS);
                            personCount.put("averageScore", averageScoreByStat(allFillCountList));
                        } else {
                            personCount = new HashMap<>();
                            personCount.put("fillCountAll", fillCountAll);
                            personCount.put("subidAll", subidAll);
                            personCount.put("receiveRate", Arith.div(fillCountAll, subidAll));
                            personCount.put("averageScore", averageScoreByStat(allFillCountList));
                            zzt.put(dimension, personCount);
                        }
                    }
                }
            }
        }
        return zzt;
    }
 
    /**
     * 获取最高分
     *
     * @param options
     * @return
     */
    private Double maxScore(List<IvrLibaTemplateTargetoption> options) {
        if (CollectionUtils.isEmpty(options)) return 0.0;
        Double maxScore = options.stream()
                .map(IvrLibaTemplateTargetoption::getScore)
                .filter(scoreStr -> scoreStr != null && !scoreStr.isEmpty())
                .mapToDouble(Double::parseDouble)
                .max()
                .orElse(0.0);
        return maxScore;
    }
 
    /**
     * 获取最低分
     *
     * @param options
     * @return
     */
    private Double minScore(List<IvrLibaTemplateTargetoption> options) {
        if (CollectionUtils.isEmpty(options)) return 0.0;
        Double minScore = options.stream()
                .map(IvrLibaTemplateTargetoption::getScore)
                .filter(scoreStr -> scoreStr != null && !scoreStr.isEmpty())
                .mapToDouble(Double::parseDouble)
                .min()
                .orElse(0.0);
        return minScore;
    }
 
    /**
     * 获取平均分
     *
     * @param fillCount
     * @return
     */
    private Double averageScore(List<ServiceSubtaskDetailDTO> fillCount) {
        if (CollectionUtils.isEmpty(fillCount)) return 0.0;
        double sum = fillCount.stream().filter(dto -> dto.getScore() != null && !dto.getScore().isEmpty()).mapToDouble(dto -> Double.parseDouble(dto.getScore())).sum();
        return new BigDecimal(sum / fillCount.size()).setScale(1, RoundingMode.HALF_UP).doubleValue();
    }
 
    // ==================== satisfactionGraph 聚合统计(替代逐个模板查库) ====================
 
    /**
     * 构建聚合统计入参(取值来源与原 DtoConversionUtils.sourceToTarget(patSatisfactionReqVO, ServiceSubtaskSatisfactionEntity.class) 一致)
     *
     * @param reqVO       原始请求
     * @param type        service_subtask.type(1 语音、2 问卷),用字符串比较避免隐式转换
     * @param templateIds 本次请求涉及的模板id(ivr 用 templateid,问卷用 svyid)
     */
    private SatisfactionStatQuery buildSatisfactionStatQuery(PatSatisfactionReqVO reqVO, String type, List<Long> templateIds) {
        SatisfactionStatQuery statQuery = new SatisfactionStatQuery();
        statQuery.setOrgid(reqVO.getOrgid());
        statQuery.setCampusid(reqVO.getCampusid());
        statQuery.setType(type);
        statQuery.setStartTime(reqVO.getStartTime());
        statQuery.setEndTime(reqVO.getEndTime());
        statQuery.setDeptcodes(reqVO.getDeptcodes());
        statQuery.setHospitaldistrictcodes(reqVO.getHospitaldistrictcodes());
        statQuery.setLibTemplateIds(CollectionUtils.isEmpty(templateIds) ? templateIds
                : templateIds.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList()));
        return statQuery;
    }
 
    /**
     * 一次查出全部模板的发送量
     *
     * @return key=模板id,value=发送量(等价于原 querySendCount 结果的 size)
     */
    private Map<Long, Long> mapSatisfactionSendCount(SatisfactionStatQuery statQuery) {
        Map<Long, Long> sendCountMap = new HashMap<>();
        if (statQuery == null || CollectionUtils.isEmpty(statQuery.getLibTemplateIds())) return sendCountMap;
        List<Map<String, Object>> rows = serviceSubtaskMapper.selectSatisfactionSendCount(statQuery);
        if (CollectionUtils.isEmpty(rows)) return sendCountMap;
        for (Map<String, Object> row : rows) {
            Long templateId = toLong(row.get("libtemplateid"));
            if (templateId == null) continue;
            sendCountMap.put(templateId, toLong(row.get("cnt"), 0L));
        }
        return sendCountMap;
    }
 
    /**
     * 一次查出全部模板的「回收人数」(按模板去重,同一个人答多道题只算一人)
     *
     * @return key=模板id,value=回收人数
     */
    private Map<Long, Long> mapSatisfactionFillPersonCount(SatisfactionStatQuery statQuery) {
        Map<Long, Long> fillPersonCountMap = new HashMap<>();
        if (statQuery == null || CollectionUtils.isEmpty(statQuery.getLibTemplateIds())) return fillPersonCountMap;
        List<Map<String, Object>> rows = serviceSubtaskDetailMapper.selectSatisfactionFillPersonCount(statQuery);
        if (CollectionUtils.isEmpty(rows)) return fillPersonCountMap;
        for (Map<String, Object> row : rows) {
            Long templateId = toLong(row.get("libtemplateid"));
            if (templateId == null) continue;
            fillPersonCountMap.put(templateId, toLong(row.get("cnt"), 0L));
        }
        return fillPersonCountMap;
    }
 
    /**
     * 一次查出全部模板的填报量(按 模板+问题+分值 分组)
     */
    private SatisfactionFillStat querySatisfactionFillStat(SatisfactionStatQuery statQuery) {
        SatisfactionFillStat fillStat = new SatisfactionFillStat();
        if (statQuery == null || CollectionUtils.isEmpty(statQuery.getLibTemplateIds())) return fillStat;
        List<Map<String, Object>> rows = serviceSubtaskDetailMapper.selectSatisfactionFillStat(statQuery);
        if (CollectionUtils.isEmpty(rows)) return fillStat;
        for (Map<String, Object> row : rows) {
            Long templateId = toLong(row.get("libtemplateid"));
            if (templateId == null) continue;
            long cnt = toLong(row.get("cnt"), 0L);
            if (cnt <= 0L) continue;
            Object scoreValue = row.get("score");
            Object questiontextValue = row.get("questiontext");
            ScoreCount scoreCount = new ScoreCount(scoreValue == null ? null : String.valueOf(scoreValue), cnt);
            fillStat.add(templateId, questiontextValue == null ? null : String.valueOf(questiontextValue), scoreCount);
        }
        return fillStat;
    }
 
    /**
     * 获取平均分(聚合版:分值与条数)
     * <p>
     * 口径与 {@link #averageScore(List)} 完全一致:分子为可解析分值之和,分母为明细行数(包含分值为空的行)。
     * 注意不能改成 sql 的 avg() 或「有分值的行数」做分母,否则返回的 averageScore 会变。
     */
    private Double averageScoreByStat(List<ScoreCount> fillCount) {
        if (CollectionUtils.isEmpty(fillCount)) return 0.0;
        double sum = 0.0;
        long rows = 0L;
        for (ScoreCount scoreCount : fillCount) {
            if (scoreCount.getCount() <= 0L) continue;
            rows += scoreCount.getCount();
            if (scoreCount.getScore() != null && !scoreCount.getScore().isEmpty()) {
                sum += Double.parseDouble(scoreCount.getScore()) * scoreCount.getCount();
            }
        }
        if (rows == 0L) return 0.0;
        return new BigDecimal(sum / rows).setScale(1, RoundingMode.HALF_UP).doubleValue();
    }
 
    /**
     * 分值分组键:模板id + 分隔符 + 规范化后的问题内容
     * <p>
     * MySQL 里 questiontext = #{questiontext} 是「忽略大小写、忽略尾部空格」的比较,
     * 这里用 trim + 小写做等价匹配。
     */
    private static String statKey(Long templateId, String questiontext) {
        return templateId + "\u0001" + (questiontext == null ? "" : questiontext.trim().toLowerCase(Locale.ROOT));
    }
 
    private static Long toLong(Object value) {
        if (value == null) return null;
        if (value instanceof Number) return ((Number) value).longValue();
        String text = String.valueOf(value).trim();
        return text.isEmpty() ? null : Long.valueOf(text);
    }
 
    private static long toLong(Object value, long defaultValue) {
        Long result = toLong(value);
        return result == null ? defaultValue : result;
    }
 
    /**
     * 满意度分值聚合结果:分值 + 该分值对应的明细行数
     */
    private static class ScoreCount {
        private final String score;
        private final long count;
 
        ScoreCount(String score, long count) {
            this.score = score;
            this.count = count;
        }
 
        String getScore() {
            return score;
        }
 
        long getCount() {
            return count;
        }
    }
 
    /**
     * 满意度填报量聚合结果
     * <p>
     * byTemplateQuestion:按 模板+问题 分组;
     * byTemplate:按模板分组(该模板全部问题),用于兼容原 queryFillCount 在
     * script_content 为 null 时不拼 questiontext 条件的行为。
     */
    private static class SatisfactionFillStat {
        private final Map<String, List<ScoreCount>> byTemplateQuestion = new HashMap<>();
        private final Map<Long, List<ScoreCount>> byTemplate = new HashMap<>();
 
        void add(Long templateId, String questiontext, ScoreCount scoreCount) {
            byTemplate.computeIfAbsent(templateId, key -> new ArrayList<>()).add(scoreCount);
            if (questiontext != null) {
                byTemplateQuestion.computeIfAbsent(statKey(templateId, questiontext), key -> new ArrayList<>()).add(scoreCount);
            }
        }
 
        List<ScoreCount> get(Long templateId, String scriptContent) {
            if (templateId == null) return null;
            if (scriptContent == null) return byTemplate.get(templateId);
            return byTemplateQuestion.get(statKey(templateId, scriptContent));
        }
    }
 
    // ==================== statistics / statisticsByDimension 批量统计(替代逐个问题查库) ====================
 
    /**
     * 满意度明细统计(statistics、statisticsByDimension 共用)
     * <p>
     * 把原来「每个问题 3 条 SQL」改成「整个请求 3 条查询 + 内存组装」:
     * ① 发送量按 libtemplateid 分组;② 填报量按 模板+问题+matchedtext+score 分组;③ 选项分值按 scriptid 分组。
     *
     * @param reqVO      原始请求
     * @param type       service_subtask.type(1 语音、2 问卷)
     * @param voice      true=语音问题(选项分值取 ivr_liba_template_targetoption)
     * @param scriptRefs 本次要统计的问题(顺序即返回顺序)
     * @param out        明细结果
     * @param totals     [0]=totalPerson, [1]=allPerson
     */
    private void buildSatisfactionDetailEntities(PatSatisfactionReqVO reqVO, String type, boolean voice,
                                                 List<SatScriptRef> scriptRefs,
                                                 List<PatSatisfactionDetailEntity> out, int[] totals) {
        if (CollectionUtils.isEmpty(scriptRefs)) return;
 
        List<Long> templateIds = scriptRefs.stream().map(SatScriptRef::getTemplateId)
                .filter(Objects::nonNull).distinct().collect(Collectors.toList());
        SatisfactionStatQuery statQuery = buildSatisfactionStatQuery(reqVO, type, templateIds);
        Map<Long, Long> sendCountMap = mapSatisfactionSendCount(statQuery);
        SatisfactionFillStatByMatchedtext fillStat = querySatisfactionFillStatByMatchedtext(statQuery);
        Map<Long, List<String>> optionScores = loadTargetOptionScores(voice, scriptRefs);
 
        for (SatScriptRef scriptRef : scriptRefs) {
            Long templateId = scriptRef.getTemplateId();
            //发送总量(原来是把全部 sub_id 查回 Java 再取 size)
            long sendCount = templateId == null ? 0L : sendCountMap.getOrDefault(templateId, 0L);
            //填报数量(原来是把明细行全部查回 Java 再统计)
            List<MatchedtextCount> fillRows = fillStat.get(templateId, scriptRef.getScriptContent());
            long fillCount = countFillRowsByMatchedtext(fillRows);
 
            PatSatisfactionDetailEntity detail = new PatSatisfactionDetailEntity();
            detail.setScriptContent(scriptRef.getScriptContent());
            detail.setAnswerPerson((int) fillCount);
            detail.setNoAnswerPerson(fillCount > 0L && sendCount > 0L ? (int) (sendCount - fillCount) : sendCount > 0L ? (int) sendCount : 0);
            detail.setAverageScore(String.valueOf(averageScoreByMatchedtext(fillRows)));
            List<String> scores = optionScores.get(scriptRef.getOptionScriptId());
            detail.setMaxScore(String.valueOf(maxScoreOf(scores)));
            detail.setMinScore(String.valueOf(minScoreOf(scores)));
            detail.setAnswerRate(sendCount == 0L ? 0 : fillCount == 0L ? 0 : fillCount * 1.0 / sendCount);
            detail.setMatchedtextStats(buildMatchedtextStats(fillRows, fillCount));
            out.add(detail);
 
            totals[0] += (int) fillCount;
            totals[1] += (int) sendCount;
        }
    }
 
    /**
     * 一次查出全部问题的填报量(按 模板+问题+matchedtext+score 分组,含 targetvalue)
     */
    private SatisfactionFillStatByMatchedtext querySatisfactionFillStatByMatchedtext(SatisfactionStatQuery statQuery) {
        SatisfactionFillStatByMatchedtext fillStat = new SatisfactionFillStatByMatchedtext();
        if (statQuery == null || CollectionUtils.isEmpty(statQuery.getLibTemplateIds())) return fillStat;
        List<Map<String, Object>> rows = serviceSubtaskDetailMapper.selectSatisfactionFillStatByMatchedtext(statQuery);
        if (CollectionUtils.isEmpty(rows)) return fillStat;
        for (Map<String, Object> row : rows) {
            Long templateId = toLong(row.get("libtemplateid"));
            if (templateId == null) continue;
            long cnt = toLong(row.get("cnt"), 0L);
            if (cnt <= 0L) continue;
            Object questiontext = row.get("questiontext");
            Object matchedtext = row.get("matchedtext");
            Object score = row.get("score");
            Object targetvalue = row.get("targetvalue");
            fillStat.add(templateId, questiontext == null ? null : String.valueOf(questiontext),
                    new MatchedtextCount(matchedtext == null ? null : String.valueOf(matchedtext),
                            score == null ? null : String.valueOf(score),
                            targetvalue == null ? null : String.valueOf(targetvalue), cnt));
        }
        return fillStat;
    }
 
    /**
     * 一次查出全部问题的选项分值(只取 scriptid、score 两列)
     * <p>
     * 原实现是每个问题查一次整行,而调用方只用到 score 算最高/最低分;
     * 问题 id 为 null 时原实现不拼 scriptid 条件(等于取该表全部分值),这里用 null 作为 key 存这一份。
     */
    private Map<Long, List<String>> loadTargetOptionScores(boolean voice, List<SatScriptRef> scriptRefs) {
        Map<Long, List<String>> optionScores = new HashMap<>();
        List<Long> scriptIds = scriptRefs.stream().map(SatScriptRef::getOptionScriptId)
                .filter(Objects::nonNull).distinct().collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(scriptIds)) {
            addTargetOptionScores(optionScores, voice
                    ? ivrLibaTemplateTargetoptionMapper.selectIvrLibaTargetoptionScores(scriptIds)
                    : svyLibTemplateTargetoptionMapper.selectSvyLibTargetoptionScores(scriptIds));
        }
        if (scriptRefs.stream().anyMatch(ref -> ref.getOptionScriptId() == null)) {
            optionScores.put(null, collectTargetOptionScores(voice
                    ? ivrLibaTemplateTargetoptionMapper.selectIvrLibaTargetoptionScores(null)
                    : svyLibTemplateTargetoptionMapper.selectSvyLibTargetoptionScores(null)));
        }
        return optionScores;
    }
 
    private void addTargetOptionScores(Map<Long, List<String>> optionScores, List<Map<String, Object>> rows) {
        if (CollectionUtils.isEmpty(rows)) return;
        for (Map<String, Object> row : rows) {
            Long scriptId = toLong(row.get("scriptid"));
            if (scriptId == null) continue;
            Object score = row.get("score");
            optionScores.computeIfAbsent(scriptId, key -> new ArrayList<>())
                    .add(score == null ? null : String.valueOf(score));
        }
    }
 
    private List<String> collectTargetOptionScores(List<Map<String, Object>> rows) {
        List<String> scores = new ArrayList<>();
        if (CollectionUtils.isEmpty(rows)) return scores;
        for (Map<String, Object> row : rows) {
            Object score = row.get("score");
            scores.add(score == null ? null : String.valueOf(score));
        }
        return scores;
    }
 
    /**
     * 各选项(matchedtext)数量及占比
     * <p>
     * 口径与原实现一致:分母是全部明细行数(含 matchedtext 为 null 的行);
     * targetvalue 用于补全未出现的选项(count=0、ratio=0)。
     */
    private Map<String, Map<String, Object>> buildMatchedtextStats(List<MatchedtextCount> fillRows, long totalFill) {
        Map<String, Map<String, Object>> matchedtextStats = new HashMap<>();
        if (CollectionUtils.isEmpty(fillRows) || totalFill <= 0L) return matchedtextStats;
 
        Map<String, Long> matchedtextCounts = new LinkedHashMap<>();
        String targetvalue = null;
        for (MatchedtextCount row : fillRows) {
            if (row.getMatchedtext() != null) {
                matchedtextCounts.merge(row.getMatchedtext(), row.getCount(), Long::sum);
            }
            if (targetvalue == null && row.getTargetvalue() != null) {
                targetvalue = row.getTargetvalue();
            }
        }
        for (Map.Entry<String, Long> entry : matchedtextCounts.entrySet()) {
            Map<String, Object> stat = new HashMap<>();
            stat.put("count", entry.getValue());
            stat.put("ratio", new BigDecimal((double) entry.getValue() / totalFill * 100).setScale(1, RoundingMode.HALF_UP).doubleValue());
            matchedtextStats.put(entry.getKey(), stat);
        }
        // 从明细里取targetvalue(&分隔的当前问题的所有选项),补全未出现的选项,count和ratio均为0
        if (targetvalue != null) {
            for (String option : targetvalue.split("&")) {
                String optionTrim = option.trim();
                if (!matchedtextStats.containsKey(optionTrim)) {
                    Map<String, Object> emptyStat = new HashMap<>();
                    emptyStat.put("count", 0L);
                    emptyStat.put("ratio", 0.0);
                    matchedtextStats.put(optionTrim, emptyStat);
                }
            }
        }
        return matchedtextStats;
    }
 
    /**
     * 取填报明细行数(原 fillCount.size())
     */
    private long countFillRowsByMatchedtext(List<MatchedtextCount> fillRows) {
        if (CollectionUtils.isEmpty(fillRows)) return 0L;
        long rows = 0L;
        for (MatchedtextCount row : fillRows) {
            rows += row.getCount();
        }
        return rows;
    }
 
    /**
     * 获取平均分(聚合版:分值与条数)
     * <p>
     * 口径与 {@link #averageScore(List)} 一致:分子为可解析分值之和,分母为明细行数(含分值为空的行)。
     */
    private Double averageScoreByMatchedtext(List<MatchedtextCount> fillRows) {
        if (CollectionUtils.isEmpty(fillRows)) return 0.0;
        double sum = 0.0;
        long rows = 0L;
        for (MatchedtextCount row : fillRows) {
            if (row.getCount() <= 0L) continue;
            rows += row.getCount();
            if (row.getScore() != null && !row.getScore().isEmpty()) {
                sum += Double.parseDouble(row.getScore()) * row.getCount();
            }
        }
        if (rows == 0L) return 0.0;
        return new BigDecimal(sum / rows).setScale(1, RoundingMode.HALF_UP).doubleValue();
    }
 
    /**
     * 获取最高分(聚合版,口径同 {@link #maxScore(List)}:空列表返回 0.0)
     */
    private Double maxScoreOf(List<String> scores) {
        if (CollectionUtils.isEmpty(scores)) return 0.0;
        return scores.stream().filter(scoreStr -> scoreStr != null && !scoreStr.isEmpty())
                .mapToDouble(Double::parseDouble).max().orElse(0.0);
    }
 
    /**
     * 获取最低分(聚合版,口径同 {@link #minScore(List)}:空列表返回 0.0)
     */
    private Double minScoreOf(List<String> scores) {
        if (CollectionUtils.isEmpty(scores)) return 0.0;
        return scores.stream().filter(scoreStr -> scoreStr != null && !scoreStr.isEmpty())
                .mapToDouble(Double::parseDouble).min().orElse(0.0);
    }
 
    /**
     * 满意度统计用的问题引用:模板id、选项表关联的问题id(可能为 null)、问题内容
     */
    private static class SatScriptRef {
        private final Long templateId;
        private final Long optionScriptId;
        private final String scriptContent;
 
        SatScriptRef(Long templateId, Long optionScriptId, String scriptContent) {
            this.templateId = templateId;
            this.optionScriptId = optionScriptId;
            this.scriptContent = scriptContent;
        }
 
        Long getTemplateId() {
            return templateId;
        }
 
        Long getOptionScriptId() {
            return optionScriptId;
        }
 
        String getScriptContent() {
            return scriptContent;
        }
    }
 
    /**
     * 满意度填报聚合结果:matchedtext + score + targetvalue + 条数
     */
    private static class MatchedtextCount {
        private final String matchedtext;
        private final String score;
        private final String targetvalue;
        private final long count;
 
        MatchedtextCount(String matchedtext, String score, String targetvalue, long count) {
            this.matchedtext = matchedtext;
            this.score = score;
            this.targetvalue = targetvalue;
            this.count = count;
        }
 
        String getMatchedtext() {
            return matchedtext;
        }
 
        String getScore() {
            return score;
        }
 
        String getTargetvalue() {
            return targetvalue;
        }
 
        long getCount() {
            return count;
        }
    }
 
    /**
     * 满意度填报聚合结果(按 matchedtext 版)
     * <p>
     * byTemplateQuestion:按 模板+问题 分组;
     * byTemplate:按模板分组(该模板全部问题),用于兼容原 queryFillCount 在
     * script_content 为 null 时不拼 questiontext 条件的行为。
     */
    private static class SatisfactionFillStatByMatchedtext {
        private final Map<String, List<MatchedtextCount>> byTemplateQuestion = new HashMap<>();
        private final Map<Long, List<MatchedtextCount>> byTemplate = new HashMap<>();
 
        void add(Long templateId, String questiontext, MatchedtextCount row) {
            byTemplate.computeIfAbsent(templateId, key -> new ArrayList<>()).add(row);
            if (questiontext != null) {
                byTemplateQuestion.computeIfAbsent(statKey(templateId, questiontext), key -> new ArrayList<>()).add(row);
            }
        }
 
        List<MatchedtextCount> get(Long templateId, String scriptContent) {
            if (templateId == null) return null;
            if (scriptContent == null) return byTemplate.get(templateId);
            return byTemplateQuestion.get(statKey(templateId, scriptContent));
        }
    }
}