import { Client, IMessage } from '@stomp/stompjs'
import SockJS from 'sockjs-client'
import { getToken } from '@/utils/auth'

let stompClient: Client | null = null
let onMessageCallback: ((data: any) => void) | null = null
let onNotifyCallback: ((data: any) => void) | null = null

export interface ChatMessage {
  type: string
  msgType?: string
  msgNo?: string
  sessionId?: number
  senderId?: number
  senderName?: string
  senderAvatar?: string
  senderRole?: string
  content?: string
  fileUrl?: string
  fileName?: string
  fileSize?: number
  payload?: any
  sendTime?: string
  orderCardId?: number
  status?: string
  lastReadMsgId?: number
}

export function connectChat(
  sessionNo: string,
  onMessage: (data: ChatMessage) => void,
  onNotify?: (data: ChatMessage) => void
) {
  onMessageCallback = onMessage
  onNotifyCallback = onNotify || null

  const token = getToken()
  const wsUrl = import.meta.env.VITE_WS_URL || 'http://localhost:8080/api/chat/ws/chat'

  stompClient = new Client({
    webSocketFactory: () => new SockJS(wsUrl),
    connectHeaders: {
      Authorization: 'Bearer ' + token
    },
    reconnectDelay: 5000,
    heartbeatIncoming: 4000,
    heartbeatOutgoing: 4000,

    onConnect: () => {
      console.log('[ChatSocket] 连接成功')

      stompClient?.subscribe(`/topic/session/${sessionNo}`, (frame: IMessage) => {
        const data = JSON.parse(frame.body)
        if (onMessageCallback) {
          onMessageCallback(data)
        }
      })

      stompClient?.subscribe('/user/queue/notify', (frame: IMessage) => {
        const data = JSON.parse(frame.body)
        handleNotify(data)
      })
    },

    onDisconnect: () => {
      console.log('[ChatSocket] 连接已断开')
    },

    onStompError: (frame) => {
      console.error('[ChatSocket] 错误:', frame.headers['message'])
    }
  })

  stompClient.activate()
}

export function sendTextByWs(sessionId: number, content: string) {
  if (!stompClient || !stompClient.connected) {
    console.warn('[ChatSocket] 未连接，无法发送消息')
    return
  }
  stompClient.publish({
    destination: '/app/chat/send',
    body: JSON.stringify({
      msgType: 'text',
      sessionId: sessionId,
      msgNo: generateMsgNo(),
      content: content
    })
  })
}

export function disconnectChat() {
  if (stompClient) {
    stompClient.deactivate()
    stompClient = null
  }
}

function handleNotify(data: ChatMessage) {
  console.log('[ChatSocket] 收到通知:', data)
  if (onNotifyCallback) {
    onNotifyCallback(data)
  }
}

export function generateMsgNo(): string {
  return 'MSG_' + Date.now() + '_' + Math.random().toString(36).slice(2, 8)
}

export function isConnected(): boolean {
  return stompClient?.connected || false
}
