派生自 projectDept/qhighschool

EricsHu
2022-12-05 068fc7f2e81178e55fa191a13709af64b1a163f6
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
package com.qxueyou.scc.exercise.service.impl;
 
import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
 
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
 
import com.qxueyou.scc.base.model.Pager;
import com.qxueyou.scc.base.model.Result;
import com.qxueyou.scc.base.service.impl.CommonAppService;
import com.qxueyou.scc.base.util.ClientUtils;
import com.qxueyou.scc.base.util.CollectionUtils;
import com.qxueyou.scc.base.util.TraceUtils;
import com.qxueyou.scc.exercise.model.ExerciseGroup;
import com.qxueyou.scc.exercise.model.ExerciseGroupItemRe;
import com.qxueyou.scc.exercise.model.ExerciseItem;
import com.qxueyou.scc.exercise.model.ExerciseItemAnalisi;
import com.qxueyou.scc.exercise.model.ExerciseItemOption;
import com.qxueyou.scc.exercise.model.ExerciseItemScore;
import com.qxueyou.scc.exercise.model.ExerciseItemSet;
import com.qxueyou.scc.exercise.service.IExerciseGroupService;
import com.qxueyou.scc.exercise.util.ExerciseUtils;
 
/**
 * 通知管理服务层
 *
 * @author kevin
 * @createTime 2017-11-1
 */
@Service
public class ExerciseGroupService extends CommonAppService implements IExerciseGroupService {
 
    @SuppressWarnings("rawtypes")
    @Autowired
    private RedisTemplate redisTemplate;
 
    private static final Logger log = LoggerFactory.getLogger(ExerciseGroupService.class);
 
    @Override
    public int queryExerciseGroupCount(Map<String, Object> param) {
        // TODO Auto-generated method stub
        return 0;
    }
 
    @Override
    public List<ExerciseGroup> queryExerciseGroupList(Map<String, Object> param, Pager page) {
        // TODO Auto-generated method stub
        return null;
    }
 
    @Override
    public String addExerciseGroup(ExerciseGroup exerciseGroup) {
        TraceUtils.setCreateTrace(exerciseGroup);
        this.insert(exerciseGroup);
        return exerciseGroup.getGroupId();
    }
 
    @Override
    public Result deleteExerciseGroup(String[] groupIds) {
        Result result = new Result(true);
        if (groupIds != null && groupIds.length > 0) {
            String hql = "update ExerciseGroup set deleteFlag = true where groupId=?";
            result = bulkUpdateInLoop(hql, groupIds);
        }
        return result;
    }
 
    @Override
    public Result updateExerciseGroup(ExerciseGroup param) {
        ExerciseGroup exerciseGroup = read(ExerciseGroup.class, param.getGroupId());
        if (exerciseGroup != null) {
            TraceUtils.setUpdateTrace(exerciseGroup);
            exerciseGroup.setGroupRange(ExerciseGroup.GROUP_RANGE_PRIV);
            exerciseGroup.setSubjectId(param.getSubjectId());
            exerciseGroup.setName(param.getName());
            exerciseGroup.setDifficultLevel(param.getDifficultLevel());
        }
        return save(exerciseGroup);
    }
 
    @Override
    public Result doExerciseGroupRealease(String[] groupIds) {
        Map<String, Object> pramMap = null;
        if (groupIds != null && groupIds.length > 0) {
            pramMap = new HashMap<String, Object>(1);
            pramMap.put("examIds", groupIds);
            String hql = "from ExerciseGroup where groupId in (:groupIds)";
            List<ExerciseGroup> lstExerciseGroup = this.findByComplexHql(hql, pramMap, ExerciseGroup.class);
 
            for (ExerciseGroup exerciseGroup : lstExerciseGroup) {
                if (ExerciseGroup.STATUS_DRAFT != exerciseGroup.getStatus()) {
                    return new Result(false, "只有草稿状态的题库,才能发布。");
                }
                exerciseGroup.setStatus(ExerciseGroup.STATUS_PUBLISHED);
                TraceUtils.setUpdateTrace(exerciseGroup);
                save(exerciseGroup);
            }
        } else {
            return new Result(false, "没有选择要发布的题库。");
        }
        return new Result(true);
    }
 
    @Override
    public Result doExerciseGroupRevocation(String[] examIds) {
        Map<String, Object> pramMap = null;
        if (examIds != null && examIds.length > 0) {
            pramMap = new HashMap<String, Object>(1);
            pramMap.put("examIds", examIds);
            String hql = "from ExerciseGroup where examId in (:examIds)";
            List<ExerciseGroup> lstExerciseGroup = this.findByComplexHql(hql, pramMap, ExerciseGroup.class);
            for (ExerciseGroup exerciseGroup : lstExerciseGroup) {
                if (ExerciseGroup.STATUS_DRAFT != exerciseGroup.getStatus()) {
                    return new Result(false, "只有发布状态的题库,才能撤回。");
                }
                exerciseGroup.setStatus(ExerciseGroup.STATUS_DRAFT);
                TraceUtils.setUpdateTrace(exerciseGroup);
                save(exerciseGroup);
            }
        } else {
            return new Result(false, "没有选择要撤回的题库。");
        }
 
        return new Result(true);
    }
 
