/** * 会话列表:拉取并更新 chatStore.contacts */ import { getContacts, getToken } from '../utils/api' import { chatStore } from '../store/chat' /** * 拉取会话列表 * @param {{ silent?: boolean }} [opts] - silent 为 false 时会置 loadingContacts(默认 true:刷新不闪屏、不挡列表) */ export async function fetchContactsList(opts = {}) { const silent = opts.silent !== false const token = getToken() if (!token) { chatStore.contacts = [] chatStore.contactsFetchFailed = false return } if (!silent) chatStore.loadingContacts = true try { const data = await getContacts(token) const list = Array.isArray(data) ? data : (data.list || data.items || data.conversations || []) chatStore.setContacts( list.map((c) => { const id = String(c.user_id ?? c.userId ?? c.id ?? '') const unreadCount = Number(c.unread_count ?? c.unreadCount ?? 0) || 0 return { id, user_id: c.user_id ?? c.userId ?? c.id, title: c.full_name ?? c.name ?? c.title ?? '未知', lastMessage: typeof c.last_message === 'string' ? c.last_message : (c.last_message && (c.last_message.content || c.last_message.text)) ?? c.last_message_preview ?? '', time: c.updated_at ?? c.last_message?.created_at ?? '', avatar: c.avatar ?? c.avatar_url ?? '', unread_count: unreadCount, is_system: !!c.is_system, app_id: c.app_id ?? null, app_name: c.app_name ?? '' } }) ) chatStore.contactsFetchFailed = false } catch (e) { // 网络或接口失败:不覆盖已有会话列表;空列表时用于展示「请下拉刷新」 chatStore.contactsFetchFailed = true } finally { if (!silent) chatStore.loadingContacts = false } } export function useContacts() { return { contacts: chatStore.contacts, loadingContacts: chatStore.loadingContacts, fetchContacts: fetchContactsList } }