ChatService.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  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. ->leftJoin('chat_groups as c1', 'c1.id', '=', 'chat_groups_members.group_id')
  724. ->select('chat_groups_members.*', 'u1.user_name', 'u1.avatar', 'c1.group_name as group_name')
  725. ->orderBy('id', 'desc')
  726. ->get();
  727. return Result::success($groupMember);
  728. }
  729. /**
  730. * 群组 - 添加群
  731. * @param array $data
  732. * @return array
  733. */
  734. public function joinGroup(array $data): array
  735. {
  736. $group = ChatGroups::where(['id' => $data['group_id']])->first();
  737. if (empty($group)) {
  738. return Result::error("群不存在", 0);
  739. }
  740. $groupMember = ChatGroupsMember::where(['user_id' => $data['user_id'], 'group_id' => $data['group_id']])->first();
  741. if ($groupMember) {
  742. return Result::error("已加入群", 0);
  743. }
  744. $info = [
  745. 'id' => PublicData::uuid(),
  746. 'user_id' => $data['user_id'],
  747. 'group_id' => $data['group_id'],
  748. ];
  749. $result = ChatGroupsMember::insert($info);
  750. var_dump($result, '--------------------');
  751. if ($result) {
  752. return Result::success($data);
  753. } else {
  754. return Result::error($data);
  755. };
  756. }
  757. /**
  758. * 话题 - 列表
  759. * @param array $data
  760. * @return array
  761. */
  762. public function getTopicsList(array $data): array
  763. {
  764. $where = [];
  765. if (!empty($data['title'])) {
  766. $where[] = ['chat_topics.title', 'like', '%' . $data['title'] . '%'];
  767. }
  768. // 不是看自己的话题
  769. if (!empty($data['user_id_search'])) {
  770. $where[] = ['chat_topics.user_id', '=', $data['user_id_search']];
  771. }
  772. if (!empty($data['status'])) {
  773. $where[] = ['chat_topics.status', '=', $data['status']];
  774. }
  775. if (!empty($data['type'])) {
  776. $where[] = ['chat_topics.type', '=', $data['type']];
  777. }
  778. if (!empty($data['nickname'])) {
  779. $where[] = ['user.nickname', '=', $data['nickname']];
  780. }
  781. var_dump($where);
  782. $result = ChatTopic::where($where)
  783. ->leftJoin('user', 'user.id', '=', 'chat_topics.user_id')
  784. ->leftJoin('chat_topics_reply', 'chat_topics.id', '=', 'chat_topics_reply.topic_id')
  785. ->leftJoin('chat_topic_class', 'chat_topics.type', '=', 'chat_topic_class.id')
  786. ->select(
  787. 'chat_topics.*',
  788. 'chat_topic_class.topicname as type_name',
  789. 'user.nickname',
  790. 'user.avatar',
  791. 'user.user_name',
  792. DB::raw('count(chat_topics_reply.id) as num')
  793. )
  794. ->groupBy('chat_topics.id')
  795. ->orderBy('chat_topics.id', 'desc')
  796. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  797. return Result::success($result);
  798. }
  799. public function getTopic(array $data): array
  800. {
  801. $result = ChatTopic::where(['id' => $data['id']])->first();
  802. return Result::success($result);
  803. }
  804. public function addTopic(array $data): array
  805. {
  806. $chattopic = [];
  807. Db::beginTransaction();
  808. try {
  809. $data['created_at'] = date('Y-m-d H:i:s');
  810. $data['updated_at'] = date('Y-m-d H:i:s');
  811. $result = ChatTopic::insertGetId($data);
  812. var_dump($result, 'tedst111111111111111111111111111111');
  813. if ($result && $data['is_group'] == 1) {
  814. //chat_group
  815. $group_id = PublicData::uuid();
  816. $groupData = [
  817. 'id' => $group_id,
  818. 'creator_id' => $data['user_id'],
  819. 'group_name' => $data['group_name'] ?? '',
  820. 'profile' => $data['profile'] ?? 0,
  821. ];
  822. $groupResult = ChatGroups::insertGetId($groupData);
  823. $groupMemberData = [
  824. 'id' => PublicData::uuid(),
  825. 'user_id' => $data['user_id'],
  826. 'group_id' => $group_id,
  827. 'leader' => 2,
  828. ];
  829. $groupMemberResult = ChatGroupsMember::insertGetId($groupMemberData);
  830. //更新result的 group_id
  831. $data['group_id'] = $group_id;
  832. ChatTopic::where(['id' => $result])->update($data);
  833. // 查询 Chattopic 数据
  834. $chattopic = Chattopic::find($result);
  835. } else {
  836. $chattopic = Chattopic::find($result);
  837. }
  838. Db::commit();
  839. } catch (\Exception $e) {
  840. Db::rollBack();
  841. return Result::error($data, $e->getMessage());
  842. }
  843. return Result::success($chattopic);
  844. }
  845. public function applyTopic(array $data): array
  846. {
  847. date_default_timezone_set('Asia/Shanghai');
  848. db::beginTransaction();
  849. try {
  850. $query = ChatTopic::where(['id' => $data['id']]);
  851. $topdata = $query->first();
  852. $result = ChatTopic::where(['id' => $data['id']])->update(['status' => $data['status']]);
  853. var_dump($result, 'tedst111111111111111');
  854. var_dump(date('Y-m-d H:i:s'), 'tedst111111111111111');
  855. $creatter = $topdata['user_id'];
  856. if ($data['status'] == 2) {
  857. //插入一条消息
  858. $chatRecordsData = [
  859. 'user_id' => $topdata['user_id'],
  860. 'receiver_id' => $topdata['group_id'],
  861. 'content' => '我创建了一个群' . Date('Y-m-d H:i:s'),
  862. 'msg_type' => 1,
  863. 'is_read' => 0,
  864. 'talk_type' => 2,
  865. 'action' => 'said',
  866. 'group_receiver_id' => $topdata['user_id'],
  867. ];
  868. ChatRecords::insert($chatRecordsData);
  869. } elseif ($data['status'] == 3) {
  870. ChatRecords::where('receiver_id', $topdata['group_id'])->delete();
  871. ChatGroupsMember::where('group_id', $topdata['group_id'])
  872. ->where([["user_id", '!=', $creatter]])->delete();
  873. }
  874. Db::commit();
  875. if ($result) {
  876. return Result::success($data);
  877. } else {
  878. return Result::error($data);
  879. }
  880. } catch (\Exception $e) {
  881. Db::rollBack();
  882. return Result::error($data, $e->getMessage());
  883. }
  884. if (empty($data['id'])) {
  885. return Result::error('id不能为空');
  886. }
  887. }
  888. public function updateTopic(array $data): array
  889. {
  890. if (empty($data['id'])) {
  891. return Result::error('id不能为空');
  892. }
  893. $result = ChatTopic::where(['id' => $data['id']])->update($data);
  894. if ($result) {
  895. return Result::success($data);
  896. } else {
  897. return Result::error($data);
  898. };
  899. }
  900. public function delTopic(array $data): array
  901. {
  902. $result = ChatTopic::where(['id' => $data['id']])->delete();
  903. //删除群和成员和聊天
  904. //删除话题回复
  905. if ($result) {
  906. return Result::success($data);
  907. } else {
  908. return Result::error('删除失败');
  909. };
  910. }
  911. public function getTopicInfo(array $data): array
  912. {
  913. $result = ChatTopic::where(['chat_topics.id' => $data['id']])
  914. ->leftJoin('user', 'user.id', '=', 'chat_topics.user_id')
  915. ->leftJoin('chat_topic_class', 'chat_topic_class.id', '=', 'chat_topics.type')
  916. ->select('chat_topics.*', 'user.nickname', 'user.avatar', 'user.user_name','chat_topic_class.topicname')
  917. ->first();
  918. return Result::success($result);
  919. }
  920. public function addReply(array $data): array
  921. {
  922. $result = ChatTopic::where(['id' => $data['id']])->get();
  923. if ($result) {
  924. $replydata['created_at'] = date('Y-m-d H:i:s');
  925. $replydata['updated_at'] = date('Y-m-d H:i:s');
  926. $replydata['content'] = $data['content'];
  927. $replydata['user_id'] = $data['user_id'];
  928. $replydata['topic_id'] = $data['id'];
  929. $re = ChatTopicsReply::insertGetId($replydata);
  930. }
  931. if ($re) {
  932. return Result::success($data);
  933. } else {
  934. return Result::error($data);
  935. }
  936. }
  937. public function getTopicReply(array $data): array
  938. {
  939. var_dump($data);
  940. $result = ChatTopicsReply::where(['topic_id' => $data['id']])
  941. ->leftJoin('user', 'user.id', '=', 'chat_topics_reply.user_id')
  942. ->select('chat_topics_reply.*', 'user.nickname', 'user.avatar', 'user.user_name')
  943. ->orderBy('chat_topics_reply.id', 'desc')
  944. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  945. return Result::success($result);
  946. }
  947. /**
  948. * 修改群成员
  949. * @param array $data
  950. * @return array
  951. */
  952. public function updateGroupMembers(array $data): array
  953. {
  954. $where = [
  955. 'group_id' => $data['group_id'],
  956. ];
  957. $group_id = $data['group_id'];
  958. //先删除群成员
  959. $result = ChatGroupsMember::where($where)
  960. ->where([["user_id", '!=', $data['user_id']]])->delete();
  961. $groupMemberData = [];
  962. foreach ($data['group_member'] as $value) {
  963. $groupMemberData[] = [
  964. 'id' => PublicData::uuid(),
  965. 'user_id' => $value,
  966. 'group_id' => $group_id,
  967. 'leader' => 0,
  968. ];
  969. }
  970. $result = ChatGroupsMember::where($where)->insert($groupMemberData);
  971. // 获取群信息
  972. $groupInfo = ChatGroups::where(['id' => $group_id])->first();
  973. if ($result) {
  974. return Result::success($groupInfo);
  975. } else {
  976. return Result::error($data);
  977. }
  978. }
  979. public function clearGroupRecords(array $data): array
  980. {
  981. $result = ChatRecords::where(['user_id' => $data['user_id'], 'receiver_id' => $data['id']])->delete();
  982. if ($result) {
  983. return Result::success("删除成功");
  984. } else {
  985. return Result::error("删除失败");
  986. }
  987. }
  988. public function recallRecord(array $data): array
  989. {
  990. //获取所有id,并删除掉
  991. $ids = array_column($data, 'id');
  992. $result = ChatRecords::whereIn('id', $ids)->delete();
  993. if ($result) {
  994. return Result::success("删除成功");
  995. } else {
  996. return Result::error("删除失败");
  997. }
  998. }
  999. public function clearRecords(array $data): array
  1000. {
  1001. $result = ChatRecords::where(['user_id' => $data['user_id'], 'receiver_id' => $data['friend_id']])->delete();
  1002. if ($result) {
  1003. return Result::success("删除成功");
  1004. } else {
  1005. return Result::error("删除失败");
  1006. }
  1007. }
  1008. public function getRecordByContent(array $data): array
  1009. {
  1010. $result = ChatRecords::where(['chat_records.user_id' => $data['user_id'], 'chat_records.receiver_id' => $data['receiver_id'], 'chat_records.content' => $data['content']])
  1011. ->orWhere(['chat_records.receiver_id' => $data['user_id'], 'chat_records.user_id' => $data['receiver_id'], 'chat_records.content' => $data['content']])
  1012. ->all();
  1013. if ($result) {
  1014. return Result::success($result['id']);
  1015. } else {
  1016. return Result::error("没有数据");
  1017. }
  1018. }
  1019. public function getRecord(array $data): array
  1020. {
  1021. $result = ChatRecords::where(['chat_records.id' => $data['id']])
  1022. ->leftJoin('user', 'user.id', '=', 'chat_records.user_id')
  1023. ->leftJoin('user as user2', 'user2.id', '=', 'chat_records.receiver_id')
  1024. ->select('chat_records.*', 'user.nickname', 'user.avatar', 'user.user_name', 'user2.nickname as receiver_nickname', 'user2.avatar as receiver_avatar')
  1025. ->get();
  1026. return Result::success($result);
  1027. }
  1028. public function delReply(array $data): array
  1029. {
  1030. $result = ChatTopicsReply::where(['id' => $data['id']])->delete();
  1031. if ($result) {
  1032. return Result::success("删除成功");
  1033. } else {
  1034. return Result::error("删除失败");
  1035. }
  1036. }
  1037. public function delAllReply(array $data): array
  1038. {
  1039. $result = ChatTopicsReply::where(['topic_id' => $data['topicid']])->delete();
  1040. if ($result) {
  1041. return Result::success("删除成功");
  1042. } else {
  1043. return Result::error("删除失败");
  1044. }
  1045. }
  1046. public function getTopicsListAdmin(array $data): array
  1047. {
  1048. $where = [];
  1049. if (!empty($data['type'])) {
  1050. $where['type'] = $data['type'];
  1051. }
  1052. if (!empty($data['title'])) {
  1053. $where['title'] = $data['title'];
  1054. }
  1055. $result = ChatTopic::where($where)
  1056. ->leftJoin('user', 'user.id', '=', 'chat_topics.user_id')
  1057. ->select('chat_topics.*', 'user.nickname', 'user.avatar', 'user.user_name')
  1058. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  1059. return Result::success($result);
  1060. }
  1061. public function getTopicClassList(array $data): array
  1062. {
  1063. $where = [];
  1064. if (!empty($data['topicname'])) {
  1065. $where[] = ['topicname', 'like', '%' . $data['topicname'] . '%'];
  1066. }
  1067. $result = ChatTopicClass::where($where)->orderBy('updated_at', 'desc')
  1068. ->paginate($data['page_size'], ['*'], 'page', $data['page'] ?? 1);
  1069. return Result::success($result);
  1070. }
  1071. public function deleteTopicClass(array $data): array
  1072. {
  1073. $result = ChatTopicClass::where(['id' => $data['id']])->delete();
  1074. if ($result) {
  1075. return Result::success("删除成功");
  1076. }
  1077. return Result::error("删除失败");
  1078. }
  1079. public function updateTopicClass(array $data): array
  1080. {
  1081. //topicname
  1082. if (!empty($data['topicname'])) {
  1083. $re = ChatTopicClass::where(['topicname' => $data['topicname']])->first();
  1084. if ($re) {
  1085. return Result::error("话题分类已存在");
  1086. }
  1087. }
  1088. $result = ChatTopicClass::where(['id' => $data['id']])->update([
  1089. 'topicname' => $data['topicname'],
  1090. 'updated_at' => date('Y-m-d H:i:s'),
  1091. ]);
  1092. if ($result) {
  1093. return Result::success("修改成功");
  1094. }
  1095. return Result::error("修改失败");
  1096. }
  1097. public function addTopicClass(array $data): array
  1098. {
  1099. //topicname
  1100. if (!empty($data['topicname'])) {
  1101. $re = ChatTopicClass::where(['topicname' => $data['topicname']])->first();
  1102. if ($re) {
  1103. return Result::error("话题分类已存在");
  1104. }
  1105. }
  1106. $result = ChatTopicClass::insert($data);
  1107. if ($result) {
  1108. return Result::success("添加成功");
  1109. }
  1110. return Result::error("添加失败");
  1111. }
  1112. /**
  1113. * 获取话题分类信息
  1114. * @param array $data
  1115. * @return array
  1116. */
  1117. public function getTopicClassInfo(array $data): array
  1118. {
  1119. $result = ChatTopicClass::where(['id' => $data['id']])->first();
  1120. return Result::success($result);
  1121. }
  1122. /**
  1123. * @param array $data
  1124. * @return array
  1125. */
  1126. public function getBusinessDistrictList(array $data): array
  1127. {
  1128. $query = ChatGroupsMember::Join('chat_topics', 'chat_topics.group_id', '=', 'chat_groups_members.group_id')
  1129. ->leftJoin('chat_topic_class', 'chat_topic_class.id', '=', 'chat_topics.type')
  1130. ->where(['chat_groups_members.user_id' => $data['user_id']])
  1131. ->when($data, function ($query) use ($data) {
  1132. if(!empty($data['type'])){
  1133. $query->where(['chat_topics.type' => $data['type']]);
  1134. }
  1135. if(!empty($data['title'])){
  1136. $query->where('chat_topics.title','like','%'.$data['title'].'%');
  1137. }
  1138. if(!empty($data['created_at'])){
  1139. $query->whereDate('chat_topics.created_at', $data['created_at']);
  1140. }
  1141. })
  1142. ->select(
  1143. 'chat_topics.id',
  1144. 'chat_topics.title',
  1145. 'chat_topics.author',
  1146. 'chat_topics.created_at',
  1147. 'chat_topics.updated_at',
  1148. 'chat_topic_class.topicname',
  1149. )
  1150. ->orderBy('chat_topics.created_at', 'desc');
  1151. $total = $query->count();
  1152. $list = $query->forPage($data['page'], $data['page_size'])->get();
  1153. $result = [
  1154. 'list' => $list,
  1155. 'total' => $total,
  1156. 'page' => intval($data['page']),
  1157. 'page_size' => intval($data['page_size']),
  1158. ];
  1159. return Result::success($result);
  1160. }
  1161. }