ChatService.php 38 KB

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