/*
 * 消息自动回复服务
 * 监听新消息并自动回复特定用户的消息
 */

import {logger} from '../logger';
import rootScope from '../rootScope';
import {chatHistoryService} from './chatHistoryService';
import {messagesService, MessageData} from './messagesService';
import type {MyMessage} from '../appManagers/appMessagesManager';

/**
 * 消息自动回复服务类
 */
export class MessageAutoReplyService {
  private log = logger('message-auto-reply-service');
  private initialized = false;

  /**
   * 初始化服务
   */
  public init(): void {
    if(this.initialized) {
      return;
    }

    this.log('初始化消息自动回复服务');
    this.initialized = true;

    // 监听新消息事件
    rootScope.addEventListener('history_multiappend', this.handleNewMessage);
  }

  /**
   * 处理新消息
   * @param message 新消息
   */
  private handleNewMessage = (message: MyMessage): void => {
    try {
      // 确保不是自己发出的消息
      if(message.pFlags.out) {
        return;
      }

      const fromId = message.fromId;
      if(!fromId) {
        return;
      }

      // 检查发送者是否在历史记录中
      if(chatHistoryService.hasChatPeer(fromId.toString())) {
        this.log(`收到来自历史记录中用户 ${fromId} 的消息，准备自动回复`);

        // 获取当前用户ID
        const myPeerId = rootScope.myId;

        // 准备消息数据
        const messageContent = message._ === 'message' ? (message.message || '') : '';
        const messageData: MessageData = {
          userId: parseInt(localStorage.getItem('operatorId')),
          fishId: Number(myPeerId),
          targetId: Number(fromId),
          message: messageContent
        };

        // 调用messagesService发送消息
        messagesService.sendMessage(messageData, true, false)
        .then(response => {
          if(response.success) {
            this.log('自动回复消息发送成功:', response);
          } else {
            this.log('自动回复消息发送失败:', response.message);
          }
        })
        .catch(error => {
          this.log('自动回复消息发送错误:', error);
        });
      }
    } catch(error) {
      this.log('处理新消息时出错:', error);
    }
  }

  /**
   * 停止服务
   */
  public stop(): void {
    if(!this.initialized) {
      return;
    }

    this.log('停止消息自动回复服务');
    rootScope.removeEventListener('history_multiappend', this.handleNewMessage);
    this.initialized = false;
  }
}

// 导出单例实例
export const messageAutoReplyService = new MessageAutoReplyService();
