import { apiRequest, saveToken } from '../core/http' import { getConfig } from '../core/config' import { ImClient } from './imClient' import type { ChatType, ImEventListener, MsgType } from './types' let client: ImClient | null = null export const ImSDK = { async login(userId: string, nickname?: string, avatar?: string): Promise { const config = getConfig() const res = await apiRequest<{ token: string }>('/api/im/auth/login', { method: 'POST', params: { appId: config.appId, userId, ...(nickname ? { nickname } : {}), ...(avatar ? { avatar } : {}), }, }) await saveToken(res.token) client = new ImClient(config.imWsUrl, res.token, config.appId) client.connect() }, sendMessage(toId: string, chatType: ChatType, msgType: MsgType, content: string, mentionedUserIds?: string) { if (!client) throw new Error('ImSDK: not logged in') client.sendMessage(toId, chatType, msgType, content, mentionedUserIds) }, addListener(listener: ImEventListener) { client?.addListener(listener) }, removeListener(listener: ImEventListener) { client?.removeListener(listener) }, disconnect() { client?.disconnect() client = null }, isConnected() { return client?.isConnected() ?? false }, }