let heartCheckTimer: number | null = null
let reconnectTimer: number | null = null
let websocket: WebSocket | null = null

let notifyId = ''
let sendMessageCallback: ((message: any) => void) | null = null
let createMessageCallback: ((message: any) => void) | null = null

function reloadInitWebSocket() {
  initWebSocket(notifyId, sendMessageCallback, createMessageCallback)
}

export function initWebSocket(notify: string | null = null, sendCallback: (message: any) => void, createCallback: (message: any) => void) {
  if (notify) {
    notifyId = notify
  }
  if (sendCallback) {
    sendMessageCallback = sendCallback
  }
  if (createCallback) {
    createMessageCallback = createCallback
  }

  // 已有连接则不重复连接（包括正在连接或已连接的状态）
  if (websocket && (websocket.readyState === WebSocket.OPEN || websocket.readyState === WebSocket.CONNECTING)) {
    console.log('>>>> webSocket 连接 已存在')
    return
  }

  // 初始化 WebSocket
  websocket = new WebSocket(`ws:${window.location.host}/socket/af-system/sendMessage?userId=${notifyId}:phone`)

  // WebSocket 打开连接时触发
  websocket.onopen = () => {
    startHeartCheck()
  }

  // WebSocket 连接发生错误时触发
  websocket.onerror = () => {
    reconnect()
  }

  // WebSocket 接收到消息时触发
  websocket.onmessage = (event: MessageEvent) => {
    try {
      if (event.data === 'phone_ping')
        return
      const message = JSON.parse(event.data)
      if (message && message.sendMessage === true) {
        // 接收消息 处理自己的业务, 不再 提示列表中展示 (后端直接调用system-sendMessage)
        sendMessageCallback?.(message)
      }
      else {
        // 消息数据 处理 更新消息列表展示
        createMessageCallback?.(message)
        sendMessageCallback?.(message)
      }
    }
    catch (e) {
      console.error('WebSocket message parsing error:', e)
    }
  }

  // WebSocket 连接关闭时触发
  websocket.onclose = () => {
    stopHeartCheck()
    reconnect()
  }
}

// 停止心跳检测
function stopHeartCheck() {
  if (heartCheckTimer !== null) {
    clearInterval(heartCheckTimer)
    heartCheckTimer = null
  }
}

// 心跳机制
function startHeartCheck() {
  stopHeartCheck()
  heartCheckTimer = window.setInterval(() => {
    if (websocket && websocket.readyState === WebSocket.OPEN) {
      websocket.send(JSON.stringify({ event: 'phone_ping', userList: [`${notifyId}:phone`] }))
    }
  }, 30000)
}

function reconnect() {
  // 防止频繁重连
  if (reconnectTimer !== null) {
    return
  }

  reconnectTimer = window.setTimeout(() => {
    reloadInitWebSocket() // 重新初始化 WebSocket
    reconnectTimer = null
  }, 5000) // 5秒尝试重连
}

// 关闭 WebSocket 连接
export function closeWebSocket() {
  if (websocket) {
    websocket.close()
    websocket = null
  }
  stopHeartCheck()
  if (reconnectTimer !== null) {
    clearTimeout(reconnectTimer)
    reconnectTimer = null
  }
}
