quanwei
2025-12-31 48d31672b4d88900080093cd1632f9d2eb978d4d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
<?php
 
namespace app\api\controller\plus\business\chat;
 
use app\api\controller\Controller;
use app\api\model\plus\business\chat\Chat as ChatModel;
use app\api\model\plus\business\chat\Conversation as ConversationModel;
use app\api\model\plus\business\chat\Participant;
use app\api\model\settings\Setting as SettingModel;
use app\api\model\user\User as UserModel;
use app\common\model\plus\business\Business as BusinessModel;
 
/**
 * 名片聊天控制器
 */
class Chat extends Controller
{
    /**
     * 发送消息
     */
    public function sendMessage()
    {
        $user = $this->getUser();
        $userId = $user['user_id'];
        $conversationId = $this->request->post('conversation_id/d', 0);
        $businessCardId = $this->request->post('business_card_id/d', 0);
        $content = $this->request->post('content/s', '');
        
        if (empty($content)) {
                return $this->renderError('消息内容不能为空');
        }
        
        // 如果没有会话ID,根据名片ID创建会话
        if (empty($conversationId) && !empty($businessCardId)) {
            $conversationModel = new ConversationModel();
            
            // 获取名片信息
            $businessModel = new BusinessModel();
            $businessCard = $businessModel->where('business_card_id', $businessCardId)->find();
            
            if (!$businessCard) {
                return $this->renderError('名片不存在');
            }
            
            // 创建会话,参与者包括当前用户和名片所有者
            $participants = [$userId, $businessCard->user_id];
            $conversationId = $conversationModel->createConversation($businessCardId, $participants);
            
            if (!$conversationId) {
                return $this->renderError('创建会话失败');
            }
        }
        
        if (empty($conversationId)) {
                return $this->renderError('会话ID不能为空');
        }
        
        $chatModel = new ChatModel();
        $result = $chatModel->sendMessage($conversationId, $userId, $content);
        
        if ($result) {
            // 更新会话时间
            $conversationModel = new ConversationModel();
            $conversationModel->updateConversationTime($conversationId);
            // 准备WebSocket消息数据
            $wsMessage = [
                'type' => 'message',
                'user_id' => $userId,
                'to_user_id' => 0, // 需要确定接收者ID
                'content' => $content,
                'conversation_id' => $conversationId,
                'business_card_id' => $businessCardId,
                'chat_id' => $chatModel->chat_id,
                'time' => date('Y-m-d H:i:s')
            ];
 
            // 确定接收者ID
            $participantModel = new Participant();
            $participants = $participantModel->where('conversation_id', $conversationId)
                ->where('user_id', '<>', $userId)
                ->select();
 
            if (!empty($participants)) {
                $wsMessage['to_user_id'] = $participants[0]['user_id'];
            }
 
            return $this->renderSuccess('发送成功', [
                'message' => $chatModel->toArray(),
                'ws_message' => $wsMessage
            ]);
        } else {
            return $this->renderError('发送失败');
        }
    }
    
    /**
     * 获取会话消息列表
     */
    public function getMessages()
    {
        $param=request()->param();
        $user = $this->getUser();
        $userId = $user['user_id'];
        if (empty($param['conversation_id']) && !empty($param['business_card_id'])) {
            $conversationModel = new ConversationModel();
            $conversation = $conversationModel->getConversationByBusinessCard($param['business_card_id']);
            if ($conversation) {
                $param['conversation_id'] = $conversation['conversation_id'];
            }
        }
        
        if (empty($param['conversation_id'])) {
            return $this->renderError('会话不存在');
        }
        
        $chatModel = new ChatModel();
        $messages = $chatModel->getMessages($param);
        $hasParticipant = Participant::where('conversation_id', $param['conversation_id'])
            ->where('user_id','<>', $userId)
            ->find();
        $heUser=(new UserModel())->detail($hasParticipant['user_id']);
        $card=(new BusinessModel())->where('user_id',$hasParticipant['user_id'])->where('is_default',1)->find();
 
        return $this->renderSuccess('获取成功', compact('messages','heUser','card'));
    }
    
