ExamService.php 25 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.scene_type' => 1, 'b.status' => 1,'a.status'=>1, 'b.mark' => 1, 'a.mark' => 1])
  183. ->where(function ($query) use ($params) {
  184. $type = isset($params['type']) && $params['type'] ? intval($params['type']) : 1;
  185. if ($type > 0) {
  186. $query->where('b.type', $type);
  187. }
  188. })
  189. ->select(['a.*', 'b.name', 'b.scene_type', 'b.type', 'b.score_total', 'b.topic_count'])
  190. ->orderBy('a.create_time', 'desc')
  191. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  192. $list = $list ? $list->toArray() : [];
  193. if ($list) {
  194. foreach ($list['data'] as &$item) {
  195. $item['date'] = $item['create_time'] ? datetime($item['create_time'], 'Y-m-d') : '';
  196. }
  197. }
  198. // 今日是否练习过
  199. $rows = isset($list['data']) ? $list['data'] : [];
  200. $first = isset($rows[0]) ? $rows[0] : [];
  201. $firstTime = isset($first['date']) ? $first['date'] : 0;
  202. if ($page == 1 && strtotime($firstTime) < strtotime(date('Y-m-d'))) {
  203. $type = isset($params['type']) && $params['type'] ? intval($params['type']) : 1;
  204. $data = PaperService::make()->getRandomPaper($userId, $type, 1);
  205. if($data){
  206. $rows = array_merge([$data], $rows);
  207. }
  208. }
  209. $datas = [
  210. 'pageSize' => $pageSize,
  211. 'total' => isset($list['total']) ? $list['total'] : 0,
  212. 'list' => $rows
  213. ];
  214. if ($rows) {
  215. RedisService::set($cacheKey, $datas, rand(10, 20));
  216. }
  217. return $datas;
  218. }
  219. /**
  220. * 答题排行榜
  221. * @param $type 1-日,2-周(7天),3-月
  222. * @param int $num
  223. * @return array|mixed
  224. */
  225. public function getRankByType($type, $num = 0)
  226. {
  227. $num = $num ? $num : ConfigService::make()->getConfigByCode('rank_num', 10);
  228. $cacheKey = "caches:exams:ranks:{$type}_{$num}";
  229. $datas = RedisService::get($cacheKey);
  230. if ($datas) {
  231. return $datas;
  232. }
  233. $prefix = env('DB_PREFIX', 'lev_');
  234. $datas = MemberAnswerRankModel::from('member_answer_ranks as a')
  235. ->leftJoin('member as b', 'b.id', '=', 'a.user_id')
  236. ->where(['a.status' => 1, 'a.mark' => 1])
  237. ->where(function ($query) use ($type) {
  238. if ($type == 1) {
  239. // 日
  240. $query->where('a.date', date('Y-m-d'));
  241. } else if ($type == 2) {
  242. // 周
  243. $query->where('a.date', '>=', date('Y-m-d', time() - 7 * 86400));
  244. } else if ($type == 3) {
  245. // 月
  246. $query->where('a.date', '>=', date('Y-m-01'));
  247. }
  248. })
  249. ->select(['a.id', 'a.user_id', 'b.avatar', 'b.nickname', 'a.answer_time', 'a.answer_count', DB::raw("ROUND(sum({$prefix}a.answer_time)/3600,0) as answer_hour"), DB::raw("sum({$prefix}a.answer_count) as count")])
  250. ->groupBy('a.user_id')
  251. ->orderByRaw("sum({$prefix}a.answer_time)/3600 desc")
  252. ->take($num)
  253. ->get();
  254. $datas = $datas ? $datas->toArray() : [];
  255. if ($datas) {
  256. foreach ($datas as &$item) {
  257. $item['avatar'] = $item['avatar'] ? get_image_url($item['avatar']) : '';
  258. }
  259. RedisService::set($cacheKey, $datas, rand(20, 30));
  260. }
  261. return $datas;
  262. }
  263. /**
  264. * 获取答题卡列表题目数据
  265. * @param $userId 用户
  266. * @param $paperId
  267. * @param int $rid
  268. * @return array|mixed
  269. */
  270. public function getCardList($userId, $paperId, $rid=0)
  271. {
  272. $cacheKey = "caches:exams:{$userId}_cardList:{$paperId}_{$rid}";
  273. $datas = RedisService::get($cacheKey);
  274. if($datas){
  275. return $datas;
  276. }
  277. $datas = ExamTopicModel::from('exam_topics as a')
  278. ->leftJoin('exam_answers_topics as b',function($join) use($userId, $rid){
  279. if($rid){
  280. $join->on('b.topic_id','=','a.id')->where(['b.user_id'=>$userId,'b.answer_log_id'=> $rid,'status'=>1,'mark'=>1]);
  281. }
  282. })
  283. ->where(['a.paper_id'=> $paperId, 'a.status'=>1,'a.mark'=>1])
  284. ->select(['a.id','a.topic_name','a.answer','a.score','a.paper_id','a.topic_type','b.id as rid','b.answer as submit_answer','b.accurate','b.score as submit_score'])
  285. ->groupBy('a.topic_type')
  286. ->orderBy('a.sort','desc')
  287. ->orderBy('a.id','asc')
  288. ->get();
  289. $datas = $datas? $datas->toArray() :[];
  290. if($datas){
  291. foreach ($datas as &$item){
  292. $item['rid'] = !empty($item['rid'])? $item['rid'] : 0;
  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. }
  297. RedisService::set($cacheKey, $datas, rand(5, 10));
  298. }
  299. return $datas;
  300. }
  301. /**
  302. * 重新答题,清除答题记录数据
  303. * @param $id
  304. * @return bool
  305. */
  306. public function reset($id, $userId=0)
  307. {
  308. $log = $this->model->where(['id'=> $id,'mark'=>1])->first();
  309. if(empty($log)){
  310. return true;
  311. }
  312. $updateData = ['score'=>0,'accurate_count'=>0,'answer_count'=>0,'answer_times'=>0,'answer_last_id'=>0,'is_submit'=>0,'status'=>1];
  313. $this->model->where(['id'=> $id,'mark'=>1])->update($updateData);
  314. ExamAnswerTopicModel::where(['answer_log_id'=> $id,'mark'=>1])->update(['status'=>2,'update_time'=>time()]);
  315. RedisService::keyDel("caches:exams:{$userId}*");
  316. return true;
  317. }
  318. /**
  319. * 答题
  320. * @param $userId
  321. * @param $params
  322. * @return array|false
  323. */
  324. public function answer($userId, $params)
  325. {
  326. $paperId = isset($params['id'])? $params['id'] : 0;
  327. $rid = isset($params['rid'])? $params['rid'] : 0;
  328. $tid = isset($params['tid'])? $params['tid'] : 0;
  329. $isSubmit = isset($params['is_submit'])? $params['is_submit'] : 1;
  330. $answer = isset($params['answer'])? $params['answer'] : '';
  331. $answerImage = isset($params['answer_image'])? $params['answer_image'] : '';
  332. $answerType = isset($params['answer_type']) && $params['answer_type']? $params['answer_type'] : 2;
  333. $remainTime = isset($params['remain_time']) && $params['remain_time']? $params['remain_time'] : 0;
  334. if($isSubmit<=0 && $answerType==2 && empty($answer)){
  335. $this->error = '请先提交答案';
  336. return false;
  337. }
  338. if($isSubmit<=0 && $answerType==1 && empty($answerImage)){
  339. $this->error = '请先上传图片答案';
  340. return false;
  341. }
  342. $cacheKey = "caches:answers:{$userId}_{$paperId}:{$tid}_{$rid}";
  343. if(RedisService::get($cacheKey.'_lock')){
  344. $this->error = '请不要频繁提交';
  345. return false;
  346. }
  347. RedisService::set($cacheKey.'_lock', $params, rand(2,3));
  348. // 试卷数据
  349. $paperInfo = ExamPaperModel::where(['id'=> $paperId,'status'=>1,'mark'=>1])
  350. ->first();
  351. $type = isset($paperInfo['type']) && $paperInfo['type']? $paperInfo['type'] : 1;
  352. $sceneType = isset($paperInfo['scene_type']) && $paperInfo['scene_type']? $paperInfo['scene_type'] : 1;
  353. $topicCount = isset($paperInfo['topic_count'])? $paperInfo['topic_count'] : 0;
  354. if(empty($paperInfo)){
  355. RedisService::clear($cacheKey.'_lock');
  356. $this->error = '试题数据错误,请返回刷新重试';
  357. return false;
  358. }
  359. // 题目数据
  360. $topicInfo = ExamTopicModel::where(['id'=> $tid,'paper_id'=>$paperId,'status'=>1,'mark'=>1])->first();
  361. $topicType = isset($topicInfo['topic_type'])? trim($topicInfo['topic_type']) : '';
  362. $topicScore = isset($topicInfo['score'])? intval($topicInfo['score']) : 0;
  363. $topicName = isset($topicInfo['topic_name'])? $topicInfo['topic_name'] : '';
  364. $topicShowType = isset($topicInfo['show_type'])? $topicInfo['show_type'] : 1;
  365. $correctAnswer = isset($topicInfo['correct_answer'])? $topicInfo['correct_answer'] : '';
  366. if(empty($topicInfo) || empty($topicType) || empty($topicName)){
  367. RedisService::clear($cacheKey.'_lock');
  368. $this->error = '题库已更新,请返回刷新重试';
  369. return false;
  370. }
  371. // 答题记录
  372. $submit = 0;
  373. $answerCount = 0;
  374. if($rid){
  375. $answerInfo = ExamAnswerModel::where(['id'=>$rid,'status'=>1,'mark'=>1])->first();
  376. $submit = isset($answerInfo['is_submit'])? $answerInfo['is_submit'] : 0;
  377. $answerCount = isset($answerInfo['answer_count'])? $answerInfo['answer_count'] : 0;
  378. if(empty($answerInfo)){
  379. $rid = 0;
  380. }
  381. if($submit){
  382. $this->error = '您已交卷';
  383. return false;
  384. }
  385. }
  386. // 验证答案内容类型和数据
  387. // 每日一练
  388. if($sceneType == 1 && $rid<=0){
  389. // 今日记录
  390. $answerInfo = ExamAnswerModel::where(['paper_id'=>$paperId,'status'=>1,'mark'=>1])->where('create_time','>=', strtotime(date('Y-m-d')))->first();
  391. $rid = isset($answerInfo['id'])? $answerInfo['id'] : 0;
  392. $submit = isset($answerInfo['is_submit'])? $answerInfo['is_submit'] : 0;
  393. $answerCount = isset($answerInfo['answer_count'])? $answerInfo['answer_count'] : 0;
  394. }
  395. // 是否已交卷
  396. if($submit == 1){
  397. RedisService::clear($cacheKey.'_lock');
  398. $this->error = '您已交卷';
  399. return false;
  400. }
  401. // 直接交卷
  402. $totalTime = ConfigService::make()->getConfigByCode('answer_total_time', 1800);
  403. $answerTime = $totalTime >$remainTime? $totalTime-$remainTime : $totalTime;
  404. if($isSubmit==1 && empty($answer) && empty($answerImage)){
  405. // 是否提交过
  406. if($answerCount<=0){
  407. $this->error = '您未提交过答案,请先答题再交卷';
  408. return false;
  409. }
  410. $this->model->where(['id'=> $rid])->update(['is_submit'=>1,'update_time'=>time()]);
  411. $this->error = '交卷成功';
  412. // 答题时间统计
  413. $id = MemberAnswerRankModel::where(['user_id'=> $userId,'date'=>date('Y-m-d'),'mark'=>1])->value('id');
  414. if($id){
  415. MemberAnswerRankModel::where(['id'=> $id])->update(['answer_time'=>DB::raw("answer_time + {$answerTime}"),'answer_count'=>DB::raw("answer_count + {$answerCount}"),'update_time'=>time()]);
  416. }else{
  417. MemberAnswerRankModel::insert(['user_id'=>$userId,'answer_time'=>$answerTime,'answer_count'=> $answerCount,'date'=>date('Y-m-d'),'create_time'=>time()]);
  418. }
  419. RedisService::keyDel("caches:exams:{$userId}*");
  420. return ['rid'=> $rid,'paper_id'=>$paperId];
  421. }
  422. // 该题是否已提交答案
  423. $logId = 0;
  424. if($rid>0){
  425. $answerTopic = ExamAnswerTopicModel::where(['answer_log_id'=>$rid,'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. var_dump($apiData);
  470. $result = DeepSeekService::make()->apiRequest($apiData);
  471. RedisService::clear($cacheKey.'_lock');
  472. $this->error = '功能开放中~';
  473. return false;
  474. }else {
  475. $submitType = 2;
  476. $apiData = [
  477. 'answer'=> $answer,
  478. 'score'=> $topicScore,
  479. 'topic'=> $topicShowType == 2 && $topicName? DeepSeekService::make()->getImageTopicData($topicName) : $topicName,
  480. ];
  481. $result = DeepSeekService::make()->apiRequest($apiData);
  482. $score = isset($result['score'])?$result['score'] : 0;
  483. $analysis = isset($result['analysis'])?$result['analysis'] : '';
  484. if($score>0){
  485. $topicData['accurate'] = 1;
  486. $topicData['score'] = $score;
  487. $topicData['answer_analysis'] = $analysis;
  488. }else{
  489. $topicData['accurate'] = 0;
  490. }
  491. }
  492. }
  493. DB::beginTransaction();
  494. if($rid){
  495. $log = [
  496. 'answer_times'=> $answerTime,
  497. 'answer_last_at'=> date('Y-m-d H:i:s'),
  498. 'answer_count'=> DB::raw("answer_count + 1"),
  499. 'answer_last_id'=> $tid,
  500. 'is_submit'=> $isSubmit==1?1:0,
  501. 'update_time'=> time()
  502. ];
  503. // 对题数
  504. if($topicData['accurate']==1){
  505. $log['accurate_count'] = DB::raw("accurate_count + 1");
  506. $log['score'] = DB::raw("score + {$topicData['score']}");
  507. }
  508. if(!$this->model->where(['id'=> $rid])->update($log)){
  509. DB::rollBack();
  510. RedisService::clear($cacheKey.'_lock');
  511. $this->error = '答题失败,请刷新后重新提交';
  512. return false;
  513. }
  514. }else{
  515. $log = [
  516. 'user_id'=> $userId,
  517. 'paper_id'=> $paperId,
  518. 'score'=> $topicData['score'],
  519. 'answer_count'=> 1,
  520. 'answer_times'=> $answerTime,
  521. 'answer_last_at'=> date('Y-m-d H:i:s'),
  522. 'answer_last_id'=> $tid,
  523. 'is_submit'=> $isSubmit,
  524. 'create_time'=> time()
  525. ];
  526. if(!$rid = $this->model->insertGetId($log)){
  527. DB::rollBack();
  528. RedisService::clear($cacheKey.'_lock');
  529. $this->error = '答题失败,请刷新后重新提交';
  530. return false;
  531. }
  532. }
  533. // 答题题目数据
  534. $topicData['answer_type'] = $submitType;
  535. $topicData['answer_log_id'] = $rid;
  536. if($logId){
  537. $topicData['update_time'] = $submitType;
  538. ExamAnswerTopicModel::where(['id'=> $logId])->update($topicData);
  539. }else if (!ExamAnswerTopicModel::insert($topicData)){
  540. DB::rollBack();
  541. RedisService::clear($cacheKey.'_lock');
  542. $this->error = '答题失败,请刷新后重新提交';
  543. return false;
  544. }
  545. DB::commit();
  546. // 答题时间统计
  547. if($isSubmit==1){
  548. $id = MemberAnswerRankModel::where(['user_id'=> $userId,'date'=>date('Y-m-d'),'mark'=>1])->value('id');
  549. if($id){
  550. $answerCount++;
  551. MemberAnswerRankModel::where(['id'=> $id])->update(['answer_time'=>DB::raw("answer_time + {$answerTime}"),'answer_count'=>DB::raw("answer_count + {$answerCount}"),'update_time'=>time()]);
  552. }else{
  553. MemberAnswerRankModel::insert(['user_id'=>$userId,'answer_time'=>$answerTime,'answer_count'=> $answerCount,'date'=>date('Y-m-d'),'create_time'=>time()]);
  554. }
  555. }
  556. $this->error = '答题成功';
  557. RedisService::clear($cacheKey.'_lock');
  558. RedisService::keyDel("caches:exams:{$userId}*");
  559. RedisService::clear("caches:exams:info_{$rid}");
  560. RedisService::keyDel("caches:paper:info_{$userId}:p{$paperId}*");
  561. return ['paper_id'=> $paperId,'rid'=>$rid,'tid'=>$tid, 'accurate'=> $topicData['accurate'],'answer'=>$topicData['answer']];
  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'])
  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. }