ChatService.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  1. <?php
  2. namespace App\JsonRpc;
  3. use App\Model\ChatFriends;
  4. use App\Model\ChatGroups;
  5. use App\Model\ChatGroupsMember;
  6. use App\Model\ChatRecords;
  7. use App\Model\ChatTopic;
  8. use App\Model\ChatTopicsReply;
  9. use App\Model\User;
  10. use App\Tools\PublicData;
  11. use App\Tools\Result;
  12. use Hyperf\DbConnection\Db;
  13. use Hyperf\RpcServer\Annotation\RpcService;
  14. #[RpcService(name: "ChatService", protocol: "jsonrpc-http", server: "jsonrpc-http")]
  15. class ChatService implements ChatServiceInterface
  16. {
  17. /**
  18. * 获取用户信息
  19. * @param array $data
  20. * @return array
  21. */
  22. public function getFriendInfo(array $data): array
  23. {
  24. $result = ChatFriends::where('friend_id', $data['friend_id'])
  25. ->where('user_id', $data['user_id'])
  26. ->select(
  27. 'chat_friends.*',
  28. 'user.user_name',
  29. 'user.mobile',
  30. 'user.nickname',
  31. 'user.avatar'
  32. )
  33. ->leftJoin('user', 'user.id', '=', 'chat_friends.friend_id')
  34. ->first();
  35. return Result::success($result);
  36. }
  37. /**
  38. * 搜索好友
  39. * @param array $data
  40. * @return array
  41. */
  42. public function searchFriend(array $data): array
  43. {
  44. $keyword = $data['keyword'];
  45. $userId = $data['user_id'];
  46. $result = User::where('user_name', 'like', '%' . $data['keyword'] . '%')
  47. ->orWhere('nickname', 'like', '%' . $data['keyword'] . '%')
  48. ->orWhere('mobile', 'like', '%' . $data['keyword'] . '%')
  49. ->leftJoin('chat_friends', function ($join) use ($userId) {
  50. $join->on('user.id', '=', 'chat_friends.friend_id')
  51. ->where('chat_friends.user_id', $userId);
  52. })
  53. ->select('user.*', 'chat_friends.remark as remark', 'chat_friends.id as isfriend')
  54. ->get();
  55. if ($result) {
  56. return Result::success($result);
  57. } else {
  58. return Result::error('没有找到相关好友');
  59. }
  60. }
  61. /**
  62. * 添加申请
  63. * @param array $data
  64. * @return array
  65. */
  66. public function addFriend(array $data): array
  67. {
  68. Db::beginTransaction();
  69. try
  70. {
  71. // 检查是否存在相同的记录
  72. $existingRecord = ChatFriends::where([
  73. 'user_id' => $data['user_id'],
  74. 'friend_id' => $data['friend_id'],
  75. ])->first();
  76. if ($existingRecord) {
  77. Db::rollBack();
  78. if ($existingRecord->status == 1) {
  79. return Result::error("好友申请已存在", 0);
  80. } elseif ($existingRecord->status == 2) {
  81. return Result::error("已经是好友关系", 0);
  82. }
  83. }
  84. $result = ChatFriends::insertGetId($data);
  85. Db::commit();
  86. } catch (\Throwable $ex) {
  87. Db::rollBack();
  88. var_dump($ex->getMessage());
  89. return Result::error("添加好友申请失败", 0);
  90. }
  91. return Result::success("添加成功");
  92. }
  93. /**
  94. * 好友列表
  95. * @param array $data
  96. * @return array
  97. */
  98. public function getFriendsList(array $data): array
  99. {
  100. var_dump($data);
  101. $result = ChatFriends::leftJoin('user', 'user.id', '=', 'chat_friends.friend_id')
  102. ->select(
  103. 'chat_friends.*',
  104. 'user.user_name',
  105. 'user.mobile',
  106. 'user.nickname',
  107. 'user.avatar'
  108. )
  109. ->where([
  110. ['user_id', $data['user_id']],
  111. ['chat_friends.status', $data['status']], // 明确指定 chat_friends 表中的 status 列
  112. ])
  113. ->get();
  114. return Result::success($result);
  115. }
  116. /**
  117. * 好友列表
  118. * @param array $data
  119. * @return array
  120. */
  121. public function getFriendsApplyList(array $data): array
  122. {
  123. var_dump($data);
  124. $result = ChatFriends::leftJoin('user', 'user.id', '=', 'chat_friends.user_id')
  125. ->select(
  126. 'chat_friends.*',
  127. 'user.user_name',
  128. 'user.mobile',
  129. 'user.nickname',
  130. 'user.avatar'
  131. )
  132. ->where([
  133. ['friend_id', $data['friend_id']],
  134. ['chat_friends.status', $data['status']], // 明确指定 chat_friends 表中的 status 列
  135. ])
  136. ->get();
  137. return Result::success($result);
  138. }
  139. /**
  140. * 更新申请
  141. * @param array $data
  142. * @return array
  143. */
  144. public function applyFriend(array $data): array
  145. {
  146. $status = $data['status'];
  147. //判断同意还是不同意
  148. if ($status == 2) {
  149. Db::beginTransaction();
  150. try {
  151. $where = [
  152. 'id' => $data['id'],
  153. 'status' => 1,
  154. ];
  155. $fr = ChatFriends::where($where)->first();
  156. if (empty($fr)) {
  157. Db::rollBack();
  158. return Result::error("好友申请记录不存在,已经是好友了", 0);
  159. }
  160. $data['status'] = $status;
  161. $data['applied_at'] = date("Y-m-d H:i:s"); //好友审核时间操作人friend_id
  162. unset($data['user_id']);
  163. ChatFriends::where($where)->update($data);
  164. Db::table('chat_friends')
  165. ->updateOrInsert(
  166. [
  167. 'user_id' => $fr['friend_id'],
  168. 'friend_id' => $fr['user_id'],
  169. ],
  170. [
  171. 'status' => $status,
  172. ]
  173. );
  174. Db::commit();
  175. } catch (\Throwable $ex) {
  176. Db::rollBack();
  177. var_dump($ex->getMessage());
  178. return Result::error("同意添加为好友失败", 0);
  179. }
  180. return Result::success(['添加成功']);
  181. } else if ($status == 4) { //拒绝
  182. Db::beginTransaction();
  183. try {
  184. $where1 = [
  185. 'id' => $data['id'],
  186. ];
  187. $deletedRows = ChatFriends::where($where1)->delete();
  188. if ($deletedRows > 0) {
  189. Db::commit();
  190. } else {
  191. // 处理记录不存在的情况
  192. Db::rollBack();
  193. throw new \Exception('记录不存在');
  194. }
  195. } catch (\Throwable $ex) {
  196. Db::rollBack();
  197. var_dump($ex->getMessage());
  198. return Result::error("拒绝添加好友失败", 0);
  199. }
  200. return Result::success(['已经拒绝']);
  201. }
  202. }
  203. /**
  204. * 删除好友
  205. * @param array $data
  206. * @return array
  207. */
  208. public function delFriend(array $data): array
  209. {
  210. Db::beginTransaction();
  211. try {
  212. $where = [
  213. 'user_id' => $data['user_id'],
  214. 'friend_id' => $data['friend_id'],
  215. ];
  216. $orwhere = [
  217. 'user_id' => $data['friend_id'],
  218. 'friend_id' => $data['user_id'],
  219. ];
  220. // 使用闭包来确保正确的 OR 关系
  221. $result = ChatFriends::where(function ($query) use ($where) {
  222. $query->where($where);
  223. })
  224. ->orWhere(function ($query) use ($orwhere) {
  225. $query->where($orwhere);
  226. })
  227. ->delete();
  228. var_dump($result, '-0------------------');
  229. $wherechat = [
  230. 'user_id' => $data['user_id'],
  231. 'receiver_id' => $data['friend_id'],
  232. ];
  233. $orwherechat = [
  234. 'user_id' => $data['friend_id'],
  235. 'receiver_id' => $data['user_id'],
  236. ];
  237. // 使用闭包来确保正确的 OR 关系
  238. ChatRecords::where(function ($query) use ($wherechat) {
  239. $query->where($wherechat);
  240. })
  241. ->orWhere(function ($query) use ($orwherechat) {
  242. $query->where($orwherechat);
  243. })
  244. ->delete();
  245. Db::commit();
  246. return Result::success("删除成功");
  247. } catch (\Exception $e) {
  248. Db::rollback();
  249. return Result::error($e->getMessage());
  250. }
  251. }
  252. /**
  253. * 是否好友
  254. * @param array $data
  255. * @return array
  256. */
  257. public function isFriend(array $data): array
  258. {
  259. $where = [
  260. 'user_id' => $data['user_id'],
  261. 'friend_id' => $data['friend_id'],
  262. ];
  263. $result = ChatFriends::where($where)->first();
  264. if ($result) {
  265. return Result::success(true);
  266. } else {
  267. return Result::error('不是好友');
  268. }
  269. }
  270. /**
  271. * 添加聊天内容
  272. * @param array $data
  273. * @return array
  274. */
  275. public function addChatRecords(array $data): array
  276. {
  277. Db::beginTransaction();
  278. try {;
  279. //添加会话内容
  280. $ChatRecordsData = [[
  281. 'msg_type' => $data['msg_type'] ?? 0,
  282. 'user_id' => $data['user_id'] ?? 0,
  283. 'is_read' => $data['is_read'] ?? 0,
  284. 'talk_type' => $data['talk_type'] ?? 0,
  285. 'action' => $data['action'] ?? 0,
  286. 'group_receiver_id' => $data['group_receiver_id'] ?? 0,
  287. 'content' => $data['content'] ?? '',
  288. 'receiver_id' => $data['receiver_id'] ?? '',
  289. ]];
  290. ChatRecords::insert($ChatRecordsData);
  291. Db::commit();} catch (\Throwable $ex) {
  292. Db::rollBack();
  293. var_dump($ex->getMessage());
  294. return Result::error("存储消息失败", 0);
  295. }
  296. return Result::success([]);
  297. }
  298. /**
  299. * 修改好友备注
  300. * @param array $data
  301. * @return array
  302. */
  303. public function updateFriend(array $data): array
  304. {
  305. $result = ChatFriends::where(['user_id' => $data['user_id'],
  306. 'friend_id' => $data['friend_id'],
  307. 'status' => 2,
  308. ])->update(['remark' => $data['remark']]);
  309. if ($result) {
  310. return Result::success('修改成功');
  311. } else {
  312. return Result::error('修改失败');
  313. }
  314. }
  315. /**
  316. * 会话列表
  317. * @param array $data
  318. * @return array
  319. */
  320. public function getConversation(array $data): array
  321. {
  322. $userId = $data['user_id'];
  323. $unreadMessages = ChatRecords::where('user_id', $userId)
  324. ->where('is_read', 0)
  325. // ->where('action', 'recieved')
  326. ->leftJoin('user', 'chat_records.receiver_id', '=', 'user.id')
  327. ->leftJoin('chat_groups', 'chat_records.receiver_id', '=', 'chat_groups.id')
  328. ->select(
  329. 'receiver_id',
  330. DB::raw('COUNT(receiver_id) AS num'),
  331. DB::raw('MAX(chat_records.id) AS max_id'),
  332. 'user.user_name as user_name',
  333. 'user.avatar as avatar',
  334. 'user.mobile as mobile',
  335. 'chat_groups.group_name as group_name'
  336. )
  337. ->groupBy('receiver_id')
  338. ->orderBy(DB::raw('MAX(chat_records.id)'), 'desc')
  339. ->get();
  340. // 查询已读消息,并将 num 字段设置为 0
  341. $readMessages = ChatRecords::where('user_id', $userId)
  342. ->where('is_read', 1)
  343. // ->where('action', 'recieved')
  344. ->leftJoin('user', 'chat_records.receiver_id', '=', 'user.id')
  345. ->leftJoin('chat_groups', 'chat_records.receiver_id', '=', 'chat_groups.id')
  346. ->select(
  347. 'receiver_id',
  348. DB::raw('0 AS num'),
  349. DB::raw('MAX(chat_records.id) AS max_id'),
  350. 'user.user_name as user_name',
  351. 'user.avatar as avatar',
  352. 'user.mobile as mobile',
  353. 'chat_groups.group_name as group_name'
  354. )
  355. ->groupBy('receiver_id')
  356. ->orderBy(DB::raw('MAX(chat_records.id)'), 'desc')
  357. ->get();
  358. // 合并未读消息和已读消息
  359. // $allMessages = array_merge($unreadMessages->toArray(), $readMessages->toArray());
  360. // 使用关联数组去重,并优先保留未读消息
  361. $allMessages = [];
  362. foreach ($unreadMessages as $message) {
  363. $allMessages[$message['receiver_id']] = $message->toArray();
  364. }
  365. foreach ($readMessages as $message) {
  366. if (strlen($message['receiver_id']) === 18) {
  367. } else {
  368. // $allMessages[$message['receiver_id']] = $message->toArray();
  369. }
  370. if (!isset($allMessages[$message['receiver_id']])) {
  371. $allMessages[$message['receiver_id']] = $message->toArray();
  372. }
  373. }
  374. // var_dump($allMessages);
  375. // 处理结果,判断是否是群聊
  376. $formattedMessages = [];
  377. foreach ($allMessages as $message) {
  378. $formattedMessage = [
  379. 'receiver_id' => $message['receiver_id'],
  380. 'num' => $message['num'],
  381. 'max_id' => $message['max_id'],
  382. 'user_name' => $message['user_name'],
  383. 'avatar' => $message['avatar'],
  384. 'mobile' => $message['mobile'],
  385. 'group_name' => $message['group_name'],
  386. ];
  387. if (strlen($message['receiver_id']) === 18) { // 判断是否是 UUID
  388. $formattedMessage['type'] = 'group';
  389. $formattedMessage['name'] = $message['group_name'];
  390. $formattedMessage['is_group'] = 1;
  391. } else {
  392. $formattedMessage['type'] = 'user';
  393. $formattedMessage['name'] = $message['user_name'];
  394. $formattedMessage['is_group'] = 0;
  395. }
  396. $formattedMessages[] = $formattedMessage;
  397. }
  398. if (!empty($formattedMessages)) {
  399. return Result::success($formattedMessages);
  400. } else {
  401. return Result::error('没有消息');
  402. }
  403. }
  404. /**
  405. * 获取聊天记录
  406. * @param array $data
  407. * @return array
  408. */
  409. public function getChatRecords(array $data): array
  410. {
  411. var_dump('222222');
  412. Db::beginTransaction();
  413. try {
  414. $userId = $data['user_id'];
  415. $friendId = $data['friend_id'];
  416. $result = ChatRecords::where(function ($query) use ($userId, $friendId) {
  417. $query->where('user_id', $userId)->where('receiver_id', $friendId);
  418. })
  419. // ->orWhere(function ($query) use ($userId, $friendId) {
  420. // $query->where('user_id', $friendId)->where('receiver_id', $userId);
  421. // })
  422. ->leftJoin('user as u1', 'chat_records.user_id', '=', 'u1.id')
  423. ->leftJoin('user as u2', 'chat_records.receiver_id', '=', 'u2.id')
  424. ->select('chat_records.*', 'u1.user_name as user_id_name', 'u1.avatar as user_avatar', 'u2.user_name as receiver_id_name', 'u2.avatar as receiver_avatar')
  425. ->orderBy('id', 'asc')->paginate(100, ['*'], 'page', $data['page'] ?? 1);
  426. //更新聊天记录已读
  427. ChatRecords::where('user_id', $userId)
  428. ->where('receiver_id', $friendId)
  429. ->where('is_read', 0)
  430. ->where('talk_type', 1)
  431. ->update(['is_read' => 1]);
  432. Db::commit();
  433. } catch (\Throwable $ex) {
  434. Db::rollBack();
  435. var_dump($ex->getMessage());
  436. return Result::error("获取聊天记录失败", 0);
  437. }
  438. if ($result) {
  439. return Result::success($result);
  440. } else {
  441. return Result::error('没有聊天记录');
  442. }
  443. }
  444. /**
  445. * 获取群聊天记录
  446. * @param array $data
  447. * @return array
  448. */
  449. public function getGroupChatRecords(array $data): array
  450. {
  451. Db::beginTransaction();
  452. try {
  453. $userId = $data['user_id'];
  454. $group_id = $data['group_id'];
  455. $result = ChatRecords::where('receiver_id', $group_id)
  456. ->where('user_id', $userId)
  457. ->leftJoin('user as u1', 'chat_records.user_id', '=', 'u1.id')
  458. ->leftJoin('user as u2', 'chat_records.group_receiver_id', '=', 'u2.id')
  459. ->select('chat_records.*', 'u1.user_name as user_id_name', 'u1.avatar as user_avatar', 'u2.user_name as receiver_id_name', 'u2.avatar as receiver_avatar')
  460. ->orderBy('id', 'asc')->paginate(100, ['*'], 'page', $data['page'] ?? 1);
  461. //更新群聊天记录
  462. ChatRecords::where('receiver_id', $group_id)
  463. ->where('user_id', $userId)
  464. ->update(['is_read' => 1]);
  465. Db::commit();
  466. } catch (\Throwable $ex) {
  467. Db::rollBack();
  468. var_dump($ex->getMessage());
  469. return Result::error("获取群聊天记录失败", 0);
  470. }
  471. if ($result) {
  472. return Result::success($result);
  473. } else {
  474. return Result::error('没有群消息');
  475. }
  476. }
  477. /**
  478. * 群组 - 创建群
  479. * @param array $data
  480. * @return array
  481. */
  482. public function addGroup(array $data): array
  483. {
  484. Db::beginTransaction();
  485. try {
  486. //创建群
  487. $groupData = [
  488. 'id' => PublicData::uuid(),
  489. 'creator_id' => $data['user_id'],
  490. 'group_name' => $data['group_name'],
  491. 'avatar' => $data['avatar'] ?? '',
  492. 'profile' => $data['profile'] ?? '',
  493. ];
  494. ChatGroups::insert($groupData);
  495. //创建群用户
  496. $groupMemberData = [];
  497. $groupChatData = [];
  498. if ($data['group_member']) {
  499. foreach ($data['group_member'] as $key => $val) {
  500. $groupMemberData[$key] = [
  501. 'id' => PublicData::uuid(),
  502. 'group_id' => $groupData['id'],
  503. 'user_id' => $val,
  504. 'leader' => $data['user_id'] == $val ? 2 : 0,
  505. ];
  506. $groupChatData[$key] = [
  507. 'user_id' => $val,
  508. 'receiver_id' => $groupData['id'],
  509. 'content' => '创建群' . Date('Y-m-d H:i:s'),
  510. 'msg_type' => 1,
  511. 'is_read' => 0,
  512. 'talk_type' => 2,
  513. 'action' => 'recieved',
  514. 'group_receiver_id' => $data['user_id'],
  515. ];
  516. }
  517. }
  518. ChatGroupsMember::insert($groupMemberData);
  519. //插入一条消息
  520. ChatRecords::insert($groupChatData);
  521. Db::commit();
  522. } catch (\Throwable $ex) {
  523. Db::rollBack();
  524. var_dump($ex->getMessage());
  525. return Result::error("创建群失败", 0);
  526. }
  527. return Result::success([]);
  528. }
  529. /**
  530. * 群组 - 加入群
  531. * @param array $data
  532. * @return array
  533. */
  534. public function addGroupMember(array $data): array
  535. {
  536. $result = ChatGroupsMember::where(['group_id' => $data['group_id'], 'user_id' => $data['user_id']])->update(['leader' => 2]);
  537. $groupChatData = [
  538. 'user_id' => $data['user_id'],
  539. 'receiver_id' => $data['group_id'],
  540. 'content' => '加入群' . Date('Y-m-d H:i:s'),
  541. 'msg_type' => 1,
  542. 'is_read' => 0,
  543. 'talk_type' => 2,
  544. 'action' => 'recieved',
  545. 'group_receiver_id' => $data['user_id'],
  546. ];
  547. ChatRecords::insert($groupChatData);
  548. if ($result) {
  549. return Result::success('修改成功');
  550. } else {
  551. return Result::error('修改失败');
  552. }
  553. }
  554. /**
  555. * 群组 - 群信息
  556. * @param array $data
  557. * @return array
  558. */
  559. public function getGroupInfo(array $data): array
  560. {
  561. $result = ChatGroups::where(['chat_groups.id' => $data['group_id']])
  562. ->join('user', 'chat_groups.creator_id', '=', 'user.id')
  563. ->select('chat_groups.*', 'user.user_name as user_name', 'user.avatar as avatar')
  564. ->first();
  565. return Result::success($result);
  566. }
  567. /**
  568. * 群组 - 删除群
  569. * @param array $data
  570. * @return array
  571. */
  572. public function delGroup(array $data): array
  573. {
  574. Db::beginTransaction();
  575. try {
  576. $groupMember = ChatGroupsMember::where(['group_id' => $data['group_id']])->delete();
  577. $result = ChatGroups::where(['id' => $data['group_id']])->delete();
  578. $result = ChatRecords::where(['receiver_id' => $data['group_id']])->delete();
  579. //群聊记录
  580. Db::commit();
  581. } catch (\Throwable $ex) {
  582. Db::rollBack();
  583. var_dump($ex->getMessage());
  584. return Result::error("删除群失败", 0);
  585. }
  586. if ($result) {
  587. return Result::success('删除成功');
  588. } else {
  589. return Result::error('删除失败');
  590. }
  591. }
  592. /**
  593. * 群组 - 退出群
  594. * @param array $data
  595. * @return array
  596. */
  597. public function quitGroup(array $data): array
  598. {
  599. $result = ChatGroupsMember::where(['group_id' => $data['group_id'], 'user_id' => $data['user_id']])->delete();
  600. ChatRecords::where(['receiver_id' => $data['group_id'], 'user_id' => $data['user_id']])->delete();
  601. if ($result) {
  602. return Result::success('退出成功');
  603. } else {
  604. return Result::error('退出失败');
  605. }
  606. }
  607. /**
  608. * 群组 - 我的群
  609. * @param array $data
  610. * @return array
  611. */
  612. public function getGroupList(array $data): array
  613. {
  614. $result = ChatGroupsMember::where(['user_id' => $data['user_id']])
  615. ->leftJoin('chat_groups', 'chat_groups_members.group_id', '=', 'chat_groups.id')
  616. ->select('chat_groups.*', 'chat_groups_members.group_id as group_id')
  617. ->orderBy('chat_groups.id', 'desc')
  618. ->paginate(100, ['*'], 'page', $data['page'] ?? 1);
  619. return Result::success($result);
  620. }
  621. /**
  622. * 群组 - 删除群成员
  623. * @param array $data
  624. * @return array
  625. */
  626. public function delGroupMembers(array $data): array
  627. {
  628. $result = ChatGroupsMember::where(['group_id' => $data['group_id'], 'user_id' => $data['user_id']])->delete();
  629. ChatRecords::where(['receiver_id' => $data['group_id'], 'user_id' => $data['user_id']])->delete();
  630. if ($result) {
  631. return Result::success('删除成功');
  632. } else {
  633. return Result::error('删除失败');
  634. }
  635. }
  636. /**
  637. * 群组 - 更新群
  638. * @param array $data
  639. * @return array
  640. */
  641. public function updateGroup(array $data): array
  642. {
  643. // 提取需要的字段
  644. $groupId = $data['group_id'];
  645. $groupName = $data['group_name'] ?? null;
  646. $profile = $data['profile'] ?? null;
  647. $avatar = $data['avatar'] ?? null;
  648. // 查询群组
  649. $group = ChatGroups::find($groupId);
  650. if (!$group) {
  651. return Result::error('群组不存在');
  652. }
  653. // 更新群组信息
  654. if ($groupName !== null) {
  655. $group->group_name = $groupName;
  656. }
  657. if ($profile !== null) {
  658. $group->profile = $profile;
  659. }
  660. if ($avatar !== null) {
  661. $group->avatar = $avatar;
  662. }
  663. // 保存更改
  664. if ($group->save()) {
  665. return Result::success($group->toArray());
  666. } else {
  667. return Result::error('更新群组信息失败');
  668. }
  669. }
  670. /**
  671. * 群组 - 删除群
  672. * @param array $data
  673. * @return array
  674. */
  675. public function deleteGroup(array $data): array
  676. {
  677. $result = ChatGroups::where(['id' => $data['group_id']])->delete();
  678. if ($result) {
  679. return Result::success('删除成功');
  680. } else {
  681. return Result::error('删除失败');
  682. }
  683. }
  684. /**
  685. * 群组 - 群用户列表
  686. * @param array $data
  687. * @return array
  688. */
  689. public function getGroupMembers(array $data): array
  690. {
  691. $groupMember = ChatGroupsMember::where(['group_id' => $data['group_id']])
  692. ->leftJoin('user as u1', 'chat_groups_members.user_id', '=', 'u1.id')
  693. ->select('chat_groups_members.*', 'u1.user_name', 'u1.avatar')
  694. ->orderBy('id', 'desc')
  695. ->get();
  696. return Result::success($groupMember);
  697. }
  698. /**
  699. * 群组 - 添加群
  700. * @param array $data
  701. * @return array
  702. */
  703. public function joinGroup(array $data): array
  704. {
  705. $group = ChatGroups::where(['id' => $data['group_id']])->first();
  706. if (empty($group)) {
  707. return Result::error("群不存在", 0);
  708. }
  709. $groupMember = ChatGroupsMember::where(['user_id' => $data['user_id'], 'group_id' => $data['group_id']])->first();
  710. if ($groupMember) {
  711. return Result::error("已加入群", 0);
  712. }
  713. $info = [
  714. 'id' => PublicData::uuid(),
  715. 'user_id' => $data['user_id'],
  716. 'group_id' => $data['group_id'],
  717. ];
  718. $result = ChatGroupsMember::insert($info);
  719. var_dump($result, '--------------------');
  720. if ($result) {
  721. return Result::success($data);
  722. } else {
  723. return Result::error($data);
  724. };
  725. }
  726. /**
  727. * 话题 - 列表
  728. * @param array $data
  729. * @return array
  730. */
  731. public function getTopicsList(array $data): array
  732. {
  733. $where = [];
  734. if (!empty($data['title'])) {
  735. $where[] = ['chat_topics.title', 'like', '%' . $data['title'] . '%'];
  736. }
  737. // 不是看自己的话题
  738. if (!empty($data['user_id_search'])) {
  739. $where[] = ['chat_topics.user_id', '=', $data['user_id_search']];
  740. }
  741. if (!empty($data['status'])) {
  742. $where[] = ['chat_topics.status', '=', $data['status']];
  743. }
  744. if (!empty($data['type'])) {
  745. $where[] = ['chat_topics.type', '=', $data['type']];
  746. }
  747. if (!empty($data['nickname'])) {
  748. $where[] = ['user.nickname', '=', $data['nickname']];
  749. }
  750. var_dump($where);
  751. $result = ChatTopic::where($where)
  752. ->leftJoin('user', 'user.id', '=', 'chat_topics.user_id')
  753. ->leftJoin('chat_topics_reply', 'chat_topics.id', '=', 'chat_topics_reply.topic_id')
  754. ->select('chat_topics.*', 'user.nickname', 'user.avatar', 'user.user_name'
  755. ,
  756. DB::raw('count(chat_topics_reply.id) as num'))
  757. ->groupBy('chat_topics.id')
  758. ->orderBy('chat_topics.id', 'desc')
  759. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  760. return Result::success($result);
  761. }
  762. public function getTopic(array $data): array
  763. {
  764. $result = ChatTopic::where(['id' => $data['id']])->first();
  765. return Result::success($result);
  766. }
  767. public function addTopic(array $data): array
  768. {
  769. $chattopic = [];
  770. try {
  771. $data['created_at'] = date('Y-m-d H:i:s');
  772. $data['updated_at'] = date('Y-m-d H:i:s');
  773. $result = ChatTopic::insertGetId($data);
  774. if ($result && $data['is_group'] == 1) {
  775. //chat_group
  776. $group_id = PublicData::uuid();
  777. $groupData = [
  778. 'id' => $group_id,
  779. 'creator_id' => $data['user_id'],
  780. 'group_name' => $data['group_name'] ?? '',
  781. 'profile' => $data['profile'] ?? 0,
  782. ];
  783. $groupResult = ChatGroups::insertGetId($groupData);
  784. $groupMemberData = [
  785. 'id' => PublicData::uuid(),
  786. 'user_id' => $data['user_id'],
  787. 'group_id' => $group_id,
  788. 'leader' => 2,
  789. ];
  790. $groupMemberResult = ChatGroupsMember::insertGetId($groupMemberData);
  791. //更新result的 group_id
  792. $data['group_id'] = $group_id;
  793. ChatTopic::where(['id' => $result])->update($data);
  794. // 查询 Chattopic 数据
  795. $chattopic = Chattopic::find($result);
  796. } else {
  797. $chattopic = Chattopic::find($result);
  798. }
  799. Db::beginTransaction();
  800. Db::commit();
  801. } catch (\Exception $e) {
  802. Db::rollBack();
  803. return Result::error($data, $e->getMessage());
  804. }
  805. return Result::success($chattopic);
  806. }
  807. public function applyTopic(array $data): array
  808. {
  809. date_default_timezone_set('Asia/Shanghai');
  810. db::beginTransaction();
  811. try {
  812. $query = ChatTopic::where(['id' => $data['id']]);
  813. $topdata = $query->first();
  814. $result = ChatTopic::where(['id' => $data['id']])->update(['status' => $data['status']]);
  815. var_dump($result, 'tedst111111111111111');
  816. var_dump(date('Y-m-d H:i:s'), 'tedst111111111111111');
  817. if ($data['status'] == 2) {
  818. //插入一条消息
  819. $chatRecordsData = [
  820. 'user_id' => $topdata['user_id'],
  821. 'receiver_id' => $topdata['group_id'],
  822. 'content' => '我创建了一个群' . Date('Y-m-d H:i:s'),
  823. 'msg_type' => 1,
  824. 'is_read' => 0,
  825. 'talk_type' => 2,
  826. 'action' => 'said',
  827. 'group_receiver_id' => $topdata['user_id'],
  828. ];
  829. ChatRecords::insert($chatRecordsData);
  830. } else {
  831. ChatRecords::where('user_id', $topdata['user_id'])->where('receiver_id', $topdata['group_id'])->delete();
  832. }
  833. Db::commit();
  834. if ($result) {
  835. return Result::success($data);
  836. } else {
  837. return Result::error($data);
  838. }
  839. } catch (\Exception $e) {
  840. Db::rollBack();
  841. return Result::error($data, $e->getMessage());
  842. }
  843. if (empty($data['id'])) {
  844. return Result::error('id不能为空');
  845. }
  846. }
  847. public function updateTopic(array $data): array
  848. {
  849. if (empty($data['id'])) {
  850. return Result::error('id不能为空');
  851. }
  852. $result = ChatTopic::where(['id' => $data['id']])->update($data);
  853. if ($result) {
  854. return Result::success($data);
  855. } else {
  856. return Result::error($data);
  857. };
  858. }
  859. public function delTopic(array $data): array
  860. {
  861. $result = ChatTopic::where(['id' => $data['id']])->delete();
  862. //删除群和成员和聊天
  863. //删除话题回复
  864. if ($result) {
  865. return Result::success($data);
  866. } else {
  867. return Result::error('删除失败');
  868. };
  869. }
  870. public function getTopicInfo(array $data): array
  871. {
  872. $result = ChatTopic::where(['chat_topics.id' => $data['id']])
  873. ->leftJoin('user', 'user.id', '=', 'chat_topics.user_id')
  874. ->select('chat_topics.*', 'user.nickname', 'user.avatar', 'user.user_name')
  875. ->first();
  876. return Result::success($result);
  877. }
  878. public function addReply(array $data): array
  879. {
  880. $result = ChatTopic::where(['id' => $data['id']])->get();
  881. if ($result) {
  882. $replydata['created_at'] = date('Y-m-d H:i:s');
  883. $replydata['updated_at'] = date('Y-m-d H:i:s');
  884. $replydata['content'] = $data['content'];
  885. $replydata['user_id'] = $data['user_id'];
  886. $replydata['topic_id'] = $data['id'];
  887. $re = ChatTopicsReply::insertGetId($replydata);
  888. }
  889. if ($re) {
  890. return Result::success($data);
  891. } else {
  892. return Result::error($data);
  893. }
  894. }
  895. public function getTopicReply(array $data): array
  896. {
  897. var_dump($data);
  898. $result = ChatTopicsReply::where(['topic_id' => $data['id']])
  899. ->leftJoin('user', 'user.id', '=', 'chat_topics_reply.user_id')
  900. ->select('chat_topics_reply.*', 'user.nickname', 'user.avatar', 'user.user_name')
  901. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  902. return Result::success($result);
  903. }
  904. /**
  905. * 修改群成员
  906. * @param array $data
  907. * @return array
  908. */
  909. public function updateGroupMembers(array $data): array
  910. {
  911. $where = [
  912. 'group_id' => $data['group_id'],
  913. ];
  914. $group_id = $data['group_id'];
  915. //先删除群成员
  916. $result = ChatGroupsMember::where($where)
  917. ->where([["user_id", '!=', $data['user_id']]])->delete();
  918. $groupMemberData = [];
  919. foreach ($data['group_member'] as $value) {
  920. $groupMemberData[] = [
  921. 'id' => PublicData::uuid(),
  922. 'user_id' => $value,
  923. 'group_id' => $group_id,
  924. 'leader' => 0,
  925. ];
  926. }
  927. $result = ChatGroupsMember::where($where)->insert($groupMemberData);
  928. // 获取群信息
  929. $groupInfo = ChatGroups::where(['id' => $group_id])->first();
  930. if ($result) {
  931. return Result::success($groupInfo);
  932. } else {
  933. return Result::error($data);
  934. }
  935. }
  936. public function clearGroupRecords(array $data): array
  937. {
  938. $result = ChatRecords::where(['user_id' => $data['user_id'], 'receiver_id' => $data['id']])->delete();
  939. if ($result) {
  940. return Result::success("删除成功");
  941. } else {
  942. return Result::error("删除失败");
  943. }
  944. }
  945. public function recallRecord(array $data): array
  946. {
  947. //获取所有id,并删除掉
  948. $ids = array_column($data, 'id');
  949. $result = ChatRecords::whereIn('id', $ids)->delete();
  950. if ($result) {
  951. return Result::success("删除成功");
  952. } else {
  953. return Result::error("删除失败");
  954. }
  955. }
  956. public function clearRecords(array $data): array
  957. {
  958. $result = ChatRecords::where(['user_id' => $data['user_id'], 'receiver_id' => $data['friend_id']])->delete();
  959. if ($result) {
  960. return Result::success("删除成功");
  961. } else {
  962. return Result::error("删除失败");
  963. }
  964. }
  965. public function getRecordByContent(array $data): array
  966. {
  967. $result = ChatRecords::where(['chat_records.user_id' => $data['user_id'], 'chat_records.receiver_id' => $data['receiver_id'], 'chat_records.content' => $data['content']])
  968. ->orWhere(['chat_records.receiver_id' => $data['user_id'], 'chat_records.user_id' => $data['receiver_id'], 'chat_records.content' => $data['content']])
  969. ->all();
  970. if ($result) {
  971. return Result::success($result['id']);
  972. } else {
  973. return Result::error("没有数据");
  974. }
  975. }
  976. public function getRecord(array $data): array
  977. {
  978. $result = ChatRecords::where(['chat_records.id' => $data['id']])
  979. ->leftJoin('user', 'user.id', '=', 'chat_records.user_id')
  980. ->leftJoin('user as user2', 'user2.id', '=', 'chat_records.receiver_id')
  981. ->select('chat_records.*', 'user.nickname', 'user.avatar', 'user.user_name', 'user2.nickname as receiver_nickname', 'user2.avatar as receiver_avatar')
  982. ->get();
  983. return Result::success($result);
  984. }
  985. public function delReply(array $data): array
  986. {
  987. $result = ChatTopicsReply::where(['id' => $data['id']])->delete();
  988. if ($result) {
  989. return Result::success("删除成功");
  990. } else {
  991. return Result::error("删除失败");
  992. }
  993. }
  994. public function delAllReply(array $data): array
  995. {
  996. $result = ChatTopicsReply::where(['topic_id' => $data['topicid']])->delete();
  997. if ($result) {
  998. return Result::success("删除成功");
  999. } else {
  1000. return Result::error("删除失败");
  1001. }
  1002. }
  1003. public function getTopicsListAdmin(array $data): array
  1004. {
  1005. $where = [];
  1006. if (!empty($data['type'])) {
  1007. $where['type'] = $data['type'];
  1008. }
  1009. if (!empty($data['title'])) {
  1010. $where['title'] = $data['title'];
  1011. }
  1012. $result = ChatTopic::where($where)
  1013. ->leftJoin('user', 'user.id', '=', 'chat_topics.user_id')
  1014. ->select('chat_topics.*', 'user.nickname', 'user.avatar', 'user.user_name')
  1015. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  1016. return Result::success($result);
  1017. }
  1018. }