    @Override
    public ExerciseGroup queryExerciseGroupDetail(String groupId) {
        ExerciseGroup exerciseGroup = this.read(ExerciseGroup.class, groupId);
        if(exerciseGroup!=null){
            exerciseGroup.setItems(this.queryExerciseItemList(exerciseGroup));
        }
        return exerciseGroup;
    }
    @Override
    public ExerciseGroup queryExerciseGroupDetail(String groupId,String batchId) {
        ExerciseGroup exerciseGroup = this.read(ExerciseGroup.class, groupId);
        if(exerciseGroup!=null){
            //根据批次ID查询考试ID
            String hql="select r.examId from ExamBatchClassRe r where r.examBatchId=?";
            String examId = this.findUnique(hql, CollectionUtils.newList(batchId), String.class);
            exerciseGroup.setItems(this.queryExerciseItemList(exerciseGroup,examId));
        }
        return exerciseGroup;
    }
    //补考考试获取试卷设置
    @Override
    public ExerciseGroup queryReExerciseGroupDetail(String groupId,String examId) {
        ExerciseGroup exerciseGroup = this.read(ExerciseGroup.class, groupId);
        if(exerciseGroup!=null){
            exerciseGroup.setItems(this.queryExerciseItemList(exerciseGroup,examId));
        }
        return exerciseGroup;
    }
 
    /**
     * 查询练习题目list
     *
     * @param groupId
     * @return
     */
    @SuppressWarnings("unchecked")
    private List<ExerciseItem> queryExerciseItemList(ExerciseGroup exerciseGroup) {
        BoundValueOperations<String, List<ExerciseItem>> boundValueOperations = redisTemplate.boundValueOps(exerciseGroup.getGroupId());
        List<ExerciseItem> lstItems = boundValueOperations.get();
 
        if(lstItems==null){
            // 1.查询练习题目信息
            StringBuffer hqlBuffer = new StringBuffer(1000);
            hqlBuffer.append("select item from ExerciseItem item, ExerciseGroupItemRe re, ExerciseGroup g");
            hqlBuffer.append(" where item.exerciseId=re.exerciseItemId and re.exerciseGroupId=g.groupId");
            hqlBuffer.append(" and g.groupId = ?  and item.deleteFlag is false  and g.deleteFlag is false");
            //如果是题库按照题目类型排序,其他按照题目顺序排序
            if(exerciseGroup.getType() == ExerciseGroup.TYPE_EXERCISE_GROUP_LIB){
                hqlBuffer.append(" and re.deleteFlag is false order by item.type, re.itemOrder");
            }else{
                hqlBuffer.append(" and re.deleteFlag is false order by re.itemOrder");
            }
 
            lstItems = this.find(hqlBuffer.toString(), CollectionUtils.newList(exerciseGroup.getGroupId()), ExerciseItem.class);
 
            // 为空
            if (lstItems.isEmpty()) {
                return lstItems;
            }
 
            // 组装选项,答案,解析等信息
            lstItems = getCommonExerItemDetail(lstItems, exerciseGroup.getGroupId());
 
            boundValueOperations.setIfAbsent(lstItems);
            boundValueOperations.expire(30, TimeUnit.DAYS);
        }
 
        return lstItems;
    }
    private List<ExerciseItem> queryExerciseItemList(ExerciseGroup exerciseGroup,String examId) {
        BoundValueOperations<String, List<ExerciseItem>> boundValueOperations = redisTemplate.boundValueOps(exerciseGroup.getGroupId());
        List<ExerciseItem> lstItems = boundValueOperations.get();
 
        if(true){
            // 1.查询练习题目信息
            StringBuffer hqlBuffer = new StringBuffer(1000);
            hqlBuffer.append("select item from ExerciseItem item, ExerciseGroupItemRe re, ExerciseGroup g");
            hqlBuffer.append(" where item.exerciseId=re.exerciseItemId and re.exerciseGroupId=g.groupId");
            hqlBuffer.append(" and g.groupId = ?  and item.deleteFlag is false  and g.deleteFlag is false");
            //如果是题库按照题目类型排序,其他按照题目顺序排序
            if(exerciseGroup.getType() == ExerciseGroup.TYPE_EXERCISE_GROUP_LIB){
                hqlBuffer.append(" and re.deleteFlag is false order by item.type, re.itemOrder");
            }else{
                hqlBuffer.append(" and re.deleteFlag is false order by re.itemOrder");
            }
 
            lstItems = this.find(hqlBuffer.toString(), CollectionUtils.newList(exerciseGroup.getGroupId()), ExerciseItem.class);
 
            // 为空
            if (lstItems.isEmpty()) {
                return lstItems;
            }
 
            // 组装选项,答案,解析等信息
            lstItems = getCommonExerItemDetail(lstItems, exerciseGroup.getGroupId(),examId);
 
            boundValueOperations.setIfAbsent(lstItems);
            boundValueOperations.expire(30, TimeUnit.DAYS);
        }
 
        return lstItems;
    }
 
