/**
 * 聊天相关API接口封装
 */

const CHAT_BASE_URL = 'http://localhost:1004/api/chat';

/**
 * 统一的聊天请求封装
 */
const chatRequest = (options) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data);
        } else {
          reject(res);
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        reject(err);
      }
    });
  });
};

/**
 * 获取用户会话列表
 */
export function getConversations(userId, pageNum = 1, pageSize = 20) {
  return chatRequest({
    url: `${CHAT_BASE_URL}/conversations?userId=${userId}&pageNum=${pageNum}&pageSize=${pageSize}`,
    method: 'GET'
  });
}

/**
 * 获取会话消息列表
 */
export function getMessages(userId, targetUserId, page = 0, size = 20) {
  return chatRequest({
    url: `${CHAT_BASE_URL}/messages?userId=${userId}&targetUserId=${targetUserId}&page=${page}&size=${size}`,
    method: 'GET'
  });
}

/**
 * 标记消息为已读
 */
export function markAsRead(userId, targetUserId) {
  return chatRequest({
    url: `${CHAT_BASE_URL}/read`,
    method: 'POST',
    data: {
      userId,
      targetUserId
    }
  });
}

/**
 * 获取未读消息总数
 */
export function getUnreadCount(userId) {
  return chatRequest({
    url: `${CHAT_BASE_URL}/unread/count?userId=${userId}`,
    method: 'GET'
  });
}

/**
 * 删除会话
 */
export function deleteConversation(userId, targetUserId) {
  return chatRequest({
    url: `${CHAT_BASE_URL}/conversation`,
    method: 'DELETE',
    data: {
      userId,
      targetUserId
    }
  });
}

/**
 * 检查用户在线状态
 */
export function checkOnlineStatus(userId) {
  return chatRequest({
    url: `${CHAT_BASE_URL}/online/status?userId=${userId}`,
    method: 'GET'
  });
}

/**
 * 上传聊天图片/文件
 */
export function uploadChatMedia(filePath) {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: 'http://localhost:8083/api/upload',  // 使用homePage服务的上传接口
      filePath: filePath,
      name: 'file',
      success: (res) => {
        try {
          const data = JSON.parse(res.data);
          resolve(data);
        } catch (e) {
          reject(e);
        }
      },
      fail: reject
    });
  });
}

/**
 * 查询消息状态（用于轮询确认）
 */
export function getMessageStatus(messageId) {
  return chatRequest({
    url: `${CHAT_BASE_URL}/message/status?messageId=${messageId}`,
    method: 'GET'
  });
}

export default {
  getConversations,
  getMessages,
  markAsRead,
  getUnreadCount,
  deleteConversation,
  checkOnlineStatus,
  uploadChatMedia,
  getMessageStatus
};



