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(
  onNotify: (data: ChatMessage) => void,
  sessionId?: number,
  onMessage?: (data: ChatMessage) => void
) {
  onNotifyCallback = onNotify || null
  onMessageCallback = onMessage || null

  const token = getToken()
  // WebSocket URL: 优先使用环境变量，否则根据当前页面协议和域名拼接
  const baseUrl = import.meta.env.VITE_WS_URL
  let wsUrl: string
  if (baseUrl) {
    wsUrl = baseUrl
  } else {
    // 开发环境走 Vite 代理，生产环境走 Nginx 代理
    const protocol = window.location.protocol === 'https:' ? 'https:' : 'http:'
    const host = window.location.host
    const apiPrefix = import.meta.env.VITE_APP_BASE_API || ''
    wsUrl = `${protocol}//${host}${apiPrefix ? '/' + apiPrefix.replace(/^\//, '') : ''}/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] 连接成功')

      // 如果提供了 sessionId，则订阅特定会话的广播
      if (sessionId) {
        stompClient?.subscribe(`/topic/session/${sessionId}`, (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
}
