ChatService.php 38 KB

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