ChatService.php 44 KB

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