heheng
2025-06-25 c5cd059cbf5cec74bf82f1dab96235eaeb60151b
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
package com.gkhy.exam.system.service.impl;
 
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gkhy.exam.common.api.CommonPage;
import com.gkhy.exam.common.api.CommonResult;
import com.gkhy.exam.common.domain.entity.SysUser;
import com.gkhy.exam.common.domain.model.LoginUserDetails;
import com.gkhy.exam.common.enums.PaperStudentStateEnum;
import com.gkhy.exam.common.enums.PrivatizeEnum;
import com.gkhy.exam.common.enums.QuestionTypeEnum;
import com.gkhy.exam.common.enums.UserTypeEnum;
import com.gkhy.exam.common.exception.ApiException;
import com.gkhy.exam.common.utils.PageUtils;
import com.gkhy.exam.common.utils.SecurityUtils;
import com.gkhy.exam.common.utils.StringUtils;
import com.gkhy.exam.system.domain.ExExamPaper;
import com.gkhy.exam.system.domain.ExPaperStudent;
import com.gkhy.exam.system.domain.ExQuestion;
import com.gkhy.exam.system.domain.ExQuestionBank;
import com.gkhy.exam.system.mapper.ExExamPaperMapper;
import com.gkhy.exam.system.mapper.ExPaperStudentMapper;
import com.gkhy.exam.system.mapper.ExQuestionBankMapper;
import com.gkhy.exam.system.mapper.ExQuestionMapper;
import com.gkhy.exam.system.service.ExQuestionService;
import org.apache.poi.ss.usermodel.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
 
/**
 * <p>
 * 考题表 服务实现类
 * </p>
 *
 * @author kzy
 * @since 2024-06-06 13:53:17
 */
@Service
public class ExQuestionServiceImpl extends ServiceImpl<ExQuestionMapper, ExQuestion> implements ExQuestionService {
    @Autowired
    private ExPaperStudentMapper paperStudentMapper;
    @Autowired
    private ExExamPaperMapper examPaperMapper;
    @Autowired
    private ExQuestionBankMapper questionBankMapper;
 
    @Override
    public CommonPage selectQuestionList(ExQuestion question) {
//        if(question.getBankId()==null){
//            throw new ApiException("题库id不能为空");
//        }
//        ExQuestionBank questionBank=questionBankMapper.selectById(question.getBankId());
//        if(!questionBank.getPrivatize().equals(PrivatizeEnum.PUBLIC.getCode())){
//            SysUser currentUser=SecurityUtils.getLoginUser().getUser();
//            if(!currentUser.getUserType().equals(UserTypeEnum.SYSTEM_USER.getCode())){
//                if(!question.getCompanyId().equals(currentUser.getCompanyId())){
//                    throw new ApiException("无权限查看其它企业题目");
//                }
//            }
//        }
        SysUser currentUser=SecurityUtils.getLoginUser().getUser();
        if(!currentUser.getUserType().equals(UserTypeEnum.SYSTEM_USER.getCode())){
            question.setCompanyId(currentUser.getCompanyId());
        }
        PageUtils.startPage();
        List<ExQuestion> questionList=baseMapper.selectQuestionList(question);
        return CommonPage.restPage(questionList);
    }
 
    @Override
    public ExQuestion selectQuestionById(Long questionId) {
        ExQuestion question= baseMapper.selectByQuestionId(questionId);
        if(question.getPrivatize().equals(PrivatizeEnum.PUBLIC.getCode())){
            return question;
        }
        SysUser currentUser=SecurityUtils.getLoginUser().getUser();
        if(currentUser.getUserType().equals(UserTypeEnum.SYSTEM_USER.getCode())){
            return question;
        }
        if(!question.getCompanyId().equals(currentUser.getCompanyId())){
            throw new ApiException("无权限查看其它企业题目");
        }
        return question;
    }
 