    /**
     * 重新组装练习题 加入分析结果
     *
     * @param lstItems
     * @param exerciseGroupId
     * @param currTitleNumber
     * @return
     */
    private List<ExerciseItem> getCommonExerItemDetail(List<ExerciseItem> lstItems, String exerciseGroupId) {
        // 0.组装参数
        Map<String, Object> argsMap = new HashMap<String, Object>();
        Object[] args = new Object[lstItems.size()];
        for (int i = 0; i < lstItems.size(); i++) {
            args[i] = lstItems.get(i).getExerciseId();
        }
        argsMap.put("exerciseIds", args);
        //查询题目得分
        String hql_itemScores = "from ExerciseItemScore s where s.groupId=:groupId and s.exerciseItemId in (:exerciseIds) and s.deleteFlag is false  order by exerciseItemId";
        List<ExerciseItemScore> lstItemScores = this.findByComplexHql(hql_itemScores, CollectionUtils.newObjectMap("groupId",exerciseGroupId,"exerciseIds",args), ExerciseItemScore.class);
        Map<String, List<ExerciseItemScore>> scoresMap=  new HashMap<String,List<ExerciseItemScore>>(lstItemScores.size());
        ExerciseUtils.packageExerciseItemScore(scoresMap, lstItemScores);
 
        // 1.查询练习题目全站分析
        String hql_analisis = "from ExerciseItemAnalisi  where exerciseItemId in (:exerciseIds)  and deleteFlag is false ";
        List<ExerciseItemAnalisi> lstAnalisis = this.findByComplexHql(hql_analisis, argsMap, ExerciseItemAnalisi.class);
        Map<String, List<ExerciseItemAnalisi>> analisiMap = new HashMap<String, List<ExerciseItemAnalisi>>(lstAnalisis.size());
        for (ExerciseItemAnalisi analisis : lstAnalisis) {
            if(analisiMap.containsKey(analisis.getExerciseItemId())){
                analisiMap.get(analisis.getExerciseItemId()).add(analisis);
            }else{
                analisiMap.put(analisis.getExerciseItemId(),CollectionUtils.newList(ExerciseItemAnalisi.class, analisis));
            }
        }
 
        // 2.查询练习题目答案选项
        Map<String, List<ExerciseItemOption>> optionsMap = new HashMap<String, List<ExerciseItemOption>>(
                lstItems.size());
        Map<String, String> answerMap = new HashMap<String, String>();
        String hql_options = "from ExerciseItemOption where exerciseItemId in (:exerciseIds) and deleteFlag is false order by exerciseItemId, optionOrder ";
        List<ExerciseItemOption> lstAllOptions = this.findByComplexHql(hql_options, argsMap, ExerciseItemOption.class);
 
        // 重新组装练习
        ExerciseUtils.packageExerciseItem(optionsMap, answerMap, lstAllOptions, null);
 
        String exerciseId = null;
        for (ExerciseItem item : lstItems) {
 
            // 4.0 分析结果
            exerciseId = item.getExerciseId();
 
            // 得到练习组id
            if (StringUtils.isNotBlank(exerciseGroupId)) {
                item.setExerciseGroupId(exerciseGroupId);
            }
 
            // 4.3 题目选项
            item.setOptions(optionsMap.get(exerciseId));
 
            item.setAnalisisResult(null);
            item.setAnalysises(null);
            item.setAnalysises(analisiMap.get(exerciseId));
 
            //组装练习题目
            item.setScores(scoresMap.get(exerciseId));
        }
 
        return lstItems;
    }
    /**
     * 重新组装练习题 加入分析结果
     *
     * @param lstItems
     * @param exerciseGroupId
     * @param currTitleNumber
     * @return
     */
    private List<ExerciseItem> getCommonExerItemDetail(List<ExerciseItem> lstItems, String exerciseGroupId,String examId) {
        // 0.组装参数
        Map<String, Object> argsMap = new HashMap<String, Object>();
        Object[] args = new Object[lstItems.size()];
        for (int i = 0; i < lstItems.size(); i++) {
            args[i] = lstItems.get(i).getExerciseId();
        }
        argsMap.put("exerciseIds", args);
 
        //查询题目得分
        String hql_itemScores = "from ExerciseItemScore s where s.groupId=:groupId and s.exerciseItemId in (:exerciseIds) and s.deleteFlag is false  order by exerciseItemId";
        List<ExerciseItemScore> lstItemScores = this.findByComplexHql(hql_itemScores, CollectionUtils.newObjectMap("groupId",exerciseGroupId,"exerciseIds",args), ExerciseItemScore.class);
        Map<String, List<ExerciseItemScore>> scoresMap= new HashMap<String,List<ExerciseItemScore>>();
        log.error("=================================================");
        List<ExerciseItemSet> exerciseItemSets=null;
        if (lstItemScores==null||lstItemScores.size()<=0){
            //根据考试ID查询itemSet
            String hql = "select r from ExerciseItemSet r where r.exerciseInfoId=?";
            exerciseItemSets = this.find(hql, CollectionUtils.newList(examId), ExerciseItemSet.class);
        }else {
            ExerciseUtils.packageExerciseItemScore(scoresMap, lstItemScores);
        }
 
        // 1.查询练习题目全站分析
        String hql_analisis = "from ExerciseItemAnalisi  where exerciseItemId in (:exerciseIds)  and deleteFlag is false ";
        List<ExerciseItemAnalisi> lstAnalisis = this.findByComplexHql(hql_analisis, argsMap, ExerciseItemAnalisi.class);
        Map<String, List<ExerciseItemAnalisi>> analisiMap = new HashMap<String, List<ExerciseItemAnalisi>>(lstAnalisis.size());
        for (ExerciseItemAnalisi analisis : lstAnalisis) {
            if(analisiMap.containsKey(analisis.getExerciseItemId())){
                analisiMap.get(analisis.getExerciseItemId()).add(analisis);
            }else{
                analisiMap.put(analisis.getExerciseItemId(),CollectionUtils.newList(ExerciseItemAnalisi.class, analisis));
            }
        }
 
        // 2.查询练习题目答案选项
        Map<String, List<ExerciseItemOption>> optionsMap = new HashMap<String, List<ExerciseItemOption>>(
                lstItems.size());
        Map<String, String> answerMap = new HashMap<String, String>();
        String hql_options = "from ExerciseItemOption where exerciseItemId in (:exerciseIds) and deleteFlag is false order by exerciseItemId, optionOrder ";
        List<ExerciseItemOption> lstAllOptions = this.findByComplexHql(hql_options, argsMap, ExerciseItemOption.class);
 
        // 重新组装练习
        ExerciseUtils.packageExerciseItem(optionsMap, answerMap, lstAllOptions, null);
 
        String exerciseId = null;
        for (ExerciseItem item : lstItems) {
 
            // 4.0 分析结果
            exerciseId = item.getExerciseId();
 
            // 得到练习组id
            if (StringUtils.isNotBlank(exerciseGroupId)) {
                item.setExerciseGroupId(exerciseGroupId);
            }
 
            // 4.3 题目选项
            item.setOptions(optionsMap.get(exerciseId));
 
            item.setAnalisisResult(null);
            item.setAnalysises(null);
            item.setAnalysises(analisiMap.get(exerciseId));
            //组装练习题目
            item.setScores(scoresMap.get(exerciseId));
            //随机试题没有对应分数,需要根据考试Id从item_set里查询每种题目的分数设置
            if (exerciseItemSets != null ) {
                //遍历每个item
                short type = item.getType();
                //遍历itemset,每个item根据type获取对应类型的分数设置
                for (ExerciseItemSet exerciseItemSet : exerciseItemSets) {
                    if (exerciseItemSet.getItemType() == type) {
                        /**
                         * attribute1: null
                         * attribute2: null
                         * exerciseItemAnswer: null
                         * exerciseItemId: "2c92ad6a710b09db0171b4477f620122"
                         * exerciseItemScoreId: "2c92ad6a72507b08017251baf6ce000d"
                         * groupId: "2c92ad6a72507b08017251ba5c6f0002"
                         * score: "4.00"
                         */
                        List<ExerciseItemScore> exeSets = new ArrayList<>();
                        ExerciseItemScore exerciseItemScore = new ExerciseItemScore();
                        exerciseItemScore.setExerciseItemId(item.getExerciseId());
                        exerciseItemScore.setGroupId(exerciseGroupId);
                        exerciseItemScore.setScore(exerciseItemSet.getRightScore().toString());
                        exeSets.add(exerciseItemScore);
                        item.setScores(exeSets);
                    }
                }
            }
        }
        return lstItems;
    }
 
