ExamService.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2017~2021 LARAVEL研发中心
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://www.laravel.cn
  8. // +----------------------------------------------------------------------
  9. // | Author: laravel开发员 <laravel.qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace App\Services\Api;
  12. use App\Models\ExamAccessLogModel;
  13. use App\Models\ExamAnswerModel;
  14. use App\Models\ExamAnswerTopicModel;
  15. use App\Models\ExamPaperModel;
  16. use App\Models\ExamTopicModel;
  17. use App\Models\MemberAnswerRankModel;
  18. use App\Services\BaseService;
  19. use App\Services\ConfigService;
  20. use App\Services\DeepSeekService;
  21. use App\Services\RedisService;
  22. use Illuminate\Support\Facades\DB;
  23. /**
  24. * 答题服务-服务类
  25. * @author laravel开发员
  26. * @since 2020/11/11
  27. * @package App\Services\Api
  28. */
  29. class ExamService extends BaseService
  30. {
  31. // 静态对象
  32. protected static $instance = null;
  33. /**
  34. * 构造函数
  35. * @author laravel开发员
  36. * @since 2020/11/11
  37. */
  38. public function __construct()
  39. {
  40. $this->model = new ExamAnswerModel();
  41. }
  42. /**
  43. * 静态入口
  44. */
  45. public static function make()
  46. {
  47. if (!self::$instance) {
  48. self::$instance = new static();
  49. }
  50. return self::$instance;
  51. }
  52. /**
  53. * @param $params
  54. * @param int $pageSize
  55. * @return array
  56. */
  57. public function getDataList($params, $pageSize = 15)
  58. {
  59. $page = isset($params['page']) ? $params['page'] : 1;
  60. $cacheKey = "caches:exams:list_{$page}_{$pageSize}:" . md5(json_encode($params));
  61. $datas = RedisService::get($cacheKey);
  62. if ($datas) {
  63. return $datas;
  64. }
  65. $query = $this->getQuery($params);
  66. $list = $query->select(['a.id', 'a.user_ids', 'a.paper_id', 'a.score', 'a.accurate_count', 'b.name', 'b.type', 'b.topic_count', 'b.score_total', 'b.is_charge', 'a.create_time', 'a.answer_times', 'a.status'])
  67. ->orderBy('a.create_time', 'desc')
  68. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  69. $list = $list ? $list->toArray() : [];
  70. if ($list) {
  71. foreach ($list['data'] as &$item) {
  72. $item['create_time'] = $item['create_time'] ? datetime($item['create_time'], 'Y-m-d H.i.s') : '';
  73. }
  74. }
  75. $rows = isset($list['data']) ? $list['data'] : [];
  76. $datas = [
  77. 'pageSize' => $pageSize,
  78. 'total' => isset($list['total']) ? $list['total'] : 0,
  79. 'list' => $rows
  80. ];
  81. if ($rows) {
  82. RedisService::set($cacheKey, $datas, rand(30, 60));
  83. }
  84. return $datas;
  85. }
  86. /**
  87. * 查询
  88. * @param $params
  89. * @return mixed
  90. */
  91. public function getQuery($params)
  92. {
  93. $where = ['b.status' => 1, 'b.mark' => 1, 'a.mark' => 1];
  94. $status = isset($params['status']) ? $params['status'] : 0;
  95. $type = isset($params['type']) ? $params['type'] : 0;
  96. $sceneType = isset($params['scene_type']) ? $params['scene_type'] : 0;
  97. $userId = isset($params['user_id']) ? $params['user_id'] : 0;
  98. $subjectId = isset($params['subject_id']) ? $params['subject_id'] : 0;
  99. if ($userId > 0) {
  100. $where['a.user_id'] = $userId;
  101. }
  102. if ($status > 0) {
  103. $where['a.status'] = $status;
  104. }
  105. if ($type > 0) {
  106. $where['b.type'] = $type;
  107. }
  108. if ($sceneType > 0) {
  109. $where['b.scene_type'] = $sceneType;
  110. }
  111. if ($subjectId > 0) {
  112. $where['b.subject_id'] = $subjectId;
  113. }
  114. return $this->model->from('exam_answers as a')
  115. ->leftJoin('exam_papers as b', 'b.id', '=', 'a.paper_id')
  116. ->where($where)
  117. ->where(function ($query) use ($params) {
  118. $keyword = isset($params['keyword']) ? $params['keyword'] : '';
  119. if ($keyword) {
  120. $query->where('b.name', 'like', "%{$keyword}%");
  121. }
  122. });
  123. }
  124. /**
  125. * 答题历史
  126. * @param $params
  127. * @param int $pageSize
  128. * @return array|mixed
  129. */
  130. public function getHistoryList($params, $pageSize = 10)
  131. {
  132. $page = isset($params['page']) ? $params['page'] : 1;
  133. $userId = isset($params['user_id']) ? $params['user_id'] : 0;
  134. $cacheKey = "caches:exams:{$userId}_history_{$page}:" . md5(json_encode($params));
  135. $datas = RedisService::get($cacheKey);
  136. if ($datas) {
  137. return $datas;
  138. }
  139. $query = $this->getQuery($params);
  140. $list = $query->select(['a.id', 'a.user_id', 'a.paper_id', 'a.score', 'a.accurate_count', 'b.name', 'b.type', 'b.scene_type', 'b.topic_count', 'b.score_total', 'b.is_charge', 'a.create_time', 'a.answer_times', 'a.status'])
  141. ->orderBy('a.create_time', 'desc')
  142. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  143. $list = $list ? $list->toArray() : [];
  144. if ($list) {
  145. foreach ($list['data'] as &$item) {
  146. $item['create_time'] = $item['create_time'] ? datetime($item['create_time'], 'Y-m-d H.i.s') : '';
  147. }
  148. }
  149. $rows = isset($list['data']) ? $list['data'] : [];
  150. $datas = [
  151. 'pageSize' => $pageSize,
  152. 'total' => isset($list['total']) ? $list['total'] : 0,
  153. 'list' => $rows
  154. ];
  155. if ($rows) {
  156. RedisService::set($cacheKey, $datas, rand(10, 20));
  157. }
  158. return $datas;
  159. }
  160. /**
  161. * 每日一练目录数据
  162. * @param $userId 用户ID
  163. * @param $params
  164. * @param $pageSize
  165. * @return array|mixed
  166. */
  167. public function getPracticeList($userId, $params, $pageSize = 10)
  168. {
  169. $page = isset($params['page']) ? $params['page'] : 1;
  170. $type = isset($params['type']) ? $params['type'] : 1;
  171. $cacheKey = "caches:exams:{$userId}_practice:{$page}_" . md5(json_encode($params));
  172. $datas = RedisService::get($cacheKey);
  173. // 每日一练访问次数统计
  174. if (empty($sc)) {
  175. ExamAccessLogModel::saveLog(date('Y-m-d'), $type, 1);
  176. }
  177. if ($datas) {
  178. return $datas;
  179. }
  180. $list = $this->model->from('exam_answers as a')
  181. ->leftJoin('exam_papers as b', 'b.id', '=', 'a.paper_id')
  182. ->where('b.topic_count', '>', 0)
  183. ->where(['b.scene_type' => 1, 'b.status' => 1, 'a.status' => 1, 'b.mark' => 1, 'a.mark' => 1])
  184. ->where(function ($query) use ($params) {
  185. $type = isset($params['type']) && $params['type'] ? intval($params['type']) : 1;
  186. if ($type > 0) {
  187. $query->where('b.type', $type);
  188. }
  189. })
  190. ->select(['a.*', 'b.name', 'b.scene_type', 'b.type', 'b.score_total', 'b.topic_count'])
  191. ->orderBy('a.create_time', 'desc')
  192. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  193. $list = $list ? $list->toArray() : [];
  194. if ($list) {
  195. foreach ($list['data'] as &$item) {
  196. $item['date'] = $item['create_time'] ? datetime($item['create_time'], 'Y-m-d') : '';
  197. }
  198. }
  199. // 今日是否练习过
  200. $rows = isset($list['data']) ? $list['data'] : [];
  201. $first = isset($rows[0]) ? $rows[0] : [];
  202. $firstTime = isset($first['date']) ? $first['date'] : 0;
  203. if ($page == 1 && strtotime($firstTime) < strtotime(date('Y-m-d'))) {
  204. $type = isset($params['type']) && $params['type'] ? intval($params['type']) : 1;
  205. $data = PaperService::make()->getRandomPaper($userId, $type, 1);
  206. if ($data) {
  207. $rows = array_merge([$data], $rows);
  208. }
  209. }
  210. $datas = [
  211. 'pageSize' => $pageSize,
  212. 'total' => isset($list['total']) ? $list['total'] : 0,
  213. 'list' => $rows
  214. ];
  215. if ($rows) {
  216. RedisService::set($cacheKey, $datas, rand(10, 20));
  217. }
  218. return $datas;
  219. }
  220. /**
  221. * 答题排行榜
  222. * @param $type 1-日,2-周(7天),3-月
  223. * @param int $num
  224. * @return array|mixed
  225. */
  226. public function getRankByType($type, $num = 0)
  227. {
  228. $num = $num ? $num : ConfigService::make()->getConfigByCode('rank_num', 50);
  229. $cacheKey = "caches:exams:ranks:{$type}_{$num}";
  230. $datas = RedisService::get($cacheKey);
  231. if ($datas) {
  232. return $datas;
  233. }
  234. $prefix = env('DB_PREFIX', 'lev_');
  235. $datas = MemberAnswerRankModel::from('member_answer_ranks as a')
  236. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  237. ->where(['a.status' => 1, 'a.mark' => 1])
  238. ->where(function ($query) use ($type) {
  239. if ($type == 1) {
  240. // 日
  241. $query->where('a.date', date('Y-m-d'));
  242. } else if ($type == 2) {
  243. // 周
  244. $query->where('a.date', '>=', date('Y-m-d', time() - 7 * 86400));
  245. } else if ($type == 3) {
  246. // 月
  247. $query->where('a.date', '>=', date('Y-m-01'));
  248. }
  249. })
  250. ->select(['a.id', 'a.user_id', 'b.avatar', 'b.nickname', 'a.answer_time', 'a.answer_count', DB::raw("sum({$prefix}a.answer_time) as answer_times"), DB::raw("sum({$prefix}a.answer_count) as count")])
  251. ->groupBy('a.user_id')
  252. ->orderByRaw("sum({$prefix}a.answer_time) desc")
  253. ->take($num)
  254. ->get();
  255. $datas = $datas ? $datas->toArray() : [];
  256. if ($datas) {
  257. foreach ($datas as &$item) {
  258. $item['avatar'] = $item['avatar'] ? get_image_url($item['avatar']) : '';
  259. $item['answer_hour'] = $item['answer_times'] > 3600 ? intval($item['answer_times'] / 3600) . 'h' : ($item['answer_times'] > 60 ? intval($item['answer_times'] / 60) . 'm' : $item['answer_times'] . 's');
  260. }
  261. RedisService::set($cacheKey, $datas, rand(20, 30));
  262. }
  263. return $datas;
  264. }
  265. /**
  266. * 获取答题卡列表题目数据
  267. * @param $userId 用户
  268. * @param $paperId
  269. * @param int $rid
  270. * @return array|mixed
  271. */
  272. public function getCardList($userId, $paperId, $rid = 0)
  273. {
  274. $cacheKey = "caches:exams:{$userId}_cardList:{$paperId}_{$rid}";
  275. $datas = RedisService::get($cacheKey);
  276. if ($datas) {
  277. return $datas;
  278. }
  279. $datas = ExamTopicModel::from('exam_topics as a')
  280. ->leftJoin('exam_answers_topics as b', function ($join) use ($userId, $rid) {
  281. $join->on('b.topic_id', '=', 'a.id')->where(['b.user_id' => $userId, 'b.answer_log_id' => $rid, 'b.status' => 1, 'b.mark' => 1]);
  282. })
  283. ->where(['a.paper_id' => $paperId, 'a.status' => 1, 'a.mark' => 1])
  284. ->select(['a.id', 'a.topic_name', 'a.correct_answer', 'b.answer', 'a.score', 'a.paper_id', 'a.topic_type', 'b.answer_log_id as rid', 'b.answer as submit_answer', 'b.accurate', 'b.score as submit_score'])
  285. ->orderBy('a.sort', 'desc')
  286. ->orderBy('a.id', 'asc')
  287. ->get();
  288. $datas = $datas ? $datas->toArray() : [];
  289. $list = [];
  290. if ($datas) {
  291. foreach ($datas as &$item) {
  292. $item['rid'] = !empty($item['rid']) && $item['rid'] ? $item['rid'] : $rid;
  293. $item['submit_answer'] = isset($item['submit_answer']) ? $item['submit_answer'] : '';
  294. $item['accurate'] = isset($item['accurate']) ? $item['accurate'] : -1;
  295. $item['submit_score'] = isset($item['submit_score']) ? $item['submit_score'] : 0;
  296. if ($item['topic_type']) {
  297. $list[$item['topic_type']][] = $item;
  298. }
  299. }
  300. RedisService::set($cacheKey, $list, rand(5, 10));
  301. }
  302. return $list;
  303. }
  304. /**
  305. * 重新答题,清除答题记录数据
  306. * @param $id
  307. * @return bool
  308. */
  309. public function reset($id, $userId = 0)
  310. {
  311. $log = $this->model->where(['id' => $id, 'mark' => 1])->first();
  312. if (empty($log)) {
  313. return true;
  314. }
  315. $updateData = ['score' => 0, 'accurate_count' => 0, 'answer_count' => 0, 'answer_times' => 0, 'answer_last_id' => 0, 'is_submit' => 0, 'status' => 1];
  316. $this->model->where(['id' => $id, 'mark' => 1])->update($updateData);
  317. ExamAnswerTopicModel::where(['answer_log_id' => $id, 'mark' => 1])->update(['status' => 2, 'update_time' => time()]);
  318. RedisService::keyDel("caches:exams:{$userId}*");
  319. return true;
  320. }
  321. /**
  322. * 答题
  323. * @param $userId
  324. * @param $params
  325. * @return array|false
  326. */
  327. public function answer($userId, $params)
  328. {
  329. $paperId = isset($params['id']) ? $params['id'] : 0;
  330. $rid = isset($params['rid']) ? $params['rid'] : 0;
  331. $tid = isset($params['tid']) ? $params['tid'] : 0;
  332. $isSubmit = isset($params['is_submit']) ? $params['is_submit'] : 1;
  333. $answer = isset($params['answer']) && $params['answer']? str_replace("\n",'\n', $params['answer']) : '';
  334. $answerImage = isset($params['answer_image']) ? $params['answer_image'] : '';
  335. $answerType = isset($params['answer_type']) && $params['answer_type'] ? $params['answer_type'] : 2;
  336. $remainTime = isset($params['remain_time']) && $params['remain_time'] ? $params['remain_time'] : 0;
  337. if ($isSubmit <= 0 && $answerType == 2 && empty($answer)) {
  338. $this->error = '请先提交答案';
  339. return false;
  340. }
  341. if ($isSubmit <= 0 && $answerType == 1 && empty($answerImage)) {
  342. $this->error = '请先上传图片答案';
  343. return false;
  344. }
  345. $cacheKey = "caches:answers:{$userId}_{$paperId}:{$tid}_{$rid}";
  346. if (RedisService::get($cacheKey . '_lock')) {
  347. $this->error = '请不要频繁提交';
  348. return false;
  349. }
  350. RedisService::set($cacheKey . '_lock', $params, rand(2, 3));
  351. // 试卷数据
  352. $paperInfo = ExamPaperModel::where(['id' => $paperId, 'status' => 1, 'mark' => 1])
  353. ->first();
  354. $sceneType = isset($paperInfo['scene_type']) && $paperInfo['scene_type'] ? $paperInfo['scene_type'] : 1;
  355. if (empty($paperInfo)) {
  356. RedisService::clear($cacheKey . '_lock');
  357. $this->error = '试题数据错误,请返回刷新重试';
  358. return false;
  359. }
  360. // 题目数据
  361. $topicInfo = ExamTopicModel::where(['id' => $tid, 'paper_id' => $paperId, 'status' => 1, 'mark' => 1])->first();
  362. $topicType = isset($topicInfo['topic_type']) ? trim($topicInfo['topic_type']) : '';
  363. $topicScore = isset($topicInfo['score']) ? intval($topicInfo['score']) : 0;
  364. $topicName = isset($topicInfo['topic_name']) && $topicInfo['topic_name']? str_replace("\n",'\n', $topicInfo['topic_name']) : '';
  365. $topicShowType = isset($topicInfo['show_type']) ? $topicInfo['show_type'] : 1;
  366. $correctAnswer = isset($topicInfo['correct_answer']) ? $topicInfo['correct_answer'] : '';
  367. if (empty($topicInfo) || empty($topicType) || empty($topicName)) {
  368. RedisService::clear($cacheKey . '_lock');
  369. $this->error = '题库已更新,请返回刷新重试';
  370. return false;
  371. }
  372. // 答题记录
  373. $submit = 0;
  374. $answerTimes = 0;
  375. $answerCount = 0;
  376. if ($rid) {
  377. $answerInfo = ExamAnswerModel::where(['id' => $rid, 'user_id' => $userId, 'status' => 1, 'mark' => 1])->first();
  378. $submit = isset($answerInfo['is_submit']) ? $answerInfo['is_submit'] : 0;
  379. $answerCount = isset($answerInfo['answer_count']) ? $answerInfo['answer_count'] : 0;
  380. $answerTimes = isset($answerInfo['answer_times']) ? $answerInfo['answer_times'] : 0;
  381. if (empty($answerInfo)) {
  382. $rid = 0;
  383. }
  384. if ($submit) {
  385. RedisService::clear($cacheKey . '_lock');
  386. $this->error = '您已交卷';
  387. return false;
  388. }
  389. }
  390. // 验证答案内容类型和数据
  391. // 每日一练
  392. if ($sceneType == 1 && $rid <= 0) {
  393. // 今日记录
  394. $answerInfo = ExamAnswerModel::where(['paper_id' => $paperId, 'status' => 1, 'mark' => 1])->where('create_time', '>=', strtotime(date('Y-m-d')))->first();
  395. $rid = isset($answerInfo['id']) ? $answerInfo['id'] : 0;
  396. $submit = isset($answerInfo['is_submit']) ? $answerInfo['is_submit'] : 0;
  397. $answerCount = isset($answerInfo['answer_count']) ? $answerInfo['answer_count'] : 0;
  398. }
  399. // 是否已交卷
  400. if ($submit == 1) {
  401. RedisService::clear($cacheKey . '_lock');
  402. $this->error = '您已交卷';
  403. return false;
  404. }
  405. // 直接交卷
  406. $totalTime = ConfigService::make()->getConfigByCode('answer_total_time', 1800);
  407. $answerTime = $totalTime > $remainTime ? $totalTime - $remainTime : $totalTime;
  408. $newAnswerTime = $answerTime > $answerTimes ? $answerTime - $answerTimes : 0;
  409. if ($isSubmit == 1 && empty($answer) && empty($answerImage)) {
  410. // 是否提交过
  411. if ($answerCount <= 0) {
  412. RedisService::clear($cacheKey . '_lock');
  413. $this->error = '您未提交过答案,请先答题再交卷';
  414. return false;
  415. }
  416. $this->model->where(['id' => $rid])->update(['is_submit' => 1, 'update_time' => time()]);
  417. $this->error = '交卷成功';
  418. RedisService::keyDel("caches:exams:{$userId}*");
  419. RedisService::clear($cacheKey . '_lock');
  420. return ['rid' => $rid, 'paper_id' => $paperId];
  421. }
  422. // 该题是否已提交答案
  423. $logId = 0;
  424. if ($rid > 0) {
  425. $answerTopic = ExamAnswerTopicModel::where(['answer_log_id' => $rid, 'user_id' => $userId, 'topic_id' => $tid, 'mark' => 1])->first();
  426. $accurate = isset($answerTopic['accurate']) ? $answerTopic['accurate'] : -1;
  427. $logId = isset($answerTopic['id']) ? $answerTopic['id'] : 0;
  428. $status = isset($answerTopic['status']) ? $answerTopic['status'] : 0;
  429. if ($answerTopic && $accurate >= 0 && $status == 1) {
  430. RedisService::clear($cacheKey . '_lock');
  431. $this->error = '该题答案已提交';
  432. return false;
  433. }
  434. }
  435. /* TODO 验证答案 */
  436. $submitType = 1;
  437. $topicData = [
  438. 'user_id' => $userId,
  439. 'topic_id' => $tid,
  440. 'answer' => $answerType == 1 ? get_image_path($answer) : $answer,
  441. 'score' => 0,
  442. 'accurate' => 0,
  443. 'create_time' => time(),
  444. 'status' => 1,
  445. 'mark' => 1,
  446. ];
  447. if (in_array($topicType, ['选择题', '单选题', '多选题', '填空题'])) {
  448. $topicData['answer_analysis'] = isset($topicInfo['answer_analysis']) ? $topicInfo['answer_analysis'] : '';
  449. if ($answer == $correctAnswer) {
  450. $topicData['accurate'] = 1;
  451. $topicData['score'] = $topicScore;
  452. } else {
  453. $topicData['accurate'] = 0;
  454. }
  455. // }else if (in_array($topicType, ['简答题','计算题','阅读理解'])){
  456. } else {
  457. // 图片答案AI验证
  458. if ($answerType == 1) {
  459. if (empty($answerImage)) {
  460. $this->error = '请上传图片答案~';
  461. return false;
  462. }
  463. $submitType = 3;
  464. $apiData = [
  465. 'answer' => DeepSeekService::make()->getImageTopicData($answerImage),
  466. 'score' => $topicScore,
  467. 'topic' => $topicShowType == 2 && $topicName ? DeepSeekService::make()->getImageTopicData($topicName) : $topicName,
  468. ];
  469. $result = DeepSeekService::make()->apiRequest($apiData);
  470. RedisService::clear($cacheKey . '_lock');
  471. $this->error = '功能开放中~';
  472. return false;
  473. } else {
  474. $submitType = 2;
  475. $apiData = [
  476. 'answer' => $answer,
  477. 'score' => $topicScore,
  478. 'topic' => $topicShowType == 2 && $topicName ? DeepSeekService::make()->getImageTopicData($topicName) : $topicName,
  479. ];
  480. $result = DeepSeekService::make()->apiRequest($apiData);
  481. $score = isset($result['score']) ? $result['score'] : 0;
  482. $analysis = isset($result['analysis']) ? $result['analysis'] : '';
  483. if ($score > 0) {
  484. $topicData['accurate'] = 1;
  485. $topicData['score'] = $score;
  486. $topicData['answer_analysis'] = $analysis;
  487. } else {
  488. $topicData['accurate'] = 0;
  489. }
  490. }
  491. }
  492. DB::beginTransaction();
  493. if ($rid) {
  494. $log = [
  495. 'answer_times' => $answerTime,
  496. 'answer_last_at' => date('Y-m-d H:i:s'),
  497. 'answer_count' => DB::raw("answer_count + 1"),
  498. 'answer_last_id' => $tid,
  499. 'is_submit' => $isSubmit == 1 ? 1 : 0,
  500. 'update_time' => time()
  501. ];
  502. // 对题数
  503. if ($topicData['accurate'] == 1) {
  504. $log['accurate_count'] = DB::raw("accurate_count + 1");
  505. $log['score'] = DB::raw("score + {$topicData['score']}");
  506. }
  507. if (!$this->model->where(['id' => $rid])->update($log)) {
  508. DB::rollBack();
  509. RedisService::clear($cacheKey . '_lock');
  510. $this->error = '答题失败,请刷新后重新提交';
  511. return false;
  512. }
  513. } else {
  514. $log = [
  515. 'user_id' => $userId,
  516. 'paper_id' => $paperId,
  517. 'score' => $topicData['score'],
  518. 'answer_count' => 1,
  519. 'answer_times' => $answerTime,
  520. 'answer_last_at' => date('Y-m-d H:i:s'),
  521. 'answer_last_id' => $tid,
  522. 'is_submit' => $isSubmit,
  523. 'create_time' => time()
  524. ];
  525. if (!$rid = $this->model->insertGetId($log)) {
  526. DB::rollBack();
  527. RedisService::clear($cacheKey . '_lock');
  528. $this->error = '答题失败,请刷新后重新提交';
  529. return false;
  530. }
  531. }
  532. // 答题题目数据
  533. $topicData['answer_type'] = $submitType;
  534. $topicData['answer_log_id'] = $rid;
  535. if ($logId) {
  536. $topicData['update_time'] = $submitType;
  537. ExamAnswerTopicModel::where(['id' => $logId])->update($topicData);
  538. } else if (!ExamAnswerTopicModel::insert($topicData)) {
  539. DB::rollBack();
  540. RedisService::clear($cacheKey . '_lock');
  541. $this->error = '答题失败,请刷新后重新提交';
  542. return false;
  543. }
  544. DB::commit();
  545. // 答题时间统计
  546. if ($newAnswerTime > 0) {
  547. $id = MemberAnswerRankModel::where(['user_id' => $userId, 'date' => date('Y-m-d'), 'mark' => 1])->value('id');
  548. if ($id) {
  549. MemberAnswerRankModel::where(['id' => $id])->update(['answer_time' => DB::raw("answer_time + {$newAnswerTime}"), 'answer_count' => DB::raw("answer_count + 1"), 'update_time' => time()]);
  550. } else {
  551. MemberAnswerRankModel::insert(['user_id' => $userId, 'answer_time' => $answerTime, 'answer_count' => 1, 'date' => date('Y-m-d'), 'create_time' => time()]);
  552. }
  553. }
  554. $this->error = '答题成功';
  555. RedisService::clear($cacheKey . '_lock');
  556. RedisService::clear("caches:exams:info_{$rid}");
  557. RedisService::keyDel("caches:exams:ranks*");
  558. RedisService::keyDel("caches:exams:{$userId}*");
  559. RedisService::keyDel("caches:paper:list*");
  560. RedisService::keyDel("caches:paper:info_{$userId}:p{$paperId}*");
  561. return ['paper_id' => $paperId, 'rid' => $rid, 'tid' => $tid, 'accurate' => $topicData['accurate'], 'score' => $topicData['score']];
  562. }
  563. /**
  564. * 是否有答题记录数据
  565. * @param $rid
  566. * @param $tid
  567. * @return array|mixed
  568. */
  569. public function getAnswerCacheTopic($rid, $tid)
  570. {
  571. $cacheKey = "caches:answers:topic_{$rid}_{$tid}";
  572. $data = RedisService::get($cacheKey);
  573. if ($data) {
  574. return $data;
  575. }
  576. $data = ExamAnswerTopicModel::where(['rid' => $rid, 'topic_id' => $tid, 'mark' => 1])->value('id');
  577. if ($data) {
  578. RedisService::set($cacheKey, $data, rand(5, 10));
  579. }
  580. return $data;
  581. }
  582. /**
  583. * 答题分数结果详情
  584. * @param $rid
  585. * @return array|mixed
  586. */
  587. public function getInfo($rid)
  588. {
  589. $cacheKey = "caches:exams:info_{$rid}";
  590. $data = RedisService::get($cacheKey);
  591. if ($data) {
  592. return $data;
  593. }
  594. $data = $this->model->from('exam_answers as a')
  595. ->leftJoin('exam_papers as b', 'b.id', '=', 'a.paper_id')
  596. ->where(['a.id' => $rid, 'a.status' => 1, 'a.mark' => 1])
  597. ->select(['a.*', 'b.topic_count', 'b.scene_type'])
  598. ->first();
  599. $data = $data ? $data->toArray() : [];
  600. if ($data) {
  601. $data['accurate_rate'] = round($data['accurate_count'] / $data['topic_count'] * 100, 2);
  602. $data['answer_times_text'] = $data['answer_times'] ? format_times($data['answer_times']) : '00:00';
  603. RedisService::set($cacheKey, $data, rand(5, 10));
  604. }
  605. return $data;
  606. }
  607. }