    @Override
    public int insertQuestion(ExQuestion question) {
        checkUserAllowed(question);
        SysUser user= SecurityUtils.getLoginUser().getUser();
        int totalCount=questionBankMapper.selectCountByBankId(question.getBankId());
        if(totalCount>1000){
            throw new ApiException("题库题目数量超过1000,不能再新增");
        }
        //公开的题库新增题目,题目也是公开
        ExQuestionBank questionBank=questionBankMapper.selectById(question.getBankId());
        if(user.getUserType().equals(UserTypeEnum.SYSTEM_USER.getCode())&&questionBank.getPrivatize().equals(PrivatizeEnum.PRIVATE.getCode())){
            throw new ApiException("管理员不允许在私有题库创建题目");
        }else if (user.getUserType().equals(UserTypeEnum.SYSTEM_USER.getCode())&&questionBank.getPrivatize().equals(PrivatizeEnum.PUBLIC.getCode())){
            question.setPrivatize(PrivatizeEnum.PUBLIC.getCode());
        }else{
            question.setCompanyId(user.getCompanyId());
            question.setPrivatize(PrivatizeEnum.PRIVATE.getCode());
        }
        validData(question);
        question.setCreateBy(user.getUsername());
        int row=baseMapper.insert(question);
        if(row<1){
            throw new ApiException("新增题目失败");
        }
        return row;
    }
 
    @Override
    public int updateQuestion(ExQuestion question) {
        validData(question);
        checkUserAllowed(question);
        question.setUpdateBy(SecurityUtils.getUsername());
        int row=baseMapper.updateById(question);
        if(row<1){
            throw new ApiException("编辑题目失败");
        }
        return row;
    }
 
    public void validData(ExQuestion question){
        if(!question.getQuestionType().equals(QuestionTypeEnum.JUDGE.getCode())&&!question.getQuestionType().equals(QuestionTypeEnum.EASY.getCode())){
            if(StringUtils.isBlank(question.getContent())){
                throw new ApiException("题目内容不能为空");
            }
            try {
                JSONObject jsonObject = JSONObject.parseObject(question.getContent());
            }catch (Exception e){
                throw new ApiException("题目内容json格式不正确");
            }
            //确保答案是按字母顺序排序
            String answer=question.getAnswer();
            if(answer.contains(",")){
                String[] ans = answer.split(",");
                Arrays.sort(ans);
                question.setAnswer(String.join(",",ans));
            }
        }
        
    }
 
    public void checkUserAllowed(ExQuestion question) {
        SysUser currentUser= SecurityUtils.getLoginUser().getUser();
        if(currentUser.getUserType().equals(UserTypeEnum.SYSTEM_USER.getCode())){
            return;
        }
        if(currentUser.getUserType().equals(UserTypeEnum.STUDENT.getCode())){
            throw new ApiException("没有权限操作");
        }
        if(question.getCompanyId()!=null&&!currentUser.getCompanyId().equals(question.getCompanyId())){
            throw new ApiException("没有权限操作其他企业题目");
        }
    }
 
    @Override
    public int deleteQuestionById(Long questionId) {
        checkUserAllowed(baseMapper.selectById(questionId));
        return baseMapper.deleteById(questionId);
    }
 
    @Override
    public List<Map> getExerciseQuestionList(Long bankId) {
        return baseMapper.getExerciseQuestionList(bankId,SecurityUtils.getUserId());
    }
 
    @Override
    public ExQuestion getExerciseQuestionById(Long questionId) {
        return baseMapper.getExeriseQuestionById(questionId,SecurityUtils.getUserId());
    }
 
    @Override
    public List<ExQuestion> getExerciseQuestionByIds(List<Long> questionIds) {
        if(questionIds==null|| questionIds.isEmpty()){
            throw new ApiException("题目id列表不能为空");
        }
        if(questionIds.size()>30){
            throw new ApiException("批量id数量超过阀值");
        }
        return baseMapper.getExeriseQuestionByIds(questionIds,SecurityUtils.getUserId());
    }
 