    @Override
    public int doCopyExerciseGroupItem(ExerciseGroup sourceGroup, ExerciseGroup targetGroup,Short[] itemTypes, int startOrder)
            throws IllegalAccessException, InvocationTargetException {
        //参数判断
        if(sourceGroup==null || targetGroup==null || ArrayUtils.isEmpty(itemTypes)){
            return  0;
        }
 
        //查询题目组与题目关联关系,需要过滤掉在目标题目组中已拷贝过的题目
        String hql = "select r1 from ExerciseGroupItemRe r1,ExerciseItem i where r1.exerciseItemId = i.exerciseId and i.type in(:itemTypes) and r1.deleteFlag is false and r1.exerciseGroupId = :sourceGroupId "
                + " and not exists (select 1 from ExerciseGroupItemRe r2 where r2.deleteFlag is false and r2.exerciseItemId = r1.exerciseItemId  and r2.exerciseGroupId = :targetGroupId ) order by r1.itemOrder ASC ";
 
        Map<String,Object> queryParamMap = new HashMap<String,Object>();
        queryParamMap.put("sourceGroupId", sourceGroup.getGroupId());
        queryParamMap.put("targetGroupId", targetGroup.getGroupId());
        queryParamMap.put("itemTypes", itemTypes);
        List<ExerciseGroupItemRe> lstSourceGroupRe = this.findByComplexHql(hql,queryParamMap,ExerciseGroupItemRe.class);
 
        //查询题目组关联的得分信息,只关联获取没初化过的
        String hql_itemScores = "select s1 from ExerciseItemScore s1,ExerciseItem i where s1.exerciseItemId = i.exerciseId and i.type in(:itemTypes) and s1.groupId=:sourceGroupId and s1.deleteFlag is false and not exists ("
                + " select 1 from ExerciseItemScore s2 where s2.deleteFlag is false and s2.exerciseItemId = s1.exerciseItemId  and s2.groupId =:targetGroupId ) order by s1.exerciseItemId";
        List<ExerciseItemScore> lstItemScores = this.findByComplexHql(hql_itemScores,queryParamMap, ExerciseItemScore.class);
        Map<String, List<ExerciseItemScore>> scoresMap=  new HashMap<String,List<ExerciseItemScore>>(lstItemScores.size());
        ExerciseUtils.packageExerciseItemScore(scoresMap, lstItemScores);
 
        List<ExerciseGroupItemRe> lstTargetItemRe = new ArrayList<ExerciseGroupItemRe>(lstSourceGroupRe.size());
        List<ExerciseItemScore> lstTargetItemScore = new ArrayList<ExerciseItemScore>(lstSourceGroupRe.size());
 
        int copyItemSize=0;
        if(lstSourceGroupRe!=null && lstSourceGroupRe.size()>0){
            //更新item的顺序号
            this.bulkUpdate("update ExerciseGroupItemRe r set r.itemOrder=r.itemOrder+"+lstSourceGroupRe.size()
                +" where r.exerciseGroupId=? and r.itemOrder>? and r.deleteFlag is false ", new Object[]{targetGroup.getGroupId(),startOrder});
 
            //拷贝item
            copyItemSize=lstSourceGroupRe.size();
            int itemOrder = startOrder;
            ExerciseItemScore objItemScore = null;
            ExerciseGroupItemRe ojbItemRe=null;
            for (ExerciseGroupItemRe it : lstSourceGroupRe) {
                ojbItemRe = new ExerciseGroupItemRe();
                BeanUtils.copyProperties(it, ojbItemRe);
                ojbItemRe.setItemOrder(++itemOrder);
                ojbItemRe.setRelationId(null);
                ojbItemRe.setExerciseGroupId(targetGroup.getGroupId());
                lstTargetItemRe.add(ojbItemRe);
 
                //复制题目分数信息
                List<ExerciseItemScore> scores = scoresMap.get(it.getExerciseItemId());
                if(scores!=null && scores.size()>0){
                    for(int i=0;i<scores.size();i++){
                        objItemScore = new ExerciseItemScore();
                        BeanUtils.copyProperties(scores.get(i), objItemScore);
                        objItemScore.setExerciseItemScoreId(null);
                        objItemScore.setGroupId(targetGroup.getGroupId());
                        lstTargetItemScore.add(objItemScore);
                    }
                }
            }
            this.saveOrUpdateAll(lstTargetItemRe);
            this.saveOrUpdateAll(lstTargetItemScore);
        }
        return copyItemSize;
    }
 
