ExamService.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  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 $params
  163. * @param int $pageSize
  164. * @return array|mixed
  165. */
  166. public function getErrorList($params, $pageSize = 10)
  167. {
  168. $page = isset($params['page']) ? $params['page'] : 1;
  169. $userId = isset($params['user_id']) ? $params['user_id'] : 0;
  170. $cacheKey = "caches:exams:{$userId}_errors_{$page}:" . md5(json_encode($params));
  171. $datas = RedisService::get($cacheKey);
  172. if ($datas) {
  173. return $datas;
  174. }
  175. $prefix = env('DB_PREFIX','lev_');
  176. $query = $this->getQuery($params);
  177. $list = $query->with(['error'])->whereRaw("{$prefix}a.accurate_count < {$prefix}a.answer_count")->where('b.id','>',0)
  178. ->select(['a.id', 'a.user_id', 'a.paper_id', 'a.score', 'a.accurate_count', 'a.answer_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'])
  179. ->orderBy('a.create_time', 'desc')
  180. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  181. $list = $list ? $list->toArray() : [];
  182. if ($list) {
  183. foreach ($list['data'] as &$item) {
  184. $item['error_count'] = $item['answer_count'] - $item['accurate_count'];
  185. $item['create_time'] = $item['create_time'] ? datetime($item['create_time'], 'Y-m-d H.i.s') : '';
  186. $item['error_id'] = isset($item['error']) && isset($item['error']['topic_id'])? $item['error']['topic_id'] : 0;
  187. }
  188. }
  189. $rows = isset($list['data']) ? $list['data'] : [];
  190. $datas = [
  191. 'pageSize' => $pageSize,
  192. 'total' => isset($list['total']) ? $list['total'] : 0,
  193. 'list' => $rows
  194. ];
  195. if ($rows) {
  196. RedisService::set($cacheKey, $datas, rand(10, 20));
  197. }
  198. return $datas;
  199. }
  200. /**
  201. * 每日一练目录数据
  202. * @param $userId 用户ID
  203. * @param $params
  204. * @param $pageSize
  205. * @return array|mixed
  206. */
  207. public function getPracticeList($userId, $params, $pageSize = 10)
  208. {
  209. $page = isset($params['page']) ? $params['page'] : 1;
  210. $type = isset($params['type']) ? $params['type'] : 1;
  211. $sc = isset($params['sc']) ? $params['sc'] : 0;
  212. $cacheKey = "caches:exam:{$userId}_practice:{$page}_" . md5(json_encode($params));
  213. $datas = RedisService::get($cacheKey);
  214. // 每日一练访问次数统计
  215. if (empty($sc)) {
  216. ExamAccessLogModel::saveLog(date('Y-m-d'), $type, 1);
  217. }
  218. if ($datas) {
  219. return $datas;
  220. }
  221. $list = $this->model->from('exam_answers as a')
  222. ->leftJoin('exam_papers as b', 'b.id', '=', 'a.paper_id')
  223. ->where('b.topic_count', '>', 0)
  224. ->where(['b.scene_type' => 1, 'b.status' => 1, 'a.status' => 1, 'b.mark' => 1, 'a.mark' => 1])
  225. ->where(function ($query) use ($params) {
  226. $type = isset($params['type']) && $params['type'] ? intval($params['type']) : 1;
  227. if ($type > 0) {
  228. $query->where('b.type', $type);
  229. }
  230. })
  231. ->select(['a.*', 'b.name', 'b.scene_type', 'b.type', 'b.score_total', 'b.topic_count'])
  232. ->orderBy('a.create_time', 'desc')
  233. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  234. $list = $list ? $list->toArray() : [];
  235. if ($list) {
  236. foreach ($list['data'] as &$item) {
  237. $item['date'] = $item['create_time'] ? datetime($item['create_time'], 'Y-m-d') : '';
  238. }
  239. }
  240. // 今日是否练习过
  241. $rows = isset($list['data']) ? $list['data'] : [];
  242. $first = isset($rows[0]) ? $rows[0] : [];
  243. $firstTime = isset($first['date']) ? $first['date'] : 0;
  244. if ($page == 1 && strtotime($firstTime) < strtotime(date('Y-m-d'))) {
  245. $type = isset($params['type']) && $params['type'] ? intval($params['type']) : 1;
  246. $data = PaperService::make()->getRandomPaper($userId, $type, 1);
  247. if ($data) {
  248. $rows = array_merge([$data], $rows);
  249. }
  250. }
  251. $datas = [
  252. 'pageSize' => $pageSize,
  253. 'total' => isset($list['total']) ? $list['total'] : 0,
  254. 'list' => $rows
  255. ];
  256. if ($rows) {
  257. RedisService::set($cacheKey, $datas, rand(10, 20));
  258. }
  259. return $datas;
  260. }
  261. /**
  262. * 答题排行榜
  263. * @param $type 1-日,2-周(7天),3-月
  264. * @param int $num
  265. * @return array|mixed
  266. */
  267. public function getRankByType($type, $num = 0)
  268. {
  269. $num = $num ? $num : ConfigService::make()->getConfigByCode('rank_num', 50);
  270. $cacheKey = "caches:exams:ranks:{$type}_{$num}";
  271. $datas = RedisService::get($cacheKey);
  272. if ($datas) {
  273. return $datas;
  274. }
  275. $prefix = env('DB_PREFIX', 'lev_');
  276. $datas = MemberAnswerRankModel::from('member_answer_ranks as a')
  277. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  278. ->where(['a.status' => 1, 'a.mark' => 1])
  279. ->where(function ($query) use ($type) {
  280. if ($type == 1) {
  281. // 日
  282. $query->where('a.date', date('Y-m-d'));
  283. } else if ($type == 2) {
  284. // 周
  285. $query->where('a.date', '>=', date('Y-m-d', time() - 7 * 86400));
  286. } else if ($type == 3) {
  287. // 月
  288. $query->where('a.date', '>=', date('Y-m-01'));
  289. }
  290. })
  291. ->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")])
  292. ->groupBy('a.user_id')
  293. ->orderByRaw("sum({$prefix}a.answer_time) desc")
  294. ->take($num)
  295. ->get();
  296. $datas = $datas ? $datas->toArray() : [];
  297. if ($datas) {
  298. foreach ($datas as &$item) {
  299. $item['avatar'] = $item['avatar'] ? get_image_url($item['avatar']) : '';
  300. $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');
  301. }
  302. RedisService::set($cacheKey, $datas, rand(20, 30));
  303. }
  304. return $datas;
  305. }
  306. /**
  307. * 获取答题卡列表题目数据
  308. * @param $userId 用户
  309. * @param $paperId
  310. * @param int $rid
  311. * @return array|mixed
  312. */
  313. public function getCardList($userId, $paperId, $rid = 0)
  314. {
  315. $cacheKey = "caches:exams:{$userId}_cardList:{$paperId}_{$rid}";
  316. $datas = RedisService::get($cacheKey);
  317. if ($datas) {
  318. return $datas;
  319. }
  320. $datas = ExamTopicModel::from('exam_topics as a')
  321. ->leftJoin('exam_answers_topics as b', function ($join) use ($userId, $rid) {
  322. $join->on('b.topic_id', '=', 'a.id')->where(['b.user_id' => $userId, 'b.answer_log_id' => $rid, 'b.status' => 1, 'b.mark' => 1]);
  323. })
  324. ->where(['a.paper_id' => $paperId, 'a.status' => 1, 'a.mark' => 1])
  325. ->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'])
  326. ->orderBy('a.sort', 'desc')
  327. ->orderBy('a.id', 'asc')
  328. ->get();
  329. $datas = $datas ? $datas->toArray() : [];
  330. $list = [];
  331. if ($datas) {
  332. foreach ($datas as &$item) {
  333. $item['rid'] = !empty($item['rid']) && $item['rid'] ? $item['rid'] : $rid;
  334. $item['submit_answer'] = isset($item['submit_answer']) ? $item['submit_answer'] : '';
  335. $item['accurate'] = isset($item['accurate']) ? $item['accurate'] : -1;
  336. $item['submit_score'] = isset($item['submit_score']) ? $item['submit_score'] : 0;
  337. if ($item['topic_type']) {
  338. $list[$item['topic_type']][] = $item;
  339. }
  340. }
  341. RedisService::set($cacheKey, $list, rand(5, 10));
  342. }
  343. return $list;
  344. }
  345. /**
  346. * 重新答题,清除答题记录数据
  347. * @param $id
  348. * @return bool
  349. */
  350. public function reset($id, $userId = 0)
  351. {
  352. $log = $this->model->where(['id' => $id, 'mark' => 1])->first();
  353. if (empty($log)) {
  354. return true;
  355. }
  356. $updateData = ['score' => 0, 'accurate_count' => 0, 'answer_count' => 0, 'answer_times' => 0, 'answer_last_id' => 0, 'is_submit' => 0, 'status' => 1];
  357. $this->model->where(['id' => $id, 'mark' => 1])->update($updateData);
  358. ExamAnswerTopicModel::where(['answer_log_id' => $id, 'mark' => 1])->update(['status' => 2, 'update_time' => time()]);
  359. RedisService::keyDel("caches:exams:{$userId}*");
  360. return true;
  361. }
  362. /**
  363. * 答题
  364. * @param $userId
  365. * @param $params
  366. * @return array|false
  367. */
  368. public function answer($userId, $params)
  369. {
  370. $paperId = isset($params['id']) ? $params['id'] : 0;
  371. $rid = isset($params['rid']) ? $params['rid'] : 0;
  372. $tid = isset($params['tid']) ? $params['tid'] : 0;
  373. $isSubmit = isset($params['is_submit']) ? $params['is_submit'] : 1;
  374. $answer = isset($params['answer']) && $params['answer']? str_replace("\n",'\n', $params['answer']) : '';
  375. $answerImage = isset($params['answer_image']) ? $params['answer_image'] : '';
  376. $answerType = isset($params['answer_type']) && $params['answer_type'] ? $params['answer_type'] : 2;
  377. $remainTime = isset($params['remain_time']) && $params['remain_time'] ? $params['remain_time'] : 0;
  378. if ($isSubmit <= 0 && $answerType == 2 && empty($answer)) {
  379. $this->error = '请先提交答案';
  380. return false;
  381. }
  382. if ($isSubmit <= 0 && $answerType == 1 && empty($answerImage)) {
  383. $this->error = '请先上传图片答案';
  384. return false;
  385. }
  386. $cacheKey = "caches:answers:{$userId}_{$paperId}:{$tid}_{$rid}";
  387. if (RedisService::get($cacheKey . '_lock')) {
  388. $this->error = '请不要频繁提交';
  389. return false;
  390. }
  391. RedisService::set($cacheKey . '_lock', $params, rand(2, 3));
  392. // 试卷数据
  393. $paperInfo = ExamPaperModel::where(['id' => $paperId, 'status' => 1, 'mark' => 1])
  394. ->first();
  395. $sceneType = isset($paperInfo['scene_type']) && $paperInfo['scene_type'] ? $paperInfo['scene_type'] : 1;
  396. if (empty($paperInfo)) {
  397. RedisService::clear($cacheKey . '_lock');
  398. $this->error = '试题数据错误,请返回刷新重试';
  399. return false;
  400. }
  401. // 题目数据
  402. $topicInfo = ExamTopicModel::where(['id' => $tid, 'paper_id' => $paperId, 'status' => 1, 'mark' => 1])->first();
  403. $topicType = isset($topicInfo['topic_type']) ? trim($topicInfo['topic_type']) : '';
  404. $topicScore = isset($topicInfo['score']) ? intval($topicInfo['score']) : 0;
  405. $topicName = isset($topicInfo['topic_name']) && $topicInfo['topic_name']? str_replace("\n",'\n', $topicInfo['topic_name']) : '';
  406. $topicShowType = isset($topicInfo['show_type']) ? $topicInfo['show_type'] : 1;
  407. $correctAnswer = isset($topicInfo['correct_answer']) ? $topicInfo['correct_answer'] : '';
  408. if (empty($topicInfo) || empty($topicType) || empty($topicName)) {
  409. RedisService::clear($cacheKey . '_lock');
  410. $this->error = '题库已更新,请返回刷新重试';
  411. return false;
  412. }
  413. // 答题记录
  414. $submit = 0;
  415. $answerTimes = 0;
  416. $answerCount = 0;
  417. if ($rid) {
  418. $answerInfo = ExamAnswerModel::where(['id' => $rid, 'user_id' => $userId, 'status' => 1, 'mark' => 1])->first();
  419. $submit = isset($answerInfo['is_submit']) ? $answerInfo['is_submit'] : 0;
  420. $answerCount = isset($answerInfo['answer_count']) ? $answerInfo['answer_count'] : 0;
  421. $answerTimes = isset($answerInfo['answer_times']) ? $answerInfo['answer_times'] : 0;
  422. if (empty($answerInfo)) {
  423. $rid = 0;
  424. }
  425. if ($submit) {
  426. RedisService::clear($cacheKey . '_lock');
  427. $this->error = '您已交卷';
  428. return false;
  429. }
  430. }
  431. // 验证答案内容类型和数据
  432. // 每日一练
  433. if ($sceneType == 1 && $rid <= 0) {
  434. // 今日记录
  435. $answerInfo = ExamAnswerModel::where(['paper_id' => $paperId, 'status' => 1, 'mark' => 1])->where('create_time', '>=', strtotime(date('Y-m-d')))->first();
  436. $rid = isset($answerInfo['id']) ? $answerInfo['id'] : 0;
  437. $submit = isset($answerInfo['is_submit']) ? $answerInfo['is_submit'] : 0;
  438. $answerCount = isset($answerInfo['answer_count']) ? $answerInfo['answer_count'] : 0;
  439. }
  440. // 是否已交卷
  441. if ($submit == 1) {
  442. RedisService::clear($cacheKey . '_lock');
  443. $this->error = '您已交卷';
  444. return false;
  445. }
  446. // 直接交卷
  447. $totalTime = ConfigService::make()->getConfigByCode('answer_total_time', 1800);
  448. $answerTime = $totalTime > $remainTime ? $totalTime - $remainTime : $totalTime;
  449. $newAnswerTime = $answerTime > $answerTimes ? $answerTime - $answerTimes : 0;
  450. if ($isSubmit == 1 && empty($answer) && empty($answerImage)) {
  451. // 是否提交过
  452. if ($answerCount <= 0) {
  453. RedisService::clear($cacheKey . '_lock');
  454. $this->error = '您未提交过答案,请先答题再交卷';
  455. return false;
  456. }
  457. $this->model->where(['id' => $rid])->update(['is_submit' => 1, 'update_time' => time()]);
  458. $this->error = '交卷成功';
  459. RedisService::keyDel("caches:exams:{$userId}*");
  460. RedisService::clear($cacheKey . '_lock');
  461. return ['rid' => $rid, 'paper_id' => $paperId];
  462. }
  463. // 该题是否已提交答案
  464. $logId = 0;
  465. if ($rid > 0) {
  466. $answerTopic = ExamAnswerTopicModel::where(['answer_log_id' => $rid, 'user_id' => $userId, 'topic_id' => $tid, 'mark' => 1])->first();
  467. $accurate = isset($answerTopic['accurate']) ? $answerTopic['accurate'] : -1;
  468. $logId = isset($answerTopic['id']) ? $answerTopic['id'] : 0;
  469. $status = isset($answerTopic['status']) ? $answerTopic['status'] : 0;
  470. if ($answerTopic && $accurate >= 0 && $status == 1) {
  471. RedisService::clear($cacheKey . '_lock');
  472. $this->error = '该题答案已提交';
  473. return false;
  474. }
  475. }
  476. /* TODO 验证答案 */
  477. $submitType = 1;
  478. $topicData = [
  479. 'user_id' => $userId,
  480. 'topic_id' => $tid,
  481. 'answer' => $answerType == 1 ? get_image_path($answer) : $answer,
  482. 'score' => 0,
  483. 'accurate' => 0,
  484. 'create_time' => time(),
  485. 'status' => 1,
  486. 'mark' => 1,
  487. ];
  488. if (in_array($topicType, ['选择题', '单选题', '多选题', '填空题'])) {
  489. $topicData['answer_analysis'] = isset($topicInfo['answer_analysis']) ? $topicInfo['answer_analysis'] : '';
  490. if ($answer == $correctAnswer) {
  491. $topicData['accurate'] = 1;
  492. $topicData['score'] = $topicScore;
  493. } else {
  494. $topicData['accurate'] = 0;
  495. }
  496. // }else if (in_array($topicType, ['简答题','计算题','阅读理解'])){
  497. } else {
  498. // 图片答案AI验证
  499. if ($answerType == 1) {
  500. if (empty($answerImage)) {
  501. $this->error = '请上传图片答案~';
  502. return false;
  503. }
  504. $submitType = 3;
  505. $apiData = [
  506. 'answer' => DeepSeekService::make()->getImageTopicData($answerImage),
  507. 'score' => $topicScore,
  508. 'topic' => $topicShowType == 2 && $topicName ? DeepSeekService::make()->getImageTopicData($topicName) : $topicName,
  509. ];
  510. $result = DeepSeekService::make()->apiRequest($apiData);
  511. RedisService::clear($cacheKey . '_lock');
  512. $this->error = '功能开放中~';
  513. return false;
  514. } else {
  515. $submitType = 2;
  516. $apiData = [
  517. 'answer' => $answer,
  518. 'score' => $topicScore,
  519. 'topic' => $topicShowType == 2 && $topicName ? DeepSeekService::make()->getImageTopicData($topicName) : $topicName,
  520. ];
  521. $result = DeepSeekService::make()->apiRequest($apiData);
  522. $score = isset($result['score']) ? $result['score'] : 0;
  523. $analysis = isset($result['analysis']) ? $result['analysis'] : '';
  524. if ($score > 0) {
  525. $topicData['accurate'] = 1;
  526. $topicData['score'] = $score;
  527. $topicData['answer_analysis'] = $analysis;
  528. } else {
  529. $topicData['accurate'] = 0;
  530. }
  531. }
  532. }
  533. DB::beginTransaction();
  534. if ($rid) {
  535. $log = [
  536. 'answer_times' => $answerTime,
  537. 'answer_last_at' => date('Y-m-d H:i:s'),
  538. 'answer_count' => DB::raw("answer_count + 1"),
  539. 'answer_last_id' => $tid,
  540. 'is_submit' => $isSubmit == 1 ? 1 : 0,
  541. 'update_time' => time()
  542. ];
  543. // 对题数
  544. if ($topicData['accurate'] == 1) {
  545. $log['accurate_count'] = DB::raw("accurate_count + 1");
  546. $log['score'] = DB::raw("score + {$topicData['score']}");
  547. }
  548. if (!$this->model->where(['id' => $rid])->update($log)) {
  549. DB::rollBack();
  550. RedisService::clear($cacheKey . '_lock');
  551. $this->error = '答题失败,请刷新后重新提交';
  552. return false;
  553. }
  554. } else {
  555. $log = [
  556. 'user_id' => $userId,
  557. 'paper_id' => $paperId,
  558. 'score' => $topicData['score'],
  559. 'answer_count' => 1,
  560. 'answer_times' => $answerTime,
  561. 'answer_last_at' => date('Y-m-d H:i:s'),
  562. 'answer_last_id' => $tid,
  563. 'is_submit' => $isSubmit,
  564. 'create_time' => time()
  565. ];
  566. if (!$rid = $this->model->insertGetId($log)) {
  567. DB::rollBack();
  568. RedisService::clear($cacheKey . '_lock');
  569. $this->error = '答题失败,请刷新后重新提交';
  570. return false;
  571. }
  572. }
  573. // 答题题目数据
  574. $topicData['answer_type'] = $submitType;
  575. $topicData['answer_log_id'] = $rid;
  576. if ($logId) {
  577. $topicData['update_time'] = $submitType;
  578. ExamAnswerTopicModel::where(['id' => $logId])->update($topicData);
  579. } else if (!ExamAnswerTopicModel::insert($topicData)) {
  580. DB::rollBack();
  581. RedisService::clear($cacheKey . '_lock');
  582. $this->error = '答题失败,请刷新后重新提交';
  583. return false;
  584. }
  585. DB::commit();
  586. // 答题时间统计
  587. if ($newAnswerTime > 0) {
  588. $id = MemberAnswerRankModel::where(['user_id' => $userId, 'date' => date('Y-m-d'), 'mark' => 1])->value('id');
  589. if ($id) {
  590. MemberAnswerRankModel::where(['id' => $id])->update(['answer_time' => DB::raw("answer_time + {$newAnswerTime}"), 'answer_count' => DB::raw("answer_count + 1"), 'update_time' => time()]);
  591. } else {
  592. MemberAnswerRankModel::insert(['user_id' => $userId, 'answer_time' => $answerTime, 'answer_count' => 1, 'date' => date('Y-m-d'), 'create_time' => time()]);
  593. }
  594. }
  595. $this->error = '答题成功';
  596. RedisService::clear($cacheKey . '_lock');
  597. RedisService::clear("caches:exams:info_{$rid}");
  598. RedisService::keyDel("caches:exams:ranks*");
  599. RedisService::keyDel("caches:exams:{$userId}*");
  600. RedisService::keyDel("caches:paper:list*");
  601. RedisService::keyDel("caches:paper:info_{$userId}:p{$paperId}*");
  602. return ['paper_id' => $paperId, 'rid' => $rid, 'tid' => $tid, 'accurate' => $topicData['accurate'], 'score' => $topicData['score']];
  603. }
  604. /**
  605. * 是否有答题记录数据
  606. * @param $rid
  607. * @param $tid
  608. * @return array|mixed
  609. */
  610. public function getAnswerCacheTopic($rid, $tid)
  611. {
  612. $cacheKey = "caches:answers:topic_{$rid}_{$tid}";
  613. $data = RedisService::get($cacheKey);
  614. if ($data) {
  615. return $data;
  616. }
  617. $data = ExamAnswerTopicModel::where(['rid' => $rid, 'topic_id' => $tid, 'mark' => 1])->value('id');
  618. if ($data) {
  619. RedisService::set($cacheKey, $data, rand(5, 10));
  620. }
  621. return $data;
  622. }
  623. /**
  624. * 答题分数结果详情
  625. * @param $rid
  626. * @return array|mixed
  627. */
  628. public function getInfo($rid)
  629. {
  630. $cacheKey = "caches:exams:info_{$rid}";
  631. $data = RedisService::get($cacheKey);
  632. if ($data) {
  633. return $data;
  634. }
  635. $data = $this->model->from('exam_answers as a')
  636. ->leftJoin('exam_papers as b', 'b.id', '=', 'a.paper_id')
  637. ->where(['a.id' => $rid, 'a.status' => 1, 'a.mark' => 1])
  638. ->select(['a.*', 'b.topic_count', 'b.scene_type'])
  639. ->first();
  640. $data = $data ? $data->toArray() : [];
  641. if ($data) {
  642. $data['accurate_rate'] = round($data['accurate_count'] / $data['topic_count'] * 100, 2);
  643. $data['answer_times_text'] = $data['answer_times'] ? format_times($data['answer_times']) : '00:00';
  644. RedisService::set($cacheKey, $data, rand(5, 10));
  645. }
  646. return $data;
  647. }
  648. }