// WebSocket服务类 - 统一管理后台WebSocket连接
// 基于参考项目接口格式实现

import { getWebSocketConfig } from '@/config/cad'
import Logger from '@/utils/logger'

class WebSocketService {
  constructor() {
    this.config = getWebSocketConfig()
    this.ws = null
    this.connectionState = 'DISCONNECTED' // CONNECTING, CONNECTED, DISCONNECTED, ERROR
    this.reconnectAttempts = 0
    this.heartbeatTimer = null

    // 状态数据
    this.softwareList = []
    this.logs = []
    this.logStats = null
    this.operationTypes = []
    this.connectedUsers = []

    // 事件监听器
    this.listeners = {
      onOpen: [],
      onMessage: [],
      onClose: [],
      onError: [],
      onStateChange: [],
      onSoftwareUpdate: [],
      onLogUpdate: [],
      onStatsUpdate: [],
      onOperationTypesUpdate: []
    }

  }

  // 获取WebSocket连接URL
  getConnectionUrl() {
    const { BASE_URL, ENDPOINT, CLIENT_ID } = this.config
    // 动态获取当前用户信息
    const currentUser = this.getCurrentUser()
    const userId = currentUser?.username || 'anonymous'
    return `${BASE_URL}${ENDPOINT}?client_id=${CLIENT_ID}&user_id=${userId}`
  }

  // 获取当前登录用户信息
  getCurrentUser() {
    try {
      // 从localStorage读取用户信息
      const userKey = 'user' // 与auth.js中的tokenConfig.userKey保持一致
      const savedUser = localStorage.getItem(userKey)
      return savedUser ? JSON.parse(savedUser) : null
    } catch {
      return null
    }
  }

  // 连接WebSocket
  connect() {
    if (this.connectionState === 'CONNECTING' || this.connectionState === 'CONNECTED') {
      return
    }

    const url = this.getConnectionUrl()
    this.setState('CONNECTING')
    this.ws = new WebSocket(url)

    this.ws.onopen = (event) => {
      this.setState('CONNECTED')
      this.reconnectAttempts = 0
      this.startHeartbeat()
      this.emit('onOpen', event)

      // 连接成功后立即获取初始数据
      setTimeout(() => {
        this.getSoftwareList()
        this.getLogStats()
        this.getOperationTypes()
        this.queryLogs()
      }, 500)
    }

    this.ws.onmessage = (event) => {
      try {
        const message = JSON.parse(event.data)
        this.handleMessage(message)
        this.emit('onMessage', message)
      } catch (error) {
        Logger.wsError('解析管理后台消息', error, event.data)
      }
    }

    this.ws.onclose = (event) => {
      this.setState('DISCONNECTED')
      this.stopHeartbeat()
      this.emit('onClose', event)

      // 自动重连
      if (!event.wasClean && this.reconnectAttempts < this.config.RECONNECT_ATTEMPTS) {
        const delay = this.config.RECONNECT_DELAY * Math.pow(2, this.reconnectAttempts)
        setTimeout(() => {
          this.reconnectAttempts++
          this.connect()
        }, delay)
      }
    }

    this.ws.onerror = (event) => {
      this.setState('ERROR')
      this.emit('onError', event)
    }
  }

  // 断开连接
  disconnect() {
    if (this.ws) {
      this.ws.close(1000, 'Client disconnect')
      this.ws = null
    }
    this.stopHeartbeat()
    this.setState('DISCONNECTED')
  }

  // 发送消息
  send(message) {
    if (this.connectionState === 'CONNECTED' && this.ws) {
      const jsonMessage = JSON.stringify(message)
      this.ws.send(jsonMessage)
      return true
    } else {
      return false
    }
  }

  // 处理收到的消息
  handleMessage(message) {
    switch (message.type) {
      case 'info':
        this.handleInfoMessage(message)
        break
      case 'heartbeat':
        break
      case 'software_list_update':
        this.handleSoftwareListUpdate(message)
        break
      case 'log_recorded':
        break
      case 'software_started':
      case 'software_stopped':
      case 'software_restarted':
        // 软件状态变更后自动刷新软件列表
        this.getSoftwareList()
        break
      case 'error':
        Logger.wsError('管理后台', message.message)
        break
      default:
        // 未知消息类型，静默忽略
    }
  }

  // 处理info类型消息
  handleInfoMessage(message) {
    if (message.data) {
      if (message.data.software_list) {
        this.softwareList = message.data.software_list
        this.emit('onSoftwareUpdate', this.softwareList)
      }

      if (message.data.logs) {
        this.logs = message.data.logs
        this.emit('onLogUpdate', this.logs)
      }

      if (message.data.stats) {
        this.logStats = message.data.stats
        this.emit('onStatsUpdate', this.logStats)
      }

      if (message.data.operations) {
        this.operationTypes = message.data.operations
        this.emit('onOperationTypesUpdate', this.operationTypes)
      }

      if (message.data.connected_users) {
        this.connectedUsers = message.data.connected_users
      }
    }
  }

  // 处理软件列表更新
  handleSoftwareListUpdate(message) {
    if (message.data && message.data.software_list) {
      this.softwareList = message.data.software_list
      this.emit('onSoftwareUpdate', this.softwareList)
    }
  }

