import {
  checkGlobalIMStatus,
  ensureGlobalIMConnection,
  getGlobalIMLoginStatus
} from './tim-chat.js'

/**
 * 全局IM状态管理器
 * 提供统一的IM状态检测和管理接口
 */
class IMStatusManager {
  constructor() {
    this.statusCheckInterval = null
    this.isMonitoring = false
    this.checkIntervalTime = 60000 // 默认1分钟检查一次
    this.lastCheckTime = 0
    this.callbacks = {
      onStatusChange: [],
      onReconnectSuccess: [],
      onReconnectFailed: []
    }
  }

  /**
   * 启动IM状态监控
   * @param {number} intervalTime 检查间隔时间（毫秒）
   */
  startMonitoring(intervalTime = 60000) {
    if (this.isMonitoring) {
      console.log('IM状态监控已在运行')
      return
    }

    this.checkIntervalTime = intervalTime
    this.isMonitoring = true

    // 立即检查一次
    this.checkIMStatus()

    // 启动定时检查
    this.statusCheckInterval = setInterval(() => {
      this.checkIMStatus()
    }, this.checkIntervalTime)

    console.log(`IM状态监控已启动，检查间隔：${intervalTime / 1000}秒`)
  }

  /**
   * 停止IM状态监控
   */
  stopMonitoring() {
    if (this.statusCheckInterval) {
      clearInterval(this.statusCheckInterval)
      this.statusCheckInterval = null
    }
    this.isMonitoring = false
    console.log('IM状态监控已停止')
  }

  /**
   * 检查IM状态
   */
  async checkIMStatus() {
    const now = Date.now()
    this.lastCheckTime = now

    try {
      console.log('执行IM状态检查...')
      const isLoggedIn = checkGlobalIMStatus()

      // 触发状态变化回调
      this.triggerCallbacks('onStatusChange', {
        isLoggedIn,
        checkTime: now,
        timestamp: new Date().toLocaleString()
      })

      if (!isLoggedIn) {
        console.log('检测到IM未登录，尝试重连...')
        await this.attemptReconnect()
      } else {
        console.log('IM状态正常')
      }

      return isLoggedIn
    } catch (error) {
      console.error('IM状态检查异常:', error)
      return false
    }
  }

  /**
   * 尝试重连IM
   */
  async attemptReconnect() {
    try {
      console.log('开始尝试IM重连...')
      const success = await ensureGlobalIMConnection()

      if (success) {
        console.log('IM重连成功')
        this.triggerCallbacks('onReconnectSuccess', {
          timestamp: new Date().toLocaleString()
        })

      } else {
        console.log('IM重连失败')
        this.triggerCallbacks('onReconnectFailed', {
          timestamp: new Date().toLocaleString()
        })
      }

      return success
    } catch (error) {
      console.error('IM重连异常:', error)
      this.triggerCallbacks('onReconnectFailed', {
        error,
        timestamp: new Date().toLocaleString()
      })
      return false
    }
  }

  /**
   * 手动触发IM连接检查
   */
  async forceCheck() {
    console.log('手动触发IM连接检查')
    return await this.checkIMStatus()
  }

  /**
   * 获取当前IM登录状态
   */
  getCurrentStatus() {
    return {
      isLoggedIn: getGlobalIMLoginStatus(),
      isMonitoring: this.isMonitoring,
      lastCheckTime: this.lastCheckTime,
      checkInterval: this.checkIntervalTime
    }
  }

  /**
   * 添加状态变化回调
   */
  onStatusChange(callback) {
    if (typeof callback === 'function') {
      this.callbacks.onStatusChange.push(callback)
    }
  }

  /**
   * 添加重连成功回调
   */
  onReconnectSuccess(callback) {
    if (typeof callback === 'function') {
      this.callbacks.onReconnectSuccess.push(callback)
    }
  }

  /**
   * 添加重连失败回调
   */
  onReconnectFailed(callback) {
    if (typeof callback === 'function') {
      this.callbacks.onReconnectFailed.push(callback)
    }
  }

  /**
   * 移除回调
   */
  removeCallback(type, callback) {
    if (this.callbacks[type]) {
      const index = this.callbacks[type].indexOf(callback)
      if (index > -1) {
        this.callbacks[type].splice(index, 1)
      }
    }
  }

  /**
   * 触发回调
   */
  triggerCallbacks(type, data) {
    if (this.callbacks[type]) {
      this.callbacks[type].forEach(callback => {
        try {
          callback(data)
        } catch (error) {
          console.error(`执行${type}回调失败:`, error)
        }
      })
    }
  }

  /**
   * 获取状态报告
   */
  getStatusReport() {
    const status = this.getCurrentStatus()
    return {
      ...status,
      report: {
        isLoggedIn: status.isLoggedIn ? '已登录' : '未登录',
        monitoring: status.isMonitoring ? '监控中' : '未监控',
        lastCheck: status.lastCheckTime ?
          new Date(status.lastCheckTime).toLocaleString() : '从未检查',
        interval: `${status.checkInterval / 1000}秒`
      }
    }
  }
}

// 创建全局实例
const globalIMStatusManager = new IMStatusManager()

// 便捷函数
export const startIMMonitoring = (interval) => globalIMStatusManager.startMonitoring(interval)
export const stopIMMonitoring = () => globalIMStatusManager.stopMonitoring()
export const checkIMStatusNow = () => globalIMStatusManager.forceCheck()
export const getIMStatus = () => globalIMStatusManager.getCurrentStatus()
export const getIMStatusReport = () => globalIMStatusManager.getStatusReport()

// 导出管理器实例和类
export { globalIMStatusManager, IMStatusManager }
export default globalIMStatusManager 