    @Override
    public int doCopyExerciseGroupItem(ExerciseGroup sourceGroup, ExerciseGroup targetGroup,String[] exerciseItemIds, int startOrder)
            throws IllegalAccessException, InvocationTargetException {
        //参数判断
        if(sourceGroup==null || targetGroup==null || ArrayUtils.isEmpty(exerciseItemIds)){
            return  0;
        }
 
        //查询题目组与题目关联关系,需要过滤掉在目标题目组中已拷贝过的题目
        String hql = "select r1 from ExerciseGroupItemRe r1 where r1.exerciseItemId in(:exerciseItemIds) and r1.deleteFlag is false and r1.exerciseGroupId = :sourceGroupId "
                + " and not exists (select 1 from ExerciseGroupItemRe r2 where r2.deleteFlag is false and r2.exerciseItemId = r1.exerciseItemId  and r2.exerciseGroupId = :targetGroupId ) order by r1.itemOrder ASC ";
 
        Map<String,Object> queryParamMap = new HashMap<String,Object>();
        queryParamMap.put("sourceGroupId", sourceGroup.getGroupId());
        queryParamMap.put("targetGroupId", targetGroup.getGroupId());
        queryParamMap.put("exerciseItemIds", exerciseItemIds);
        List<ExerciseGroupItemRe> lstSourceGroupRe = this.findByComplexHql(hql,queryParamMap,ExerciseGroupItemRe.class);
 
        //查询题目组关联的得分信息,只关联获取没初化过的
        String hql_itemScores = "select s1 from ExerciseItemScore s1 where s1.exerciseItemId in (:exerciseItemIds) and  s1.groupId=:sourceGroupId and s1.deleteFlag is false and not exists ("
                + " select 1 from ExerciseItemScore s2 where s2.deleteFlag is false and s2.exerciseItemId = s1.exerciseItemId  and s2.groupId =:targetGroupId ) order by s1.exerciseItemId";
        List<ExerciseItemScore> lstItemScores = this.findByComplexHql(hql_itemScores,queryParamMap, ExerciseItemScore.class);
        Map<String, List<ExerciseItemScore>> scoresMap=  new HashMap<String,List<ExerciseItemScore>>(lstItemScores.size());
        ExerciseUtils.packageExerciseItemScore(scoresMap, lstItemScores);
 
        List<ExerciseGroupItemRe> lstTargetItemRe = new ArrayList<ExerciseGroupItemRe>(lstSourceGroupRe.size());
        List<ExerciseItemScore> lstTargetItemScore = new ArrayList<ExerciseItemScore>(lstSourceGroupRe.size());
 
        int copyItemSize=0;
        if(lstSourceGroupRe!=null && lstSourceGroupRe.size()>0){
            //更新item的顺序号
            this.bulkUpdate("update ExerciseGroupItemRe r set r.itemOrder=r.itemOrder+"+lstSourceGroupRe.size()
                +" where r.exerciseGroupId=? and r.itemOrder>? and r.deleteFlag is false ", new Object[]{targetGroup.getGroupId(),startOrder});
 
            //拷贝item
            copyItemSize=lstSourceGroupRe.size();
            int itemOrder = startOrder;
            ExerciseItemScore objItemScore = null;
            ExerciseGroupItemRe ojbItemRe=null;
            for (ExerciseGroupItemRe it : lstSourceGroupRe) {
                ojbItemRe = new ExerciseGroupItemRe();
                BeanUtils.copyProperties(it, ojbItemRe);
                ojbItemRe.setItemOrder(++itemOrder);
                ojbItemRe.setRelationId(null);
                ojbItemRe.setExerciseGroupId(targetGroup.getGroupId());
                lstTargetItemRe.add(ojbItemRe);
 
                //复制题目分数信息
                List<ExerciseItemScore> scores = scoresMap.get(it.getExerciseItemId());
                if(scores!=null && scores.size()>0){
                    for(int i=0;i<scores.size();i++){
                        objItemScore = new ExerciseItemScore();
                        BeanUtils.copyProperties(scores.get(i), objItemScore);
                        objItemScore.setExerciseItemScoreId(null);
                        objItemScore.setGroupId(targetGroup.getGroupId());
                        lstTargetItemScore.add(objItemScore);
                    }
                }
            }
            this.saveOrUpdateAll(lstTargetItemRe);
            this.saveOrUpdateAll(lstTargetItemScore);
        }
        return copyItemSize;
    }
 
