request->param('type', 'user'); $type = $type === 'master' ? 'master' : 'user'; $category = $this->request->param('category', 'all'); $page = max(1, (int)$this->request->param('page', 1)); $limit = min(50, max(1, (int)$this->request->param('limit', 20))); $receiveId = $this->receiveId($type); $build = function () use ($type, $receiveId, $category) { $q = Db::name('message')->where('receive_type', $type)->where('receive_id', $receiveId); if ($category !== 'all' && $category !== '') { $q->where('type', $category); } return $q; }; $total = $build()->count(); $list = $build()->order('id desc')->page($page, $limit)->select(); foreach ($list as &$row) { $row['time_text'] = date('m-d H:i', (int)$row['createtime']); $row['is_read'] = (int)$row['is_read']; } unset($row); $this->success('', [ 'list' => $list, 'total' => (int)$total, 'unread' => $this->unreadCount($type, $receiveId), 'page' => $page, ]); } /** * 标记单条已读 * @ApiMethod (POST) */ public function read() { $id = (int)$this->request->post('id'); $type = $this->request->post('type', 'user') === 'master' ? 'master' : 'user'; $receiveId = $this->receiveId($type); $row = Db::name('message')->where('id', $id)->where('receive_type', $type)->where('receive_id', $receiveId)->find(); if (!$row) { $this->error('消息不存在'); } Db::name('message')->where('id', $id)->update(['is_read' => 1]); $this->success('已读'); } /** * 全部标记已读 * @ApiMethod (POST) */ public function readAll() { $type = $this->request->post('type', 'user') === 'master' ? 'master' : 'user'; $receiveId = $this->receiveId($type); $affected = Db::name('message') ->where('receive_type', $type)->where('receive_id', $receiveId)->where('is_read', 0) ->update(['is_read' => 1]); $this->success('已全部标记为已读', ['count' => (int)$affected]); } /** * 未读数(供 Tab 角标) */ public function unread() { $type = $this->request->param('type', 'user') === 'master' ? 'master' : 'user'; $this->success('', ['unread' => $this->unreadCount($type, $this->receiveId($type))]); } /** * 消息归属ID:用户=uid,师傅=master.id */ protected function receiveId($type) { if ($type === 'master') { $master = $this->masterInfo(); return $master ? (int)$master['id'] : 0; } return $this->uid(); } protected function unreadCount($type, $receiveId) { if (!$receiveId) { return 0; } return (int)Db::name('message') ->where('receive_type', $type)->where('receive_id', $receiveId)->where('is_read', 0) ->count(); } }