    @Override
    public List<Map> getPaperQuestionList(Long paperId,Integer viewType) {
        LambdaQueryWrapper<ExPaperStudent> lambdaQueryWrapper = Wrappers.<ExPaperStudent>lambdaQuery()
                .eq(ExPaperStudent::getPaperId, paperId)
                .eq(ExPaperStudent::getStudentId, SecurityUtils.getUserId());
        ExPaperStudent paperStudent=paperStudentMapper.selectOne(lambdaQueryWrapper);
        if(paperStudent==null){
            throw new ApiException("您分配的试卷未查询到");
        }
        Long currentDateTime=System.currentTimeMillis();
        if(viewType==1){//更新考试开始时间
            if(paperStudent.getState()!= PaperStudentStateEnum.WAIT_EXAM.getCode()){
                throw new ApiException("考试已完成,不能重复考试");
            }
            ExExamPaper examPaper = examPaperMapper.selectById(paperStudent.getPaperId());
            if(examPaper.getLimited()==1){
                if(paperStudent.getStartTime()!=null && (currentDateTime-paperStudent.getStartTime()>=examPaper.getLimitTime()*60*1000)){
//                    paperStudent.setCompleted(1);
//                    paperStudentMapper.updateById(paperStudent);
                    throw new ApiException("考试已超时,不能再考试");
                }
                LocalDateTime deadline = examPaper.getDeadline();
                if(currentDateTime-deadline.toInstant(ZoneOffset.of("+8")).toEpochMilli()>0){
//                    paperStudent.setCompleted(1);
//                    paperStudentMapper.updateById(paperStudent);
                    throw new ApiException("已过考试截止时间,不能再考试");
                }
            }
            if(paperStudent.getStartTime()==null) {
                int row = paperStudentMapper.updateById(new ExPaperStudent().setId(paperStudent.getId()).setPaperId(paperStudent.getPaperId()).setStudentId(paperStudent.getStudentId()).setStartTime(currentDateTime));
                if (row < 1) {
                    throw new ApiException("设置考试开始时间失败");
                }
            }
        }else{
            if(!Objects.equals(paperStudent.getState(), PaperStudentStateEnum.DONE_REVIEW.getCode())){
//                if(paperStudent.getStartTime()!=null) {//判断考卷是否已完成
//                    ExExamPaper examPaper = examPaperMapper.selectById(paperStudent.getPaperId());
//                    if(examPaper.getLimited()==1) {
//                        if (currentDateTime-paperStudent.getStartTime()>=examPaper.getLimitTime()*60*1000){
//                            paperStudent.setCompleted(1);
//                            paperStudentMapper.updateById(paperStudent);
//                        }
//                    }
//                }
                throw new ApiException("试卷未审批完,无法查看");
            }
        }
        return baseMapper.getPaperQuestionList(paperId,paperStudent.getState(),SecurityUtils.getUserId(),viewType);
    }
 
    @Override
    public ExQuestion getPaperQuestionById(Long paperId, Long questionId) {
        LambdaQueryWrapper<ExPaperStudent> lambdaQueryWrapper = Wrappers.<ExPaperStudent>lambdaQuery()
                .eq(ExPaperStudent::getPaperId, paperId)
                .eq(ExPaperStudent::getStudentId, SecurityUtils.getUserId());
        ExPaperStudent paperStudent=paperStudentMapper.selectOne(lambdaQueryWrapper);
        if(paperStudent==null){
            throw new ApiException("您分配的试卷未查询到");
        }
        return baseMapper.getPaperQuestionById(paperId,questionId,paperStudent.getState(),SecurityUtils.getUserId());
    }
 
    @Override
    public List<ExQuestion> getPaperQuestionByIds(Long paperId, List<Long> questionIds) {
        if(questionIds.size()>30){
            throw new ApiException("批量id数量超过阀值");
        }
        LambdaQueryWrapper<ExPaperStudent> lambdaQueryWrapper = Wrappers.<ExPaperStudent>lambdaQuery()
                .eq(ExPaperStudent::getPaperId, paperId)
                .eq(ExPaperStudent::getStudentId, SecurityUtils.getUserId());
        ExPaperStudent paperStudent=paperStudentMapper.selectOne(lambdaQueryWrapper);
        if(paperStudent==null){
            throw new ApiException("您分配的试卷未查询到");
        }
        return baseMapper.getPaperQuestionByIds(paperId,questionIds,paperStudent.getState(),SecurityUtils.getUserId());
    }
 
    @Override
    public List<Long> getExerciseErrorQuestionList(Long bankId) {
        return baseMapper.getExerciseErrorQuestionList(bankId,SecurityUtils.getUserId());
    }
 
    @Override
    public List<ExQuestion> selectQuestionByPaperId(Long paperId) {
        return baseMapper.selectQuestionByPaperId(paperId);
    }
 
