ChatService.php 38 KB

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