blob: 4eb3840538983be8225e3a8d25802c7165471138 [file] [log] [blame] [edit]
import { request } from '@umijs/max';
import type {
SysUserMessage,
ChatContact,
ChatContactListParams,
ChatHistoryParams,
SendMessageParams,
} from './data.d';
// API 路径配置 - 可根据实际后端接口调整
const API_CONFIG = {
CHAT_CONTACTS: '/api/system/user/message/chat/users',
CHAT_HISTORY: '/api/system/user/message/list',
SEND_MESSAGE: '/api/system/user/message',
USER_INFO: '/api/system/user'
};
/** 获取聊天对象列表 */
export async function getChatContactList() {
// 默认数据
const defaultData = [
{
userId: 2,
nickName: '张三'
},
{
userId: 3,
nickName: '李四'
},
{
userId: 4,
nickName: '王五'
}
];
try {
const response = await request('/api/system/user/message/chat/users', {
method: 'get'
});
if (!response) {
return defaultData;
}
return response.data;
} catch (error) {
console.warn('获取聊天对象列表接口异常,使用默认数据:', error);
return defaultData;
}
}
/** 获取与指定用户的聊天记录 */
export async function getChatHistory(params: ChatHistoryParams) {
// 默认数据
const defaultData = [
{
messageId: 1,
senderId: params.userId,
receiverId: params.currentUserId || 1,
content: `这是来自用户${params.userId}的第一条消息`,
createTime: new Date(Date.now() - 1000 * 60 * 60 * 2),
delFlag: '0'
},
{
messageId: 2,
senderId: params.currentUserId || 1,
receiverId: params.userId,
content: '收到,感谢你的消息',
createTime: new Date(Date.now() - 1000 * 60 * 60),
delFlag: '0'
},
{
messageId: 3,
senderId: params.userId,
receiverId: params.currentUserId || 1,
content: `这是来自用户${params.userId}的最新消息,包含更多详细信息`,
createTime: new Date(Date.now() - 1000 * 60 * 30),
delFlag: '0'
}
];
try {
const response = await request(`${API_CONFIG.CHAT_HISTORY}`, {
method: 'get',
params: {
userId1: params.currentUserId,
userId2: params.userId
}
});
console.log(response);
if (!response || !response.data) {
return defaultData;
}
return response.data;
} catch (error) {
console.warn('获取聊天记录接口异常,使用默认数据:', error);
return defaultData;
}
}
/** 发送消息 */
export async function sendMessage(params: SendMessageParams) {
try {
return await request(API_CONFIG.SEND_MESSAGE, {
method: 'post',
data: params,
});
} catch (error) {
// 发送消息失败时记录错误但不返回默认数据,让组件处理错误
console.error('发送消息接口异常:', error);
throw error; // 重新抛出错误,让调用方处理
}
}
// 添加好友
export async function addFriend(params: { userId: number, authorUsername: string }) {
try {
return await request('api/system/user/follow', {
method: 'post',
data: params,
});
} catch (error) {
// 发送消息失败时记录错误但不返回默认数据,让组件处理错误
console.error('发送消息接口异常:', error);
throw error; // 重新抛出错误,让调用方处理
}
};
/** 获取用户信息(用于聊天对象显示) */
export async function getUserInfo(userId: number) {
// 默认用户信息
const defaultUserInfo = {
userId,
nickName: `用户${userId}`,
avatar: ''
};
try {
const response = await request(`${API_CONFIG.USER_INFO}/${userId}`, {
method: 'get',
});
if (!response || !response.data) {
return defaultUserInfo;
}
return response.data;
} catch (error) {
// 接口报错时返回默认用户信息
console.warn(`获取用户${userId}信息接口异常,使用默认数据:`, error);
return defaultUserInfo;
}
}