Files
cunkebao_v3/Server/application/chukebao/controller/WechatFriendController.php

95 lines
3.4 KiB
PHP
Raw Normal View History

2025-09-13 17:20:34 +08:00
<?php
namespace app\chukebao\controller;
use library\ResponseHelper;
use think\Db;
class WechatFriendController extends BaseController
{
public function getList(){
$page = $this->request->param('page', 1);
$limit = $this->request->param('limit', 10);
$accountId = $this->getUserInfo('s2_accountId');
if (empty($accountId)){
return ResponseHelper::error('请先登录');
}
2025-09-16 09:57:06 +08:00
$query = Db::table('s2_wechat_friend')
->where(['accountId' => $accountId,'isDeleted' => 0])
->order('id desc');
$list = $query->page($page, $limit)->select();
$total = $query->count();
2025-09-17 16:51:11 +08:00
// 提取所有好友ID
$friendIds = array_column($list, 'id');
// 一次性查询所有好友的未读消息数量
$unreadCounts = [];
if (!empty($friendIds)) {
$unreadResults = Db::table('s2_wechat_message')
->field('wechatFriendId, COUNT(*) as count')
->where('wechatFriendId', 'in', $friendIds)
->where('isRead', 0)
->group('wechatFriendId')
->select();
foreach ($unreadResults as $result) {
$unreadCounts[$result['wechatFriendId']] = $result['count'];
}
}
// 一次性查询所有好友的最新消息
$latestMessages = [];
if (!empty($friendIds)) {
// 使用子查询获取每个好友的最新消息ID
$subQuery = Db::table('s2_wechat_message')
->field('MAX(id) as max_id, wechatFriendId')
->where('wechatFriendId', 'in', $friendIds)
->group('wechatFriendId')
->buildSql();
// 查询最新消息的详细信息
$messageResults = Db::table('s2_wechat_message')
->alias('m')
->join([$subQuery => 'sub'], 'm.id = sub.max_id')
->field('m.*, sub.wechatFriendId')
->select();
foreach ($messageResults as $message) {
$latestMessages[$message['wechatFriendId']] = $message;
}
}
2025-09-19 16:48:42 +08:00
$aiTypeData = [];
if (!empty($friendIds)) {
$aiTypeData = Db::name('ai_friend_settings')
->where('friendId', 'in', $friendIds)
->column('friendId,type');
}
2025-09-17 16:51:11 +08:00
// 处理每个好友的数据
foreach ($list as $k => &$v) {
$v['createTime'] = !empty($v['createTime']) ? date('Y-m-d H:i:s', $v['createTime']) : '';
$v['updateTime'] = !empty($v['updateTime']) ? date('Y-m-d H:i:s', $v['updateTime']) : '';
$v['passTime'] = !empty($v['passTime']) ? date('Y-m-d H:i:s', $v['passTime']) : '';
2025-09-19 16:48:42 +08:00
2025-09-17 16:51:11 +08:00
$config = [
'unreadCount' => isset($unreadCounts[$v['id']]) ? $unreadCounts[$v['id']] : 0,
'chat' => isset($latestMessages[$v['id']]),
'msgTime' => isset($latestMessages[$v['id']]) ? $latestMessages[$v['id']]['wechatTime'] : 0
];
// 将消息配置添加到好友数据中
$v['config'] = $config;
2025-09-19 16:48:42 +08:00
$v['aiType'] = isset($aiTypeData[$v['id']]) ? $aiTypeData[$v['id']] : 0;
2025-09-16 09:57:06 +08:00
}
unset($v);
return ResponseHelper::success(['list'=>$list,'total'=>$total]);
2025-09-13 17:20:34 +08:00
}
}