ChatService.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  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)->orderBy('updated_at', 'desc')
  1058. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  1059. return Result::success($result);
  1060. }
  1061. public function deleteTopicClass(array $data): array
  1062. {
  1063. $result = ChatTopicClass::where(['id' => $data['id']])->delete();
  1064. if ($result) {
  1065. return Result::success("删除成功");
  1066. }
  1067. return Result::error("删除失败");
  1068. }
  1069. public function updateTopicClass(array $data): array
  1070. {
  1071. //topicname
  1072. if (!empty($data['topicname'])) {
  1073. $re = ChatTopicClass::where(['topicname' => $data['topicname']])->first();
  1074. if ($re) {
  1075. return Result::error("话题分类已存在");
  1076. }
  1077. }
  1078. $result = ChatTopicClass::where(['id' => $data['id']])->update([
  1079. 'topicname' => $data['topicname'],
  1080. 'updated_at' => date('Y-m-d H:i:s'),
  1081. ]);
  1082. if ($result) {
  1083. return Result::success("修改成功");
  1084. }
  1085. return Result::error("修改失败");
  1086. }
  1087. public function addTopicClass(array $data): array
  1088. {
  1089. //topicname
  1090. if (!empty($data['topicname'])) {
  1091. $re = ChatTopicClass::where(['topicname' => $data['topicname']])->first();
  1092. if ($re) {
  1093. return Result::error("话题分类已存在");
  1094. }
  1095. }
  1096. $result = ChatTopicClass::insert($data);
  1097. if ($result) {
  1098. return Result::success("添加成功");
  1099. }
  1100. return Result::error("添加失败");
  1101. }
  1102. /**
  1103. * 获取话题分类信息
  1104. * @param array $data
  1105. * @return array
  1106. */
  1107. public function getTopicClassInfo(array $data): array
  1108. {
  1109. $result = ChatTopicClass::where(['id' => $data['id']])->first();
  1110. return Result::success($result);
  1111. }
  1112. }