import { getChatRegisterInfoApi, getMessagesByRoomIdApi } from '@/api/chat.js';

/**
 * 聊天消息管理器（简化版）
 */
const ChatManager = {
  currentRoomId: null,
  lastMessageId: 0,
  unreadCounts: {},
  messageCache: {},
  roomMessages: {},

  enterRoom(roomId) {
    this.currentRoomId = roomId;
    uni.setStorageSync('currentRoomId', roomId);
    this.resetUnreadCount(roomId);
  },

  leaveRoom() {
    this.currentRoomId = null;
    uni.removeStorageSync('currentRoomId');
  },

  getCurrentRoomId() {
    return this.currentRoomId || uni.getStorageSync('currentRoomId');
  },

  increaseUnreadCount(roomId) {
    if (this.getCurrentRoomId() !== roomId) {
      this.unreadCounts[roomId] = (this.unreadCounts[roomId] || 0) + 1;
      this.notifyUnreadChange();
    }
  },

  resetUnreadCount(roomId) {
    if (this.unreadCounts[roomId]) {
      this.unreadCounts[roomId] = 0;
      this.notifyUnreadChange();
    }
  },

  getUnreadCount(roomId) {
    return this.unreadCounts[roomId] || 0;
  },

  getAllUnreadCount() {
    return Object.values(this.unreadCounts).reduce((sum, count) => sum + count, 0);
  },

  notifyUnreadChange() {
    uni.$emit('unread-message-update', {
      total: this.getAllUnreadCount(),
      byRoom: { ...this.unreadCounts }
    });
  },

  addMessageToRoom(roomId, message) {
    if (!this.roomMessages[roomId]) {
      this.roomMessages[roomId] = [];
    }
    this.roomMessages[roomId].push(message);
  },

  getRoomMessages(roomId) {
    let that = this;
    this.roomMessages[roomId] = [];
    getMessagesByRoomIdApi({
      room_id: roomId,
      last_message_id: 0,
    }).then((res) => {
      const payload = res && (res.result != null ? res.result : res.data && res.data.result);
      if (res && payload) {
        that.roomMessages[roomId] = that.checkMessage(payload.list || []);
        that.lastMessageId = payload.last_message_id || 0;
        uni.$emit('load-room-message', 1);
      }
    }).catch(err => {
      console.error('获取消息失败:', err);
    });
    return this.roomMessages[roomId] || [];
  },

  checkMessage(message, type = 0) {
    if (type === 1) {
      return {
        id: message.id,
        sender_user_id: message.sender_user_id,
        receiver_user_id: message.receiver_user_id,
        message_type: message.message_type,
        message_content: message.message_content,
        duration: message.duration,
        room_id: message.room_id,
        created_at: message.created_at || message.send_time,
        created_at_text: message.created_at_text || this.formatTime(message.send_time || message.created_at),
        timestamp: message.send_time || message.created_at
      };
    }
    return message.map((item) => {
      const result = {
        id: item.id,
        sender_user_id: item.sender_user_id,
        receiver_user_id: item.receiver_user_id,
        message_type: item.message_type,
        message_content: item.message_content,
        duration: item.duration,
        room_id: item.room_id,
        created_at: item.created_at || item.send_time,
        created_at_text: item.created_at_text || this.formatTime(item.send_time || item.created_at),
        timestamp: item.send_time || item.created_at
      };

      if (item.message_type === 10) {
        this.getChatRegisterInfo(result, message.indexOf(item));
      }
      return result;
    });
  },

  formatTime(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp * 1000);
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  },

  getChatRegisterInfo(message, index) {
    const parsedContent = this.parseMessageContent(message.message_content);
    if (parsedContent._loaded || !parsedContent.id) return;
    
    getChatRegisterInfoApi({ id: parsedContent.id, message_id: message.id || '' }).then((res) => {
      const info = res && (res.result != null ? res.result : res.data && res.data.result);
      if (res && info) {
        const resultWithFlag = { ...info, _loaded: true };
        const roomId = message.room_id;
        if (this.roomMessages[roomId] && this.roomMessages[roomId][index]) {
          this.roomMessages[roomId][index].message_content = JSON.stringify(resultWithFlag);
        }
      }
    });
  },

  parseMessageContent(content) {
    try {
      return typeof content === 'object' ? content : JSON.parse(content);
    } catch (e) {
      return content;
    }
  },

  loadHistory(roomId) {
    getMessagesByRoomIdApi({
      room_id: roomId,
      last_message_id: this.lastMessageId,
    }).then((res) => {
      const payload = res && (res.result != null ? res.result : res.data && res.data.result);
      if (res && payload) {
        const newMessages = this.checkMessage(payload.list || []);
        if (newMessages.length > 0) {
          this.roomMessages[roomId] = [...newMessages, ...(this.roomMessages[roomId] || [])];
          this.lastMessageId = payload.last_message_id || 0;
          uni.$emit('load-room-message', 0);
        } else {
          uni.$emit('no-more-history');
        }
      } else {
        uni.$emit('no-more-history');
      }
    }).catch(err => {
      console.error('加载历史消息失败:', err);
      uni.$emit('no-more-history');
    });
  }
};

export { ChatManager };