    /**
     * 获取会话列表
     */
    public function getConversations()
    {
        $param=request()->param();
        $user = $this->getUser();
        $param['user_id'] = $user['user_id'];
        
        
        $conversationModel = new ConversationModel();
        $conversations = $conversationModel->getUserConversations($param);
        // 为每个会话添加未读消息数量
        $chatModel = new ChatModel();
        foreach ($conversations as &$conversation) {
            $conversation['unread_count'] = $chatModel->getUnreadCount($conversation['conversation_id'], $param['user_id']);
            $chatData=$chatModel->where('conversation_id',$conversation['conversation_id'])->order('create_time','desc')->find();
            // 获取最后一条消息
            if (!empty($chatData)) {
                $conversation['last_message'] = $chatData;
            }
        }
        
        return $this->renderSuccess('获取成功', compact('conversations'));
    }
    
    /**
     * 标记消息为已读
     */
    public function markAsRead()
    {
        $user = $this->getUser();
        $userId = $user['user_id'];
        
        $param=request()->param();
        
        if (empty($param['chat_id']) && empty($param['conversation_id'])) {
            return $this->renderError('参数错误');
        }
        
        $chatModel = new ChatModel();
        
        if (!empty($param['chat_id'])) {
            // 标记单条消息为已读
            $result = $chatModel->markAsRead($param['chat_id'], $userId);
            $error=$chatModel->getError();
        } else {
            $chatDate=$chatModel->where('conversation_id',$param['conversation_id'])->where('sender_id','<>',$userId)->find();
            if (empty($chatDate)){
                return $this->renderSuccess('标记成功');
            }
            // 标记整个会话为已读
            $participantModel = new Participant();
            $result = $participantModel->markConversationAsRead($param['conversation_id'], $chatDate['sender_id']);
            // 更新会话中所有消息的已读状态
            if ($result) {
                $chatModel->where('conversation_id', $param['conversation_id'])
                    ->where('sender_id', '<>', $userId)
                    ->where('is_read', 0)
                    ->update([
                        'is_read' => 1,
                        'read_time' => time(),
                        'update_time' => time()
                    ]);
            }
            $error=$participantModel->getError();
        }
        
        if ($result) {
            return $this->renderSuccess('标记成功');
        } else {
            return $this->renderError('标记失败'.$error);
        }
    }
    
    /**
     * 根据名片ID获取或创建会话
     */
    public function getOrCreateConversation()
    {
        $user = $this->getUser();
        $userId = $user['user_id'];
        
        $businessCardId = $this->request->post('business_card_id/d', 0);
        
        if (empty($businessCardId)) {
            return $this->renderError('名片ID不能为空');
        }
        
        // 获取名片信息
        $businessModel = new BusinessModel();
        $businessCard = $businessModel->where('business_card_id', $businessCardId)->find();
        
        if (!$businessCard) {
            return $this->renderError('名片不存在');
        }
        
        $conversationModel = new ConversationModel();
        
        // 检查是否已存在会话
        $conversation = $conversationModel->getConversationByBusinessCardUser($businessCardId,$userId);
 
        if ($businessCard['user_id'] == $userId&&!$conversation) {
            return $this->renderError('不能与自己建立会话');
        }
        if (!$conversation) {
            // 创建新会话
            $participants = [$userId, $businessCard['user_id']];
            $conversationId = $conversationModel->createConversation($businessCardId, $participants);
            if ($conversationId) {
                $conversation = $conversationModel->getConversationByBusinessCard($businessCardId);
            }
        }
        
        if ($conversation) {
            // 添加未读消息数量
            $chatModel = new ChatModel();
            $conversation['unread_count'] = $chatModel->getUnreadCount($conversation['conversation_id'], $userId);
 
            $wsUrl = SettingModel::getSysConfig()['url'];
            return $this->renderSuccess('获取成功', compact('conversation','wsUrl'));
        } else {
            return $this->renderError('创建会话失败');
        }
    }
}