ChatService.php 40 KB

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