ChatService.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  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. ->leftJoin('chat_topic_class', 'chat_topic_class.id', '=', 'chat_topics.type')
  913. ->select('chat_topics.*', 'user.nickname', 'user.avatar', 'user.user_name','chat_topic_class.topicname')
  914. ->first();
  915. return Result::success($result);
  916. }
  917. public function addReply(array $data): array
  918. {
  919. $result = ChatTopic::where(['id' => $data['id']])->get();
  920. if ($result) {
  921. $replydata['created_at'] = date('Y-m-d H:i:s');
  922. $replydata['updated_at'] = date('Y-m-d H:i:s');
  923. $replydata['content'] = $data['content'];
  924. $replydata['user_id'] = $data['user_id'];
  925. $replydata['topic_id'] = $data['id'];
  926. $re = ChatTopicsReply::insertGetId($replydata);
  927. }
  928. if ($re) {
  929. return Result::success($data);
  930. } else {
  931. return Result::error($data);
  932. }
  933. }
  934. public function getTopicReply(array $data): array
  935. {
  936. var_dump($data);
  937. $result = ChatTopicsReply::where(['topic_id' => $data['id']])
  938. ->leftJoin('user', 'user.id', '=', 'chat_topics_reply.user_id')
  939. ->select('chat_topics_reply.*', 'user.nickname', 'user.avatar', 'user.user_name')
  940. ->orderBy('chat_topics_reply.id', 'desc')
  941. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  942. return Result::success($result);
  943. }
  944. /**
  945. * 修改群成员
  946. * @param array $data
  947. * @return array
  948. */
  949. public function updateGroupMembers(array $data): array
  950. {
  951. $where = [
  952. 'group_id' => $data['group_id'],
  953. ];
  954. $group_id = $data['group_id'];
  955. //先删除群成员
  956. $result = ChatGroupsMember::where($where)
  957. ->where([["user_id", '!=', $data['user_id']]])->delete();
  958. $groupMemberData = [];
  959. foreach ($data['group_member'] as $value) {
  960. $groupMemberData[] = [
  961. 'id' => PublicData::uuid(),
  962. 'user_id' => $value,
  963. 'group_id' => $group_id,
  964. 'leader' => 0,
  965. ];
  966. }
  967. $result = ChatGroupsMember::where($where)->insert($groupMemberData);
  968. // 获取群信息
  969. $groupInfo = ChatGroups::where(['id' => $group_id])->first();
  970. if ($result) {
  971. return Result::success($groupInfo);
  972. } else {
  973. return Result::error($data);
  974. }
  975. }
  976. public function clearGroupRecords(array $data): array
  977. {
  978. $result = ChatRecords::where(['user_id' => $data['user_id'], 'receiver_id' => $data['id']])->delete();
  979. if ($result) {
  980. return Result::success("删除成功");
  981. } else {
  982. return Result::error("删除失败");
  983. }
  984. }
  985. public function recallRecord(array $data): array
  986. {
  987. //获取所有id,并删除掉
  988. $ids = array_column($data, 'id');
  989. $result = ChatRecords::whereIn('id', $ids)->delete();
  990. if ($result) {
  991. return Result::success("删除成功");
  992. } else {
  993. return Result::error("删除失败");
  994. }
  995. }
  996. public function clearRecords(array $data): array
  997. {
  998. $result = ChatRecords::where(['user_id' => $data['user_id'], 'receiver_id' => $data['friend_id']])->delete();
  999. if ($result) {
  1000. return Result::success("删除成功");
  1001. } else {
  1002. return Result::error("删除失败");
  1003. }
  1004. }
  1005. public function getRecordByContent(array $data): array
  1006. {
  1007. $result = ChatRecords::where(['chat_records.user_id' => $data['user_id'], 'chat_records.receiver_id' => $data['receiver_id'], 'chat_records.content' => $data['content']])
  1008. ->orWhere(['chat_records.receiver_id' => $data['user_id'], 'chat_records.user_id' => $data['receiver_id'], 'chat_records.content' => $data['content']])
  1009. ->all();
  1010. if ($result) {
  1011. return Result::success($result['id']);
  1012. } else {
  1013. return Result::error("没有数据");
  1014. }
  1015. }
  1016. public function getRecord(array $data): array
  1017. {
  1018. $result = ChatRecords::where(['chat_records.id' => $data['id']])
  1019. ->leftJoin('user', 'user.id', '=', 'chat_records.user_id')
  1020. ->leftJoin('user as user2', 'user2.id', '=', 'chat_records.receiver_id')
  1021. ->select('chat_records.*', 'user.nickname', 'user.avatar', 'user.user_name', 'user2.nickname as receiver_nickname', 'user2.avatar as receiver_avatar')
  1022. ->get();
  1023. return Result::success($result);
  1024. }
  1025. public function delReply(array $data): array
  1026. {
  1027. $result = ChatTopicsReply::where(['id' => $data['id']])->delete();
  1028. if ($result) {
  1029. return Result::success("删除成功");
  1030. } else {
  1031. return Result::error("删除失败");
  1032. }
  1033. }
  1034. public function delAllReply(array $data): array
  1035. {
  1036. $result = ChatTopicsReply::where(['topic_id' => $data['topicid']])->delete();
  1037. if ($result) {
  1038. return Result::success("删除成功");
  1039. } else {
  1040. return Result::error("删除失败");
  1041. }
  1042. }
  1043. public function getTopicsListAdmin(array $data): array
  1044. {
  1045. $where = [];
  1046. if (!empty($data['type'])) {
  1047. $where['type'] = $data['type'];
  1048. }
  1049. if (!empty($data['title'])) {
  1050. $where['title'] = $data['title'];
  1051. }
  1052. $result = ChatTopic::where($where)
  1053. ->leftJoin('user', 'user.id', '=', 'chat_topics.user_id')
  1054. ->select('chat_topics.*', 'user.nickname', 'user.avatar', 'user.user_name')
  1055. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  1056. return Result::success($result);
  1057. }
  1058. public function getTopicClassList(array $data): array
  1059. {
  1060. $where = [];
  1061. if (!empty($data['topicname'])) {
  1062. $where[] = ['topicname', 'like', '%' . $data['topicname'] . '%'];
  1063. }
  1064. $result = ChatTopicClass::where($where)->orderBy('updated_at', 'desc')
  1065. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  1066. return Result::success($result);
  1067. }
  1068. public function deleteTopicClass(array $data): array
  1069. {
  1070. $result = ChatTopicClass::where(['id' => $data['id']])->delete();
  1071. if ($result) {
  1072. return Result::success("删除成功");
  1073. }
  1074. return Result::error("删除失败");
  1075. }
  1076. public function updateTopicClass(array $data): array
  1077. {
  1078. //topicname
  1079. if (!empty($data['topicname'])) {
  1080. $re = ChatTopicClass::where(['topicname' => $data['topicname']])->first();
  1081. if ($re) {
  1082. return Result::error("话题分类已存在");
  1083. }
  1084. }
  1085. $result = ChatTopicClass::where(['id' => $data['id']])->update([
  1086. 'topicname' => $data['topicname'],
  1087. 'updated_at' => date('Y-m-d H:i:s'),
  1088. ]);
  1089. if ($result) {
  1090. return Result::success("修改成功");
  1091. }
  1092. return Result::error("修改失败");
  1093. }
  1094. public function addTopicClass(array $data): array
  1095. {
  1096. //topicname
  1097. if (!empty($data['topicname'])) {
  1098. $re = ChatTopicClass::where(['topicname' => $data['topicname']])->first();
  1099. if ($re) {
  1100. return Result::error("话题分类已存在");
  1101. }
  1102. }
  1103. $result = ChatTopicClass::insert($data);
  1104. if ($result) {
  1105. return Result::success("添加成功");
  1106. }
  1107. return Result::error("添加失败");
  1108. }
  1109. /**
  1110. * 获取话题分类信息
  1111. * @param array $data
  1112. * @return array
  1113. */
  1114. public function getTopicClassInfo(array $data): array
  1115. {
  1116. $result = ChatTopicClass::where(['id' => $data['id']])->first();
  1117. return Result::success($result);
  1118. }
  1119. /**
  1120. * @param array $data
  1121. * @return array
  1122. */
  1123. public function getBusinessDistrictList(array $data): array
  1124. {
  1125. $query = ChatGroupsMember::Join('chat_topics', 'chat_topics.group_id', '=', 'chat_groups_members.group_id')
  1126. ->leftJoin('chat_topic_class', 'chat_topic_class.id', '=', 'chat_topics.type')
  1127. ->where(['chat_groups_members.user_id' => $data['user_id']])
  1128. ->when($data, function ($query) use ($data) {
  1129. if(!empty($data['type'])){
  1130. $query->where(['chat_topics.type' => $data['type']]);
  1131. }
  1132. if(!empty($data['title'])){
  1133. $query->where('chat_topics.title','like','%'.$data['title'].'%');
  1134. }
  1135. if(!empty($data['created_at'])){
  1136. $query->whereDate('chat_topics.created_at', $data['created_at']);
  1137. }
  1138. })
  1139. ->select(
  1140. 'chat_topics.id',
  1141. 'chat_topics.title',
  1142. 'chat_topics.author',
  1143. 'chat_topics.created_at',
  1144. 'chat_topics.updated_at',
  1145. 'chat_topic_class.topicname',
  1146. )
  1147. ->orderBy('chat_topics.created_at', 'desc');
  1148. $total = $query->count();
  1149. $list = $query->forPage($data['page'], $data['page_size'])->get();
  1150. $result = [
  1151. 'list' => $list,
  1152. 'total' => $total,
  1153. 'page' => intval($data['page']),
  1154. 'page_size' => intval($data['page_size']),
  1155. ];
  1156. return Result::success($result);
  1157. }
  1158. }