/**
 * 微信小程序实时日志工具
 * 用于线上环境问题排查
 * 文档: https://developers.weixin.qq.com/miniprogram/dev/framework/realtimelog/
 */

class RealtimeLogger {
  constructor() {
    this.logger = null;
    this.enabled = true;
    this.init();
  }

  init() {
    try {
      // 获取实时日志管理器
      this.logger = wx.getRealtimeLogManager ? wx.getRealtimeLogManager() : null;
      
      if (!this.logger) {
        console.warn('当前微信版本不支持实时日志');
        this.enabled = false;
      }
    } catch (error) {
      console.error('实时日志初始化失败:', error);
      this.enabled = false;
    }
  }

  /**
   * 记录信息日志
   */
  info(...args) {
    if (this.enabled && this.logger) {
      this.logger.info.apply(this.logger, args);
    }
    // 同时输出到控制台
    console.log('[实时日志-INFO]', ...args);
  }

  /**
   * 记录警告日志
   */
  warn(...args) {
    if (this.enabled && this.logger) {
      this.logger.warn.apply(this.logger, args);
    }
    console.warn('[实时日志-WARN]', ...args);
  }

  /**
   * 记录错误日志
   */
  error(...args) {
    if (this.enabled && this.logger) {
      this.logger.error.apply(this.logger, args);
    }
    console.error('[实时日志-ERROR]', ...args);
  }

  /**
   * 设置过滤关键字（用于后台搜索）
   */
  setFilterMsg(msg) {
    if (this.enabled && this.logger && this.logger.setFilterMsg) {
      this.logger.setFilterMsg(msg);
    }
  }

  /**
   * 添加过滤关键字
   */
  addFilterMsg(msg) {
    if (this.enabled && this.logger && this.logger.addFilterMsg) {
      this.logger.addFilterMsg(msg);
    }
  }

  /**
   * 记录NIM相关日志（带标签）
   */
  nim(action, data) {
    const logData = {
      action,
      timestamp: new Date().toISOString(),
      data
    };
    this.info('[NIM]', JSON.stringify(logData));
  }

  /**
   * 记录登录相关日志
   */
  login(action, data) {
    const logData = {
      action,
      timestamp: new Date().toISOString(),
      data
    };
    this.info('[LOGIN]', JSON.stringify(logData));
  }

  /**
   * 记录网络请求日志
   */
  network(method, url, status, data) {
    const logData = {
      method,
      url,
      status,
      timestamp: new Date().toISOString(),
      data
    };
    this.info('[NETWORK]', JSON.stringify(logData));
  }
}

// 创建单例
const realtimeLogger = new RealtimeLogger();

module.exports = realtimeLogger;