  // API方法 - 心跳检测
  ping() {
    return this.send({ type: 'ping' })
  }

  // API方法 - 获取服务状态
  getStatus() {
    return this.send({ type: 'get_status' })
  }

  // API方法 - 获取软件列表
  getSoftwareList() {
    return this.send({ type: 'get_software_list' })
  }

  // API方法 - 启动软件
  startSoftware(softwareId) {
    if (!softwareId || typeof softwareId !== 'string' || softwareId.length === 0) {
      Logger.error('启动软件失败: 无效的软件ID', softwareId)
      return false
    }

    return this.send({
      type: 'start_software',
      software_id: softwareId
    })
  }

  // API方法 - 停止软件
  stopSoftware(softwareId) {
    if (!softwareId || typeof softwareId !== 'string' || softwareId.length === 0) {
      Logger.error('停止软件失败: 无效的软件ID', softwareId)
      return false
    }

    return this.send({
      type: 'stop_software',
      software_id: softwareId
    })
  }

  // API方法 - 重启软件
  restartSoftware(softwareId) {
    if (!softwareId || typeof softwareId !== 'string' || softwareId.length === 0) {
      Logger.error('重启软件失败: 无效的软件ID', softwareId)
      return false
    }

    return this.send({
      type: 'restart_software',
      software_id: softwareId
    })
  }

  // API方法 - 记录操作日志
  logOperation(operation, details = '', options = {}) {
    if (!operation || typeof operation !== 'string' || operation.length === 0) {
      Logger.error('记录日志失败: 操作名称不能为空')
      return false
    }

    // 获取当前用户信息
    const currentUser = this.getCurrentUser()
    const username = currentUser?.username || 'anonymous'

    const logData = {
      type: 'log_operation',
      operation: operation.substring(0, 100), // 限制长度
      details: details ? details.substring(0, 1000) : '', // 限制长度
      action_type: options.action_type || 'execute',
      target_object: options.target_object || '',
      status: options.status || 'success',
      duration: options.duration || 0,
      operation_category: options.operation_category || '软件控制',
      user_name: username, // 添加用户名信息
      user_id: username    // 添加用户ID信息
    }

    return this.send(logData)
  }

  // API方法 - 查询操作日志
  queryLogs(filters = {}) {
    const queryData = {
      type: 'query_logs',
      limit: filters.limit || 100,
      offset: filters.offset || 0
    }

    // 添加可选的筛选条件
    if (filters.log_type) queryData.log_type = filters.log_type
    if (filters.operation) queryData.operation = filters.operation
    if (filters.user_id_filter) queryData.user_id_filter = filters.user_id_filter
    if (filters.level) queryData.level = filters.level
    if (filters.start_time) queryData.start_time = filters.start_time
    if (filters.end_time) queryData.end_time = filters.end_time

    return this.send(queryData)
  }

  // API方法 - 根据ID获取日志
  getLogById(logId) {
    if (!logId || typeof logId !== 'string' || logId.length === 0) {
      Logger.error('获取日志失败: 无效的日志ID', logId)
      return false
    }

    return this.send({
      type: 'get_log_by_id',
      log_id: logId
    })
  }

  // API方法 - 获取日志统计信息
  getLogStats() {
    return this.send({ type: 'get_log_stats' })
  }

  // API方法 - 清理过期日志
  cleanupLogs() {
    return this.send({ type: 'cleanup_logs' })
  }

  // API方法 - 获取操作类型列表
  getOperationTypes() {
    return this.send({ type: 'get_operation_types' })
  }

  // 心跳检测
  startHeartbeat() {
    this.heartbeatTimer = setInterval(() => {
      if (this.connectionState === 'CONNECTED') {
        this.ping()
      }
    }, this.config.HEARTBEAT_INTERVAL)
  }

  stopHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer)
      this.heartbeatTimer = null
    }
  }

  // 状态管理
  setState(newState) {
    if (this.connectionState !== newState) {
      const oldState = this.connectionState
      this.connectionState = newState
      this.emit('onStateChange', { oldState, newState })
    }
  }

  // 事件系统
  on(event, callback) {
    if (this.listeners[event]) {
      this.listeners[event].push(callback)
    } else {
      // 静默忽略未知事件类型
    }
  }

  off(event, callback) {
    if (this.listeners[event]) {
      const index = this.listeners[event].indexOf(callback)
      if (index > -1) {
        this.listeners[event].splice(index, 1)
      }
    }
  }

  emit(event, data) {
    if (this.listeners[event]) {
      this.listeners[event].forEach(callback => {
        try {
          callback(data)
        } catch (error) {
          Logger.callbackError(event, error)
        }
      })
    }
  }

  // 获取当前状态
  getState() {
    return {
      connectionState: this.connectionState,
      softwareList: this.softwareList,
      logs: this.logs,
      logStats: this.logStats,
      operationTypes: this.operationTypes,
      connectedUsers: this.connectedUsers
    }
  }
}

// 导出单例实例
export const websocketService = new WebSocketService()

// 默认导出
export default websocketService