    @SuppressWarnings("unchecked")
    @Override
    public Result doExchangeExamPaperGroupItemOrder(String groupId, String exerciseItemId1, String exerciseItemId2) {
        String hql = "from ExerciseGroupItemRe where deleteFlag is false and exerciseGroupId = :groupId and exerciseItemId in (:exerciseItemIds)";
 
        Map<String, Object> queryParams = new HashMap<String, Object>();
        queryParams.put("groupId", groupId);
        queryParams.put("exerciseItemIds", new String[] { exerciseItemId1, exerciseItemId2 });
        List<ExerciseGroupItemRe> lstItemRe = this.findByComplexHql(hql, queryParams, ExerciseGroupItemRe.class);
        // 交换顺序号
        int tempOrder = lstItemRe.get(0).getItemOrder();
        lstItemRe.get(0).setItemOrder(lstItemRe.get(1).getItemOrder());
        lstItemRe.get(1).setItemOrder(tempOrder);
        this.saveOrUpdateAll(lstItemRe);
        this.redisTemplate.delete(groupId);
        return new Result(true);
    }
 
    @Override
    public Result doPublishExerciseLib(String[] groupIds) {
        Map<String, Object> pramMap = null;
        if (groupIds != null && groupIds.length > 0) {
            pramMap = new HashMap<String, Object>(2);
            pramMap.put("type", ExerciseGroup.TYPE_EXERCISE_GROUP_LIB);
            pramMap.put("groupIds", groupIds);
 
            String hql = "from ExerciseGroup where  type=:type and  groupId in (:groupIds)";
            List<ExerciseGroup> lstExerciseLibs = this.findByComplexHql(hql, pramMap, ExerciseGroup.class);
 
            for (ExerciseGroup exerciseGroup : lstExerciseLibs) {
                if (ExerciseGroup.STATUS_DRAFT != exerciseGroup.getStatus()) {
                    return new Result(false, "只有草稿状态的题库,才能发布。");
                }
                //判断题库中是否有题,有题目的题库才能发布
                if(exerciseGroup.getAllCount()==null || exerciseGroup.getAllCount().intValue()<=0){
                    return new Result(false, "只有已经配置题目的题库,才能发布。");
                }
                exerciseGroup.setStatus(ExerciseGroup.STATUS_PUBLISHED);
                TraceUtils.setUpdateTrace(exerciseGroup);
                save(exerciseGroup);
            }
        } else {
            return new Result(false, "没有选择要发布的题库。");
        }
        return new Result(true);
    }
 
