ChatService.php 36 KB

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