ChatService.php 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  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\ChatTopicClass;
  10. use App\Model\User;
  11. use App\Tools\PublicData;
  12. use App\Tools\Result;
  13. use Hyperf\DbConnection\Db;
  14. use Hyperf\RpcServer\Annotation\RpcService;
  15. #[RpcService(name: "ChatService", protocol: "jsonrpc-http", server: "jsonrpc-http")]
  16. class ChatService implements ChatServiceInterface
  17. {
  18. /**
  19. * 获取用户信息
  20. * @param array $data
  21. * @return array
  22. */
  23. public function getFriendInfo(array $data): array
  24. {
  25. $result = ChatFriends::where('friend_id', $data['friend_id'])
  26. ->where('user_id', $data['user_id'])
  27. ->select(
  28. 'chat_friends.*',
  29. 'user.user_name',
  30. 'user.mobile',
  31. 'user.nickname',
  32. 'user.avatar'
  33. )
  34. ->leftJoin('user', 'user.id', '=', 'chat_friends.friend_id')
  35. ->first();
  36. return Result::success($result);
  37. }
  38. /**
  39. * 搜索好友
  40. * @param array $data
  41. * @return array
  42. */
  43. public function searchFriend(array $data): array
  44. {
  45. $keyword = $data['keyword'];
  46. $userId = $data['user_id'];
  47. $result = User::leftJoin('chat_friends', function ($join) use ($userId) {
  48. $join->on('user.id', '=', 'chat_friends.friend_id')
  49. ->where('chat_friends.user_id', '=', $userId);
  50. })
  51. ->where(function ($query) use ($data) {
  52. $query->where('user.user_name', 'like', '%' . $data['keyword'] . '%')
  53. ->orWhere('user.nickname', 'like', '%' . $data['keyword'] . '%')
  54. ->orWhere('user.mobile', 'like', '%' . $data['keyword'] . '%');
  55. })
  56. ->where('user.id', '<>', $userId)
  57. ->where('user.type_id', '<>', '20000')
  58. ->select('user.*', 'chat_friends.remark as remark', 'chat_friends.id as isfriend')
  59. // ->select('user.*', 'chat_friends.friend_id')
  60. ->get();
  61. return Result::success($result);
  62. if ($result) {
  63. return Result::success($result);
  64. } else {
  65. return Result::error('没有找到相关好友');
  66. }
  67. }
  68. /**
  69. * 添加申请
  70. * @param array $data
  71. * @return array
  72. */
  73. public function addFriend(array $data): array
  74. {
  75. Db::beginTransaction();
  76. try {
  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();
  320. } catch (\Throwable $ex) {
  321. Db::rollBack();
  322. var_dump($ex->getMessage());
  323. return Result::error("存储消息失败", 0);
  324. }
  325. return Result::success([]);
  326. }
  327. /**
  328. * 修改好友备注
  329. * @param array $data
  330. * @return array
  331. */
  332. public function updateFriend(array $data): array
  333. {
  334. $result = ChatFriends::where([
  335. 'user_id' => $data['user_id'],
  336. 'friend_id' => $data['friend_id'],
  337. 'status' => 2,
  338. ])->update(['remark' => $data['remark']]);
  339. if ($result) {
  340. return Result::success('修改成功');
  341. } else {
  342. return Result::error('修改失败');
  343. }
  344. }
  345. /**
  346. * 会话列表
  347. * @param array $data
  348. * @return array
  349. */
  350. public function getConversation(array $data): array
  351. {
  352. $userId = $data['user_id'];
  353. $unreadMessages = ChatRecords::where('user_id', $userId)
  354. ->where('is_read', 0)
  355. // ->where('action', 'recieved')
  356. ->leftJoin('user', 'chat_records.receiver_id', '=', 'user.id')
  357. ->leftJoin('chat_groups', 'chat_records.receiver_id', '=', 'chat_groups.id')
  358. ->select(
  359. 'receiver_id',
  360. DB::raw('COUNT(receiver_id) AS num'),
  361. DB::raw('MAX(chat_records.id) AS max_id'),
  362. 'user.user_name as user_name',
  363. 'user.avatar as avatar',
  364. 'user.mobile as mobile',
  365. 'chat_groups.group_name as group_name'
  366. )
  367. ->groupBy('receiver_id')
  368. ->orderBy(DB::raw('MAX(chat_records.id)'), 'desc')
  369. ->get();
  370. // 查询已读消息,并将 num 字段设置为 0
  371. $readMessages = ChatRecords::where('user_id', $userId)
  372. ->where('is_read', 1)
  373. // ->where('action', 'recieved')
  374. ->leftJoin('user', 'chat_records.receiver_id', '=', 'user.id')
  375. ->leftJoin('chat_groups', 'chat_records.receiver_id', '=', 'chat_groups.id')
  376. ->select(
  377. 'receiver_id',
  378. DB::raw('0 AS num'),
  379. DB::raw('MAX(chat_records.id) AS max_id'),
  380. 'user.user_name as user_name',
  381. 'user.avatar as avatar',
  382. 'user.mobile as mobile',
  383. 'chat_groups.group_name as group_name'
  384. )
  385. ->groupBy('receiver_id')
  386. ->orderBy(DB::raw('MAX(chat_records.id)'), 'desc')
  387. ->get();
  388. // 合并未读消息和已读消息
  389. // $allMessages = array_merge($unreadMessages->toArray(), $readMessages->toArray());
  390. // 使用关联数组去重,并优先保留未读消息
  391. $allMessages = [];
  392. foreach ($unreadMessages as $message) {
  393. $allMessages[$message['receiver_id']] = $message->toArray();
  394. }
  395. foreach ($readMessages as $message) {
  396. if (strlen($message['receiver_id']) === 18) {
  397. } else {
  398. // $allMessages[$message['receiver_id']] = $message->toArray();
  399. }
  400. if (!isset($allMessages[$message['receiver_id']])) {
  401. $allMessages[$message['receiver_id']] = $message->toArray();
  402. }
  403. }
  404. // var_dump($allMessages);
  405. // 处理结果,判断是否是群聊
  406. $formattedMessages = [];
  407. foreach ($allMessages as $message) {
  408. $formattedMessage = [
  409. 'receiver_id' => $message['receiver_id'],
  410. 'num' => $message['num'],
  411. 'max_id' => $message['max_id'],
  412. 'user_name' => $message['user_name'],
  413. 'avatar' => $message['avatar'],
  414. 'mobile' => $message['mobile'],
  415. 'group_name' => $message['group_name'],
  416. ];
  417. if (strlen($message['receiver_id']) === 18) { // 判断是否是 UUID
  418. $formattedMessage['type'] = 'group';
  419. $formattedMessage['name'] = $message['group_name'];
  420. $formattedMessage['is_group'] = 1;
  421. } else {
  422. $formattedMessage['type'] = 'user';
  423. $formattedMessage['name'] = $message['user_name'];
  424. $formattedMessage['is_group'] = 0;
  425. }
  426. $formattedMessages[] = $formattedMessage;
  427. }
  428. if (!empty($formattedMessages)) {
  429. return Result::success($formattedMessages);
  430. } else {
  431. return Result::error('没有消息');
  432. }
  433. }
  434. /**
  435. * 获取聊天记录
  436. * @param array $data
  437. * @return array
  438. */
  439. public function getChatRecords(array $data): array
  440. {
  441. var_dump('222222');
  442. Db::beginTransaction();
  443. try {
  444. $userId = $data['user_id'];
  445. $friendId = $data['friend_id'];
  446. $result = ChatRecords::where(function ($query) use ($userId, $friendId) {
  447. $query->where('user_id', $userId)->where('receiver_id', $friendId);
  448. })
  449. // ->orWhere(function ($query) use ($userId, $friendId) {
  450. // $query->where('user_id', $friendId)->where('receiver_id', $userId);
  451. // })
  452. ->leftJoin('user as u1', 'chat_records.user_id', '=', 'u1.id')
  453. ->leftJoin('user as u2', 'chat_records.receiver_id', '=', 'u2.id')
  454. ->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')
  455. ->orderBy('id', 'asc')->paginate(100, ['*'], 'page', $data['page'] ?? 1);
  456. //更新聊天记录已读
  457. ChatRecords::where('user_id', $userId)
  458. ->where('receiver_id', $friendId)
  459. ->where('is_read', 0)
  460. ->where('talk_type', 1)
  461. ->update(['is_read' => 1]);
  462. Db::commit();
  463. } catch (\Throwable $ex) {
  464. Db::rollBack();
  465. var_dump($ex->getMessage());
  466. return Result::error("获取聊天记录失败", 0);
  467. }
  468. if ($result) {
  469. return Result::success($result);
  470. } else {
  471. return Result::error('没有聊天记录');
  472. }
  473. }
  474. /**
  475. * 获取群聊天记录
  476. * @param array $data
  477. * @return array
  478. */
  479. public function getGroupChatRecords(array $data): array
  480. {
  481. Db::beginTransaction();
  482. try {
  483. $userId = $data['user_id'];
  484. $group_id = $data['group_id'];
  485. $result = ChatRecords::where('receiver_id', $group_id)
  486. ->where('user_id', $userId)
  487. ->leftJoin('user as u1', 'chat_records.user_id', '=', 'u1.id')
  488. ->leftJoin('user as u2', 'chat_records.group_receiver_id', '=', 'u2.id')
  489. ->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')
  490. ->orderBy('id', 'asc')->paginate(100, ['*'], 'page', $data['page'] ?? 1);
  491. //更新群聊天记录
  492. ChatRecords::where('receiver_id', $group_id)
  493. ->where('user_id', $userId)
  494. ->update(['is_read' => 1]);
  495. Db::commit();
  496. } catch (\Throwable $ex) {
  497. Db::rollBack();
  498. var_dump($ex->getMessage());
  499. return Result::error("获取群聊天记录失败", 0);
  500. }
  501. if ($result) {
  502. return Result::success($result);
  503. } else {
  504. return Result::error('没有群消息');
  505. }
  506. }
  507. /**
  508. * 群组 - 创建群
  509. * @param array $data
  510. * @return array
  511. */
  512. public function addGroup(array $data): array
  513. {
  514. Db::beginTransaction();
  515. try {
  516. //创建群
  517. $groupData = [
  518. 'id' => PublicData::uuid(),
  519. 'creator_id' => $data['user_id'],
  520. 'group_name' => $data['group_name'],
  521. 'avatar' => $data['avatar'] ?? '',
  522. 'profile' => $data['profile'] ?? '',
  523. ];
  524. ChatGroups::insert($groupData);
  525. //创建群用户
  526. $groupMemberData = [];
  527. $groupChatData = [];
  528. if ($data['group_member']) {
  529. foreach ($data['group_member'] as $key => $val) {
  530. $groupMemberData[$key] = [
  531. 'id' => PublicData::uuid(),
  532. 'group_id' => $groupData['id'],
  533. 'user_id' => $val,
  534. 'leader' => $data['user_id'] == $val ? 2 : 0,
  535. ];
  536. $groupChatData[$key] = [
  537. 'user_id' => $val,
  538. 'receiver_id' => $groupData['id'],
  539. 'content' => '创建群' . Date('Y-m-d H:i:s'),
  540. 'msg_type' => 1,
  541. 'is_read' => 0,
  542. 'talk_type' => 2,
  543. 'action' => 'recieved',
  544. 'group_receiver_id' => $data['user_id'],
  545. ];
  546. }
  547. }
  548. ChatGroupsMember::insert($groupMemberData);
  549. //插入一条消息
  550. ChatRecords::insert($groupChatData);
  551. Db::commit();
  552. } catch (\Throwable $ex) {
  553. Db::rollBack();
  554. var_dump($ex->getMessage());
  555. return Result::error("创建群失败", 0);
  556. }
  557. return Result::success([]);
  558. }
  559. /**
  560. * 群组 - 加入群
  561. * @param array $data
  562. * @return array
  563. */
  564. public function addGroupMember(array $data): array
  565. {
  566. $result = ChatGroupsMember::where(['group_id' => $data['group_id'], 'user_id' => $data['user_id']])->update(['leader' => 2]);
  567. $groupChatData = [
  568. 'user_id' => $data['user_id'],
  569. 'receiver_id' => $data['group_id'],
  570. 'content' => '加入群' . Date('Y-m-d H:i:s'),
  571. 'msg_type' => 1,
  572. 'is_read' => 0,
  573. 'talk_type' => 2,
  574. 'action' => 'recieved',
  575. 'group_receiver_id' => $data['user_id'],
  576. ];
  577. ChatRecords::insert($groupChatData);
  578. if ($result) {
  579. return Result::success('修改成功');
  580. } else {
  581. return Result::error('修改失败');
  582. }
  583. }
  584. /**
  585. * 群组 - 群信息
  586. * @param array $data
  587. * @return array
  588. */
  589. public function getGroupInfo(array $data): array
  590. {
  591. $result = ChatGroups::where(['chat_groups.id' => $data['group_id']])
  592. ->join('user', 'chat_groups.creator_id', '=', 'user.id')
  593. ->select('chat_groups.*', 'user.user_name as user_name', 'user.avatar as avatar')
  594. ->first();
  595. return Result::success($result);
  596. }
  597. /**
  598. * 群组 - 删除群
  599. * @param array $data
  600. * @return array
  601. */
  602. public function delGroup(array $data): array
  603. {
  604. Db::beginTransaction();
  605. try {
  606. $groupMember = ChatGroupsMember::where(['group_id' => $data['group_id']])->delete();
  607. $result = ChatGroups::where(['id' => $data['group_id']])->delete();
  608. $result = ChatRecords::where(['receiver_id' => $data['group_id']])->delete();
  609. //群聊记录
  610. Db::commit();
  611. } catch (\Throwable $ex) {
  612. Db::rollBack();
  613. var_dump($ex->getMessage());
  614. return Result::error("删除群失败", 0);
  615. }
  616. if ($result) {
  617. return Result::success('删除成功');
  618. } else {
  619. return Result::error('删除失败');
  620. }
  621. }
  622. /**
  623. * 群组 - 退出群
  624. * @param array $data
  625. * @return array
  626. */
  627. public function quitGroup(array $data): array
  628. {
  629. $result = ChatGroupsMember::where(['group_id' => $data['group_id'], 'user_id' => $data['user_id']])->delete();
  630. ChatRecords::where(['receiver_id' => $data['group_id'], 'user_id' => $data['user_id']])->delete();
  631. if ($result) {
  632. return Result::success('退出成功');
  633. } else {
  634. return Result::error('退出失败');
  635. }
  636. }
  637. /**
  638. * 群组 - 我的群
  639. * @param array $data
  640. * @return array
  641. */
  642. public function getGroupList(array $data): array
  643. {
  644. $result = ChatGroupsMember::where(['user_id' => $data['user_id']])
  645. ->leftJoin('chat_groups', 'chat_groups_members.group_id', '=', 'chat_groups.id')
  646. ->select('chat_groups.*', 'chat_groups_members.group_id as group_id')
  647. ->orderBy('chat_groups.id', 'desc')
  648. ->paginate(100, ['*'], 'page', $data['page'] ?? 1);
  649. return Result::success($result);
  650. }
  651. /**
  652. * 群组 - 删除群成员
  653. * @param array $data
  654. * @return array
  655. */
  656. public function delGroupMembers(array $data): array
  657. {
  658. $result = ChatGroupsMember::where(['group_id' => $data['group_id'], 'user_id' => $data['user_id']])->delete();
  659. ChatRecords::where(['receiver_id' => $data['group_id'], 'user_id' => $data['user_id']])->delete();
  660. if ($result) {
  661. return Result::success('删除成功');
  662. } else {
  663. return Result::error('删除失败');
  664. }
  665. }
  666. /**
  667. * 群组 - 更新群
  668. * @param array $data
  669. * @return array
  670. */
  671. public function updateGroup(array $data): array
  672. {
  673. // 提取需要的字段
  674. $groupId = $data['group_id'];
  675. $groupName = $data['group_name'] ?? null;
  676. $profile = $data['profile'] ?? null;
  677. $avatar = $data['avatar'] ?? null;
  678. // 查询群组
  679. $group = ChatGroups::find($groupId);
  680. if (!$group) {
  681. return Result::error('群组不存在');
  682. }
  683. // 更新群组信息
  684. if ($groupName !== null) {
  685. $group->group_name = $groupName;
  686. }
  687. if ($profile !== null) {
  688. $group->profile = $profile;
  689. }
  690. if ($avatar !== null) {
  691. $group->avatar = $avatar;
  692. }
  693. // 保存更改
  694. if ($group->save()) {
  695. return Result::success($group->toArray());
  696. } else {
  697. return Result::error('更新群组信息失败');
  698. }
  699. }
  700. /**
  701. * 群组 - 删除群
  702. * @param array $data
  703. * @return array
  704. */
  705. public function deleteGroup(array $data): array
  706. {
  707. $result = ChatGroups::where(['id' => $data['group_id']])->delete();
  708. if ($result) {
  709. return Result::success('删除成功');
  710. } else {
  711. return Result::error('删除失败');
  712. }
  713. }
  714. /**
  715. * 群组 - 群用户列表
  716. * @param array $data
  717. * @return array
  718. */
  719. public function getGroupMembers(array $data): array
  720. {
  721. $groupMember = ChatGroupsMember::where(['group_id' => $data['group_id']])
  722. ->leftJoin('user as u1', 'chat_groups_members.user_id', '=', 'u1.id')
  723. ->select('chat_groups_members.*', 'u1.user_name', 'u1.avatar')
  724. ->orderBy('id', 'desc')
  725. ->get();
  726. return Result::success($groupMember);
  727. }
  728. /**
  729. * 群组 - 添加群
  730. * @param array $data
  731. * @return array
  732. */
  733. public function joinGroup(array $data): array
  734. {
  735. $group = ChatGroups::where(['id' => $data['group_id']])->first();
  736. if (empty($group)) {
  737. return Result::error("群不存在", 0);
  738. }
  739. $groupMember = ChatGroupsMember::where(['user_id' => $data['user_id'], 'group_id' => $data['group_id']])->first();
  740. if ($groupMember) {
  741. return Result::error("已加入群", 0);
  742. }
  743. $info = [
  744. 'id' => PublicData::uuid(),
  745. 'user_id' => $data['user_id'],
  746. 'group_id' => $data['group_id'],
  747. ];
  748. $result = ChatGroupsMember::insert($info);
  749. var_dump($result, '--------------------');
  750. if ($result) {
  751. return Result::success($data);
  752. } else {
  753. return Result::error($data);
  754. };
  755. }
  756. /**
  757. * 话题 - 列表
  758. * @param array $data
  759. * @return array
  760. */
  761. public function getTopicsList(array $data): array
  762. {
  763. $where = [];
  764. if (!empty($data['title'])) {
  765. $where[] = ['chat_topics.title', 'like', '%' . $data['title'] . '%'];
  766. }
  767. // 不是看自己的话题
  768. if (!empty($data['user_id_search'])) {
  769. $where[] = ['chat_topics.user_id', '=', $data['user_id_search']];
  770. }
  771. if (!empty($data['status'])) {
  772. $where[] = ['chat_topics.status', '=', $data['status']];
  773. }
  774. if (!empty($data['type'])) {
  775. $where[] = ['chat_topics.type', '=', $data['type']];
  776. }
  777. if (!empty($data['nickname'])) {
  778. $where[] = ['user.nickname', '=', $data['nickname']];
  779. }
  780. var_dump($where);
  781. $result = ChatTopic::where($where)
  782. ->leftJoin('user', 'user.id', '=', 'chat_topics.user_id')
  783. ->leftJoin('chat_topics_reply', 'chat_topics.id', '=', 'chat_topics_reply.topic_id')
  784. ->select(
  785. 'chat_topics.*',
  786. 'user.nickname',
  787. 'user.avatar',
  788. 'user.user_name',
  789. DB::raw('count(chat_topics_reply.id) as num')
  790. )
  791. ->groupBy('chat_topics.id')
  792. ->orderBy('chat_topics.id', 'desc')
  793. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  794. return Result::success($result);
  795. }
  796. public function getTopic(array $data): array
  797. {
  798. $result = ChatTopic::where(['id' => $data['id']])->first();
  799. return Result::success($result);
  800. }
  801. public function addTopic(array $data): array
  802. {
  803. $chattopic = [];
  804. Db::beginTransaction();
  805. try {
  806. $data['created_at'] = date('Y-m-d H:i:s');
  807. $data['updated_at'] = date('Y-m-d H:i:s');
  808. $result = ChatTopic::insertGetId($data);
  809. var_dump($result, 'tedst111111111111111111111111111111');
  810. if ($result && $data['is_group'] == 1) {
  811. //chat_group
  812. $group_id = PublicData::uuid();
  813. $groupData = [
  814. 'id' => $group_id,
  815. 'creator_id' => $data['user_id'],
  816. 'group_name' => $data['group_name'] ?? '',
  817. 'profile' => $data['profile'] ?? 0,
  818. ];
  819. $groupResult = ChatGroups::insertGetId($groupData);
  820. $groupMemberData = [
  821. 'id' => PublicData::uuid(),
  822. 'user_id' => $data['user_id'],
  823. 'group_id' => $group_id,
  824. 'leader' => 2,
  825. ];
  826. $groupMemberResult = ChatGroupsMember::insertGetId($groupMemberData);
  827. //更新result的 group_id
  828. $data['group_id'] = $group_id;
  829. ChatTopic::where(['id' => $result])->update($data);
  830. // 查询 Chattopic 数据
  831. $chattopic = Chattopic::find($result);
  832. } else {
  833. $chattopic = Chattopic::find($result);
  834. }
  835. Db::commit();
  836. } catch (\Exception $e) {
  837. Db::rollBack();
  838. return Result::error($data, $e->getMessage());
  839. }
  840. return Result::success($chattopic);
  841. }
  842. public function applyTopic(array $data): array
  843. {
  844. date_default_timezone_set('Asia/Shanghai');
  845. db::beginTransaction();
  846. try {
  847. $query = ChatTopic::where(['id' => $data['id']]);
  848. $topdata = $query->first();
  849. $result = ChatTopic::where(['id' => $data['id']])->update(['status' => $data['status']]);
  850. var_dump($result, 'tedst111111111111111');
  851. var_dump(date('Y-m-d H:i:s'), 'tedst111111111111111');
  852. $creatter = $topdata['user_id'];
  853. if ($data['status'] == 2) {
  854. //插入一条消息
  855. $chatRecordsData = [
  856. 'user_id' => $topdata['user_id'],
  857. 'receiver_id' => $topdata['group_id'],
  858. 'content' => '我创建了一个群' . Date('Y-m-d H:i:s'),
  859. 'msg_type' => 1,
  860. 'is_read' => 0,
  861. 'talk_type' => 2,
  862. 'action' => 'said',
  863. 'group_receiver_id' => $topdata['user_id'],
  864. ];
  865. ChatRecords::insert($chatRecordsData);
  866. } elseif ($data['status'] == 3) {
  867. ChatRecords::where('receiver_id', $topdata['group_id'])->delete();
  868. ChatGroupsMember::where('group_id', $topdata['group_id'])
  869. ->where([["user_id", '!=', $creatter]])->delete();
  870. }
  871. Db::commit();
  872. if ($result) {
  873. return Result::success($data);
  874. } else {
  875. return Result::error($data);
  876. }
  877. } catch (\Exception $e) {
  878. Db::rollBack();
  879. return Result::error($data, $e->getMessage());
  880. }
  881. if (empty($data['id'])) {
  882. return Result::error('id不能为空');
  883. }
  884. }
  885. public function updateTopic(array $data): array
  886. {
  887. if (empty($data['id'])) {
  888. return Result::error('id不能为空');
  889. }
  890. $result = ChatTopic::where(['id' => $data['id']])->update($data);
  891. if ($result) {
  892. return Result::success($data);
  893. } else {
  894. return Result::error($data);
  895. };
  896. }
  897. public function delTopic(array $data): array
  898. {
  899. $result = ChatTopic::where(['id' => $data['id']])->delete();
  900. //删除群和成员和聊天
  901. //删除话题回复
  902. if ($result) {
  903. return Result::success($data);
  904. } else {
  905. return Result::error('删除失败');
  906. };
  907. }
  908. public function getTopicInfo(array $data): array
  909. {
  910. $result = ChatTopic::where(['chat_topics.id' => $data['id']])
  911. ->leftJoin('user', 'user.id', '=', 'chat_topics.user_id')
  912. ->select('chat_topics.*', 'user.nickname', 'user.avatar', 'user.user_name')
  913. ->first();
  914. return Result::success($result);
  915. }
  916. public function addReply(array $data): array
  917. {
  918. $result = ChatTopic::where(['id' => $data['id']])->get();
  919. if ($result) {
  920. $replydata['created_at'] = date('Y-m-d H:i:s');
  921. $replydata['updated_at'] = date('Y-m-d H:i:s');
  922. $replydata['content'] = $data['content'];
  923. $replydata['user_id'] = $data['user_id'];
  924. $replydata['topic_id'] = $data['id'];
  925. $re = ChatTopicsReply::insertGetId($replydata);
  926. }
  927. if ($re) {
  928. return Result::success($data);
  929. } else {
  930. return Result::error($data);
  931. }
  932. }
  933. public function getTopicReply(array $data): array
  934. {
  935. var_dump($data);
  936. $result = ChatTopicsReply::where(['topic_id' => $data['id']])
  937. ->leftJoin('user', 'user.id', '=', 'chat_topics_reply.user_id')
  938. ->select('chat_topics_reply.*', 'user.nickname', 'user.avatar', 'user.user_name')
  939. ->orderBy('chat_topics_reply.id', 'desc')
  940. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  941. return Result::success($result);
  942. }
  943. /**
  944. * 修改群成员
  945. * @param array $data
  946. * @return array
  947. */
  948. public function updateGroupMembers(array $data): array
  949. {
  950. $where = [
  951. 'group_id' => $data['group_id'],
  952. ];
  953. $group_id = $data['group_id'];
  954. //先删除群成员
  955. $result = ChatGroupsMember::where($where)
  956. ->where([["user_id", '!=', $data['user_id']]])->delete();
  957. $groupMemberData = [];
  958. foreach ($data['group_member'] as $value) {
  959. $groupMemberData[] = [
  960. 'id' => PublicData::uuid(),
  961. 'user_id' => $value,
  962. 'group_id' => $group_id,
  963. 'leader' => 0,
  964. ];
  965. }
  966. $result = ChatGroupsMember::where($where)->insert($groupMemberData);
  967. // 获取群信息
  968. $groupInfo = ChatGroups::where(['id' => $group_id])->first();
  969. if ($result) {
  970. return Result::success($groupInfo);
  971. } else {
  972. return Result::error($data);
  973. }
  974. }
  975. public function clearGroupRecords(array $data): array
  976. {
  977. $result = ChatRecords::where(['user_id' => $data['user_id'], 'receiver_id' => $data['id']])->delete();
  978. if ($result) {
  979. return Result::success("删除成功");
  980. } else {
  981. return Result::error("删除失败");
  982. }
  983. }
  984. public function recallRecord(array $data): array
  985. {
  986. //获取所有id,并删除掉
  987. $ids = array_column($data, 'id');
  988. $result = ChatRecords::whereIn('id', $ids)->delete();
  989. if ($result) {
  990. return Result::success("删除成功");
  991. } else {
  992. return Result::error("删除失败");
  993. }
  994. }
  995. public function clearRecords(array $data): array
  996. {
  997. $result = ChatRecords::where(['user_id' => $data['user_id'], 'receiver_id' => $data['friend_id']])->delete();
  998. if ($result) {
  999. return Result::success("删除成功");
  1000. } else {
  1001. return Result::error("删除失败");
  1002. }
  1003. }
  1004. public function getRecordByContent(array $data): array
  1005. {
  1006. $result = ChatRecords::where(['chat_records.user_id' => $data['user_id'], 'chat_records.receiver_id' => $data['receiver_id'], 'chat_records.content' => $data['content']])
  1007. ->orWhere(['chat_records.receiver_id' => $data['user_id'], 'chat_records.user_id' => $data['receiver_id'], 'chat_records.content' => $data['content']])
  1008. ->all();
  1009. if ($result) {
  1010. return Result::success($result['id']);
  1011. } else {
  1012. return Result::error("没有数据");
  1013. }
  1014. }
  1015. public function getRecord(array $data): array
  1016. {
  1017. $result = ChatRecords::where(['chat_records.id' => $data['id']])
  1018. ->leftJoin('user', 'user.id', '=', 'chat_records.user_id')
  1019. ->leftJoin('user as user2', 'user2.id', '=', 'chat_records.receiver_id')
  1020. ->select('chat_records.*', 'user.nickname', 'user.avatar', 'user.user_name', 'user2.nickname as receiver_nickname', 'user2.avatar as receiver_avatar')
  1021. ->get();
  1022. return Result::success($result);
  1023. }
  1024. public function delReply(array $data): array
  1025. {
  1026. $result = ChatTopicsReply::where(['id' => $data['id']])->delete();
  1027. if ($result) {
  1028. return Result::success("删除成功");
  1029. } else {
  1030. return Result::error("删除失败");
  1031. }
  1032. }
  1033. public function delAllReply(array $data): array
  1034. {
  1035. $result = ChatTopicsReply::where(['topic_id' => $data['topicid']])->delete();
  1036. if ($result) {
  1037. return Result::success("删除成功");
  1038. } else {
  1039. return Result::error("删除失败");
  1040. }
  1041. }
  1042. public function getTopicsListAdmin(array $data): array
  1043. {
  1044. $where = [];
  1045. if (!empty($data['type'])) {
  1046. $where['type'] = $data['type'];
  1047. }
  1048. if (!empty($data['title'])) {
  1049. $where['title'] = $data['title'];
  1050. }
  1051. $result = ChatTopic::where($where)
  1052. ->leftJoin('user', 'user.id', '=', 'chat_topics.user_id')
  1053. ->select('chat_topics.*', 'user.nickname', 'user.avatar', 'user.user_name')
  1054. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  1055. return Result::success($result);
  1056. }
  1057. public function getTopicClassList(array $data): array
  1058. {
  1059. $where = [];
  1060. if (!empty($data['topicname'])) {
  1061. $where[] = ['topicname', 'like', '%' . $data['topicname'] . '%'];
  1062. }
  1063. $result = ChatTopicClass::where($where)->orderBy('updated_at', 'desc')
  1064. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  1065. return Result::success($result);
  1066. }
  1067. public function deleteTopicClass(array $data): array
  1068. {
  1069. $result = ChatTopicClass::where(['id' => $data['id']])->delete();
  1070. if ($result) {
  1071. return Result::success("删除成功");
  1072. }
  1073. return Result::error("删除失败");
  1074. }
  1075. public function updateTopicClass(array $data): array
  1076. {
  1077. //topicname
  1078. if (!empty($data['topicname'])) {
  1079. $re = ChatTopicClass::where(['topicname' => $data['topicname']])->first();
  1080. if ($re) {
  1081. return Result::error("话题分类已存在");
  1082. }
  1083. }
  1084. $result = ChatTopicClass::where(['id' => $data['id']])->update([
  1085. 'topicname' => $data['topicname'],
  1086. 'updated_at' => date('Y-m-d H:i:s'),
  1087. ]);
  1088. if ($result) {
  1089. return Result::success("修改成功");
  1090. }
  1091. return Result::error("修改失败");
  1092. }
  1093. public function addTopicClass(array $data): array
  1094. {
  1095. //topicname
  1096. if (!empty($data['topicname'])) {
  1097. $re = ChatTopicClass::where(['topicname' => $data['topicname']])->first();
  1098. if ($re) {
  1099. return Result::error("话题分类已存在");
  1100. }
  1101. }
  1102. $result = ChatTopicClass::insert($data);
  1103. if ($result) {
  1104. return Result::success("添加成功");
  1105. }
  1106. return Result::error("添加失败");
  1107. }
  1108. /**
  1109. * 获取话题分类信息
  1110. * @param array $data
  1111. * @return array
  1112. */
  1113. public function getTopicClassInfo(array $data): array
  1114. {
  1115. $result = ChatTopicClass::where(['id' => $data['id']])->first();
  1116. return Result::success($result);
  1117. }
  1118. }