    @Override
    public Result doRevokeExerciseLib(String[] groupIds) {
        Map<String, Object> pramMap = null;
        if (groupIds != null && groupIds.length > 0) {
            pramMap = new HashMap<String, Object>(2);
            pramMap.put("type", ExerciseGroup.TYPE_EXERCISE_GROUP_LIB);
            pramMap.put("groupIds", groupIds);
            String hql = "from ExerciseGroup where  type=:type and  groupId in (:groupIds)";
            List<ExerciseGroup> lstExerciseLibs = this.findByComplexHql(hql, pramMap, ExerciseGroup.class);
 
            for (ExerciseGroup exerciseGroup : lstExerciseLibs) {
                if (ExerciseGroup.STATUS_PUBLISHED != exerciseGroup.getStatus()) {
                    return new Result(false, "只有发布状态的题库,才能撤回。");
                }
                exerciseGroup.setStatus(ExerciseGroup.STATUS_DRAFT);
                TraceUtils.setUpdateTrace(exerciseGroup);
                save(exerciseGroup);
            }
        } else {
            return new Result(false, "没有选择要撤回的题库。");
        }
        return new Result(true);
    }
 
    @Override
    @SuppressWarnings("unchecked")
    public String doCreateRandomExerciseGroup(String newGroupName,short newGroupType,String [] sourceGroupIds,List<ExerciseItemSet> lstExerciseItemSet){
        Result result = this.doCreateRandomExerciseItem(sourceGroupIds,lstExerciseItemSet );
 
        if (!result.isSuccess()) {
            return null;
        }
 
        List<Map<String, Object>> lstExerciseItem = (List<Map<String, Object>>) result.getData();
 
        ExerciseGroup group = new ExerciseGroup();
        group.setDeleteFlag(false);
        group.setName(newGroupName);
        group.setOrderNum(BigInteger.ZERO);
        group.setType(newGroupType);
        group.setOrgId(ClientUtils.getOrgId());
        group.setStatus(ExerciseGroup.STATUS_PUBLISHED);
        group.setAllCount(BigInteger.valueOf(lstExerciseItem.size()));
        TraceUtils.setCreateTrace(group);
        this.save(group);
 
        int k = 1;
        for (Map<String, Object> item : lstExerciseItem) {
            ExerciseGroupItemRe itemRe = new ExerciseGroupItemRe();
            itemRe.setDocOrder(item.get("docOrder") == null ? 0 : (Integer) item.get("docOrder"));
            itemRe.setItemOrder(k);
            itemRe.setExerciseGroupId(group.getGroupId());
            itemRe.setExerciseItemId((String) item.get("exerciseId"));
            itemRe.setDeleteFlag(false);
            k++;
            this.save(itemRe);
        }
        return group.getGroupId();
    }
 
 
    /**
     * 创建考试题目
     *
     * @param groupIds
     * @return
     */
    private Result doCreateRandomExerciseItem(String[] groupIds, List<ExerciseItemSet> lstExerciseItemSet) {
        if (groupIds.length == 0 || lstExerciseItemSet == null || lstExerciseItemSet.size() == 0) {
            return new Result(false, "参数错误");
        }
 
        List<Map<String, Object>> lstExerciseItem = new ArrayList<Map<String, Object>>();
 
        //按照题型(单选题(1),多选题(2),判断题(3), 填空题(8),简答题(4))排序lstExerciseItemSet
        Collections.sort(lstExerciseItemSet, new Comparator<ExerciseItemSet>(){
            @Override
            public int compare(ExerciseItemSet o1, ExerciseItemSet o2) {
                int type1 = o1.getItemType()==ExerciseItem.TYPE_ESSAY_QUESTION?Short.MAX_VALUE:o1.getItemType();
                int type2 = o2.getItemType()==ExerciseItem.TYPE_ESSAY_QUESTION?Short.MAX_VALUE:o2.getItemType();
                return type1-type2;
            }
        });
 
        String[] paramGroupIds=null;
        for (ExerciseItemSet itemSet : lstExerciseItemSet) {
            if(StringUtils.isEmpty(itemSet.getSourceGroupId())){
                paramGroupIds = groupIds;
            }else{
                paramGroupIds = new String[]{itemSet.getSourceGroupId()};
            }
 
            List<Map<String, Object>> lstItem = this.findListWithMapByHql(
                    "select i.exerciseId as exerciseId, r.docOrder as docOrder"
                            + " from ExerciseGroupItemRe r, ExerciseItem i where i.deleteFlag is false and r.deleteFlag is false"
                            + " and r.exerciseItemId = i.exerciseId and r.exerciseGroupId in (:exerciseGroupId) and type = :type",
                    CollectionUtils.newObjectMap("exerciseGroupId", paramGroupIds, "type", itemSet.getItemType()));
 
            if (lstItem.size() < itemSet.getItemCount()) {
                return new Result(false, "题目数据不够,请增加题库的题目或者减少试卷的题数");
            }
 
            lstExerciseItem.addAll(this.getRandomList(lstItem, itemSet.getItemCount()));
        }
 
        return new Result(true, "", lstExerciseItem);
    }
 
