XuqmGroup-WeChatMiniProgram.../pages/chat/chat.js

105 行
2.5 KiB
JavaScript

const app = getApp()
Page({
data: {
userId: '',
connected: false,
activeTab: 'conv',
conversations: [],
friends: [],
messages: [],
currentTarget: '',
currentChatType: 'SINGLE',
inputText: '',
},
onLoad() {
const sdk = app.globalData.sdk
const userId = app.globalData.userId
this.setData({ userId })
sdk.on('connected', () => this.setData({ connected: true }))
sdk.on('disconnected', () => this.setData({ connected: false }))
sdk.on('message', (msg) => this.handleMessage(msg))
sdk.on('revoke', ({ msgId }) => this.handleRevoke(msgId))
this.loadConversations()
this.loadFriends()
},
onUnload() {
app.globalData.sdk?.disconnect()
},
handleMessage(msg) {
const messages = [...this.data.messages, msg]
this.setData({ messages })
},
handleRevoke(msgId) {
const messages = this.data.messages.map(m =>
m.id === msgId ? { ...m, revoked: true, content: '' } : m
)
this.setData({ messages })
},
async loadConversations() {
try {
const conversations = await app.globalData.sdk.listConversations()
this.setData({ conversations })
} catch (err) {
console.error('loadConversations failed', err)
}
},
async loadFriends() {
try {
const friends = await app.globalData.sdk.listFriends()
this.setData({ friends })
} catch (err) {
console.error('loadFriends failed', err)
}
},
switchTab(e) {
this.setData({ activeTab: e.currentTarget.dataset.tab })
},
selectConv(e) {
const { id, type } = e.currentTarget.dataset
this.setData({ currentTarget: id, currentChatType: type, messages: [] })
this.loadHistory(id, type)
},
startChat(e) {
const id = e.currentTarget.dataset.id
this.setData({ currentTarget: id, currentChatType: 'SINGLE', messages: [] })
this.loadHistory(id, 'SINGLE')
},
async loadHistory(targetId, chatType) {
try {
const result = await app.globalData.sdk.fetchHistory(targetId, { page: 0, size: 50 })
this.setData({ messages: result.content || [] })
} catch (err) {
console.error('loadHistory failed', err)
}
},
onInput(e) {
this.setData({ inputText: e.detail.value })
},
sendText() {
const { inputText, currentTarget, currentChatType } = this.data
if (!inputText.trim() || !currentTarget) return
app.globalData.sdk.send({
toId: currentTarget,
chatType: currentChatType,
msgType: 'TEXT',
content: inputText.trim(),
})
this.setData({ inputText: '' })
},
})