ChatService.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  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::insertGetId($info);
  719. if ($result) {
  720. return Result::success($data);
  721. } else {
  722. return Result::error($data);
  723. };
  724. }
  725. /**
  726. * 话题 - 列表
  727. * @param array $data
  728. * @return array
  729. */
  730. public function getTopicsList(array $data): array
  731. {
  732. $where = [];
  733. if (!empty($data['title'])) {
  734. $where[] = ['chat_topics.title', 'like', '%' . $data['title'] . '%'];
  735. }
  736. if (!empty($data['user_id'])) {
  737. $where[] = ['chat_topics.user_id', '=', $data['user_id']];
  738. }
  739. if (!empty($data['status'])) {
  740. $where[] = ['chat_topics.status', '=', $data['status']];
  741. }
  742. if (!empty($data['type'])) {
  743. $where[] = ['chat_topics.type', '=', $data['type']];
  744. }
  745. if (!empty($data['nickname'])) {
  746. $where[] = ['user.nickname', '=', $data['nickname']];
  747. }
  748. var_dump($where);
  749. $result = ChatTopic::where($where)
  750. ->leftJoin('user', 'user.id', '=', 'chat_topics.user_id')
  751. ->leftJoin('chat_topics_reply', 'chat_topics.id', '=', 'chat_topics_reply.topic_id')
  752. ->select('chat_topics.*', 'user.nickname', 'user.avatar', 'user.user_name'
  753. ,
  754. DB::raw('count(chat_topics_reply.id) as num'))
  755. ->groupBy('chat_topics.id')
  756. ->orderBy('chat_topics.id', 'desc')
  757. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  758. return Result::success($result);
  759. }
  760. public function getTopic(array $data): array
  761. {
  762. $result = ChatTopic::where(['id' => $data['id']])->first();
  763. return Result::success($result);
  764. }
  765. public function addTopic(array $data): array
  766. {
  767. $chattopic = [];
  768. try {
  769. $data['created_at'] = date('Y-m-d H:i:s');
  770. $data['updated_at'] = date('Y-m-d H:i:s');
  771. $result = ChatTopic::insertGetId($data);
  772. if ($result && $data['is_group'] == 1) {
  773. //chat_group
  774. $group_id = PublicData::uuid();
  775. $groupData = [
  776. 'id' => $group_id,
  777. 'creator_id' => $data['user_id'],
  778. 'group_name' => $data['group_name'] ?? '',
  779. 'profile' => $data['profile'] ?? 0,
  780. ];
  781. $groupResult = ChatGroups::insertGetId($groupData);
  782. $groupMemberData = [
  783. 'id' => PublicData::uuid(),
  784. 'user_id' => $data['user_id'],
  785. 'group_id' => $group_id,
  786. 'leader' => 2,
  787. ];
  788. $groupMemberResult = ChatGroupsMember::insertGetId($groupMemberData);
  789. //更新result的 group_id
  790. $data['group_id'] = $group_id;
  791. ChatTopic::where(['id' => $result])->update($data);
  792. // 查询 Chattopic 数据
  793. $chattopic = Chattopic::find($result);
  794. } else {
  795. $chattopic = Chattopic::find($result);
  796. }
  797. Db::beginTransaction();
  798. Db::commit();
  799. } catch (\Exception $e) {
  800. Db::rollBack();
  801. return Result::error($data, $e->getMessage());
  802. }
  803. return Result::success($chattopic);
  804. }
  805. public function applyTopic(array $data): array
  806. {
  807. date_default_timezone_set('Asia/Shanghai');
  808. db::beginTransaction();
  809. try {
  810. $query = ChatTopic::where(['id' => $data['id']]);
  811. $topdata = $query->first();
  812. $result = ChatTopic::where(['id' => $data['id']])->update(['status' => $data['status']]);
  813. var_dump($result, 'tedst111111111111111');
  814. var_dump(date('Y-m-d H:i:s'), 'tedst111111111111111');
  815. if ($data['status'] == 2) {
  816. //插入一条消息
  817. $chatRecordsData = [
  818. 'user_id' => $topdata['user_id'],
  819. 'receiver_id' => $topdata['group_id'],
  820. 'content' => '我创建了一个群' . Date('Y-m-d H:i:s'),
  821. 'msg_type' => 1,
  822. 'is_read' => 0,
  823. 'talk_type' => 2,
  824. 'action' => 'said',
  825. 'group_receiver_id' => $topdata['user_id'],
  826. ];
  827. ChatRecords::insert($chatRecordsData);
  828. } else {
  829. ChatRecords::where('user_id', $topdata['user_id'])->where('receiver_id', $topdata['group_id'])->delete();
  830. }
  831. Db::commit();
  832. if ($result) {
  833. return Result::success($data);
  834. } else {
  835. return Result::error($data);
  836. }
  837. } catch (\Exception $e) {
  838. Db::rollBack();
  839. return Result::error($data, $e->getMessage());
  840. }
  841. if (empty($data['id'])) {
  842. return Result::error('id不能为空');
  843. }
  844. }
  845. public function updateTopic(array $data): array
  846. {
  847. if (empty($data['id'])) {
  848. return Result::error('id不能为空');
  849. }
  850. $result = ChatTopic::where(['id' => $data['id']])->update($data);
  851. if ($result) {
  852. return Result::success($data);
  853. } else {
  854. return Result::error($data);
  855. };
  856. }
  857. public function delTopic(array $data): array
  858. {
  859. $result = ChatTopic::where(['id' => $data['id']])->delete();
  860. //删除群和成员和聊天
  861. //删除话题回复
  862. if ($result) {
  863. return Result::success($data);
  864. } else {
  865. return Result::error('删除失败');
  866. };
  867. }
  868. public function getTopicInfo(array $data): array
  869. {
  870. $result = ChatTopic::where(['chat_topics.id' => $data['id']])
  871. ->leftJoin('user', 'user.id', '=', 'chat_topics.user_id')
  872. ->select('chat_topics.*', 'user.nickname', 'user.avatar', 'user.user_name')
  873. ->first();
  874. return Result::success($result);
  875. }
  876. public function addReply(array $data): array
  877. {
  878. $result = ChatTopic::where(['id' => $data['id']])->get();
  879. if ($result) {
  880. $replydata['created_at'] = date('Y-m-d H:i:s');
  881. $replydata['updated_at'] = date('Y-m-d H:i:s');
  882. $replydata['content'] = $data['content'];
  883. $replydata['user_id'] = $data['user_id'];
  884. $replydata['topic_id'] = $data['id'];
  885. $re = ChatTopicsReply::insertGetId($replydata);
  886. }
  887. if ($re) {
  888. return Result::success($data);
  889. } else {
  890. return Result::error($data);
  891. }
  892. }
  893. public function getTopicReply(array $data): array
  894. {
  895. var_dump($data);
  896. $result = ChatTopicsReply::where(['topic_id' => $data['id']])
  897. ->leftJoin('user', 'user.id', '=', 'chat_topics_reply.user_id')
  898. ->select('chat_topics_reply.*', 'user.nickname', 'user.avatar', 'user.user_name')
  899. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  900. return Result::success($result);
  901. }
  902. /**
  903. * 修改群成员
  904. * @param array $data
  905. * @return array
  906. */
  907. public function updateGroupMembers(array $data): array
  908. {
  909. $where = [
  910. 'group_id' => $data['group_id'],
  911. ];
  912. $group_id = $data['group_id'];
  913. //先删除群成员
  914. $result = ChatGroupsMember::where($where)
  915. ->where([["user_id", '!=', $data['user_id']]])->delete();
  916. $groupMemberData = [];
  917. foreach ($data['group_member'] as $value) {
  918. $groupMemberData[] = [
  919. 'id' => PublicData::uuid(),
  920. 'user_id' => $value,
  921. 'group_id' => $group_id,
  922. 'leader' => 0,
  923. ];
  924. }
  925. $result = ChatGroupsMember::where($where)->insert($groupMemberData);
  926. // 获取群信息
  927. $groupInfo = ChatGroups::where(['id' => $group_id])->first();
  928. if ($result) {
  929. return Result::success($groupInfo);
  930. } else {
  931. return Result::error($data);
  932. }
  933. }
  934. public function clearGroupRecords(array $data): array
  935. {
  936. $result = ChatRecords::where(['user_id' => $data['user_id'], 'receiver_id' => $data['id']])->delete();
  937. if ($result) {
  938. return Result::success("删除成功");
  939. } else {
  940. return Result::error("删除失败");
  941. }
  942. }
  943. public function recallRecord(array $data): array
  944. {
  945. //获取所有id,并删除掉
  946. $ids = array_column($data, 'id');
  947. $result = ChatRecords::whereIn('id', $ids)->delete();
  948. if ($result) {
  949. return Result::success("删除成功");
  950. } else {
  951. return Result::error("删除失败");
  952. }
  953. }
  954. public function clearRecords(array $data): array
  955. {
  956. $result = ChatRecords::where(['user_id' => $data['user_id'], 'receiver_id' => $data['friend_id']])->delete();
  957. if ($result) {
  958. return Result::success("删除成功");
  959. } else {
  960. return Result::error("删除失败");
  961. }
  962. }
  963. public function getRecordByContent(array $data): array
  964. {
  965. $result = ChatRecords::where(['chat_records.user_id' => $data['user_id'], 'chat_records.receiver_id' => $data['receiver_id'], 'chat_records.content' => $data['content']])
  966. ->orWhere(['chat_records.receiver_id' => $data['user_id'], 'chat_records.user_id' => $data['receiver_id'], 'chat_records.content' => $data['content']])
  967. ->all();
  968. if ($result) {
  969. return Result::success($result['id']);
  970. } else {
  971. return Result::error("没有数据");
  972. }
  973. }
  974. public function getRecord(array $data): array
  975. {
  976. $result = ChatRecords::where(['chat_records.id' => $data['id']])
  977. ->leftJoin('user', 'user.id', '=', 'chat_records.user_id')
  978. ->leftJoin('user as user2', 'user2.id', '=', 'chat_records.receiver_id')
  979. ->select('chat_records.*', 'user.nickname', 'user.avatar', 'user.user_name', 'user2.nickname as receiver_nickname', 'user2.avatar as receiver_avatar')
  980. ->get();
  981. return Result::success($result);
  982. }
  983. public function delReply(array $data): array
  984. {
  985. $result = ChatTopicsReply::where(['id' => $data['id']])->delete();
  986. if ($result) {
  987. return Result::success("删除成功");
  988. } else {
  989. return Result::error("删除失败");
  990. }
  991. }
  992. public function delAllReply(array $data): array
  993. {
  994. $result = ChatTopicsReply::where(['topic_id' => $data['topicid']])->delete();
  995. if ($result) {
  996. return Result::success("删除成功");
  997. } else {
  998. return Result::error("删除失败");
  999. }
  1000. }
  1001. public function getTopicsListAdmin(array $data): array
  1002. {
  1003. $where = [];
  1004. if (!empty($data['type'])) {
  1005. $where['type'] = $data['type'];
  1006. }
  1007. if (!empty($data['title'])) {
  1008. $where['title'] = $data['title'];
  1009. }
  1010. $result = ChatTopic::where($where)
  1011. ->leftJoin('user', 'user.id', '=', 'chat_topics.user_id')
  1012. ->select('chat_topics.*', 'user.nickname', 'user.avatar', 'user.user_name')
  1013. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  1014. return Result::success($result);
  1015. }
  1016. }