    /**
     * 随机获取List中若干数据
     *
     * @param paramList
     * @param count
     * @return
     */
    private List<Map<String, Object>> getRandomList(List<Map<String, Object>> paramList, int count) {
        if (paramList.size() < count) {
            return paramList;
        }
        Random random = new Random();
        List<Integer> tempList = new ArrayList<Integer>();
        List<Map<String, Object>> newList = new ArrayList<Map<String, Object>>();
        int temp = 0;
        for (int i = 0; i < count; i++) {
            temp = random.nextInt(paramList.size());// 将产生的随机数作为被抽list的索引
            if (!tempList.contains(temp)) {
                tempList.add(temp);
                newList.add(paramList.get(temp));
            } else {
                i--;
            }
        }
        return newList;
    }
 
    /**
     * 获取题库中各种题型的数量
     * @param groupIds
     * @return
     */
    @Override
    public List<ExerciseGroup> queryExerciseGroupItemsStatistic(String[] groupIds){
        Map<String,ExerciseGroup> resultMap =null;
        if(groupIds!=null && groupIds.length>0){
            resultMap = new LinkedHashMap<String,ExerciseGroup>(groupIds.length);
            String hql = " select g.groupId,g.name,i.type,count(i.type) from ExerciseGroup g,ExerciseGroupItemRe r,ExerciseItem i where g.groupId in (:groupIds) and  "
                    + " g.groupId=r.exerciseGroupId  and r.exerciseItemId = i.exerciseId and r.deleteFlag is false group by r.exerciseGroupId,i.type";
            Map<String,Object> param =new HashMap<String,Object>();
            param.put("groupIds", groupIds);
            List<Object[]> lstItemStatics = this.findByComplexHql(hql, param, Object[].class);
 
            ExerciseGroup tempGroup = null;
            String tempGroupId=null;
            String tempGroupName=null;
            short tempType= 0;
            int tempCount=0;
            for(int i=0;i<lstItemStatics.size();i++){
                tempGroupId= (String) lstItemStatics.get(i)[0];
                tempGroupName=(String) lstItemStatics.get(i)[1];
                tempType = (Short) lstItemStatics.get(i)[2];
                tempCount = ((Long) lstItemStatics.get(i)[3]).intValue();
 
                if(resultMap.get(tempGroupId)==null){
                    tempGroup = new ExerciseGroup();
                    tempGroup.setGroupId(tempGroupId);
                    tempGroup.setName(tempGroupName);
                    resultMap.put(tempGroupId, tempGroup);
                }else{
                    tempGroup = resultMap.get(tempGroupId);
                }
 
                if(tempType==ExerciseItem.TYPE_SINGLE_SELECT){
                    tempGroup.setSingleSelectCount(tempCount);
                }else if(tempType==ExerciseItem.TYPE_MULTI_SELECT){
                    tempGroup.setMultiSelectCount(tempCount);
                }else if(tempType==ExerciseItem.TYPE_TRUE_OR_FALSE){
                    tempGroup.setJudgeCount(tempCount);
                }else if(tempType==ExerciseItem.TYPE_ESSAY_QUESTION){
                    tempGroup.setQuestionCount(tempCount);
                }else if(tempType==ExerciseItem.TYPE_FILL_BLANKS){
                    tempGroup.setFillBlanksCount(tempCount);
                }
            }
        }
        return  new ArrayList<ExerciseGroup>( resultMap.values());
    }
 
 
     @Override
     public String [] queryGroupNamesByIds(String[] groupIds){
            if(groupIds!=null && groupIds.length==0){
                return null;
            }
 
            String [] groupNames = null;
 
            List<Map<String,Object>> lstResult= this.findListWithMapByHql("select g.groupId as groupId ,g.name as groupName from ExerciseGroup g where g.groupId in (:groupIds) ",
                    CollectionUtils.newObjectMap("groupIds",groupIds));
 
            if(lstResult!=null && lstResult.size()==groupIds.length){
                Map<String,String> map= new HashMap<String,String>(lstResult.size());
                groupNames =new String[groupIds.length];
 
                for(Map<String,Object> item:lstResult){
                    map.put((String)item.get("groupId"), (String)item.get("groupName"));
                }
 
                for(int i=0;i<groupIds.length;i++){
                    groupNames[i]= map.get(groupIds[i]);
                }
            }
 
            return groupNames;
        }
 
 
 
 
 
 
 
}