    @Override
    public CommonResult uploadQuestion(@NotNull MultipartFile file) throws IOException {
        Workbook workbook = WorkbookFactory.create(file.getInputStream());
        Sheet sheetAt = workbook.getSheetAt(0);
        List<ExQuestion> exQuestions = new ArrayList<>();
        LoginUserDetails loginUser = SecurityUtils.getLoginUser();
        for (int i = 0; i <sheetAt.getLastRowNum(); i++) {
            Row row = sheetAt.getRow(i + 1);
            ExQuestion exQuestion = new ExQuestion();
            if (row!=null){
                exQuestion.setQuestionType((int)row.getCell(0).getNumericCellValue());
                exQuestion.setBankId((long)row.getCell(1).getNumericCellValue());
                exQuestion.setAnswer(row.getCell(2).getStringCellValue());
                exQuestion.setTitle(row.getCell(3).getStringCellValue());
                NhoooRootBean nhoooRootBean = new NhoooRootBean();
                List<Items> items1 = new ArrayList<>();
                String cellValue4 = getCellValue(row.getCell(4));
                if (cellValue4!=null){
                    Items items = new Items();
                    items.setPrefix("A");
                    items.setContent(cellValue4);
                    items1.add(items);
                }
                String cellValue5 = getCellValue(row.getCell(5));
                if (cellValue5!=null){
                    Items items = new Items();
                    items.setPrefix("B");
                    items.setContent(cellValue5);
                    items1.add(items);
                }
                String cellValue6 = getCellValue(row.getCell(6));
                if (cellValue6!=null){
                    Items items = new Items();
                    items.setPrefix("C");
                    items.setContent(cellValue6);
                    items1.add(items);
                }
                String cellValue7 = getCellValue(row.getCell(7));
                if (cellValue7!=null){
                    Items items = new Items();
                    items.setPrefix("D");
                    items.setContent(cellValue7);
                    items1.add(items);
                }
                String cellValue8 = getCellValue(row.getCell(8));
                if (cellValue8!=null){
                    Items items = new Items();
                    items.setPrefix("E");
                    items.setContent(cellValue8);
                    items1.add(items);
                }
                String cellValue9 = getCellValue(row.getCell(8));
                if (cellValue9!=null){
                    Items items = new Items();
                    items.setPrefix("F");
                    items.setContent(cellValue9);
                    items1.add(items);
                }
                String cellValue10 = getCellValue(row.getCell(10));
                if (cellValue10!=null){
                    Items items = new Items();
                    items.setPrefix("G");
                    items.setContent(cellValue10);
                    items1.add(items);
                }
                String cellValue11 = getCellValue(row.getCell(11));
                if (cellValue11!=null){
                    Items items = new Items();
                    items.setPrefix("H");
                    items.setContent(cellValue11);
                    items1.add(items);
                }
                nhoooRootBean.setAnalyze("");
                nhoooRootBean.setItems(items1);
                exQuestion.setContent(JSONObject.toJSONString(nhoooRootBean));
                exQuestion.setPrivatize(0);
                exQuestion.setCreateBy(loginUser.getUsername());
                exQuestion.setCreateTime(LocalDateTime.now());
                exQuestion.setUpdateBy(loginUser.getUsername());
                exQuestion.setUpdateTime(LocalDateTime.now());
                exQuestion.setCompanyId(loginUser.getUser().getCompanyId());
                exQuestion.setStatus(0);
                exQuestions.add(exQuestion);
            }
        }
        int i = baseMapper.saveBatch(exQuestions);
        if (i<1){
            throw new ApiException("导入题目失败");
        }
        workbook.close();
        return CommonResult.success();
    }
 
 
    private String getCellValue(Cell cell) {
        if (cell == null) {
            return null;
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return null;
        }
    }
 
    public class NhoooRootBean {
 
        private String analyze;
        private List<Items> itemsList;
        public void setAnalyze(String analyze) {
            this.analyze = analyze;
        }
        public String getAnalyze() {
            return analyze;
        }
 
        public void setItems(List<Items> items) {
            this.itemsList = items;
        }
        public List getItems() {
            return itemsList;
        }
 
    }
 
    public class Items {
 
        private String prefix;
        private String content;
        public void setPrefix(String prefix) {
            this.prefix = prefix;
        }
        public String getPrefix() {
            return prefix;
        }
 
        public void setContent(String content) {
            this.content = content;
        }
        public String getContent() {
            return content;
        }
 
    }
 
}