import { ElMessage } from 'element-plus'
import SDK from './index'
import emitter from '@/utils/mitt'
import store from '@/store'

export const registerIMEvents = () => {
  SDK.on('onConnectSuccess', () => {
    console.log('[IM] 连接成功')
  })

  SDK.on('onConnectFailed', (err) => {
    console.error('[IM] 连接失败:', err)
  })

  SDK.on('onKickedOffline', () => {
  console.warn('[IM] 被踢下线')
  ElMessage.warning('您已在其他设备登录，当前设备被踢下线')
  store.commit('app/setLoginVisible', true) // 用于触发登录弹窗
})

SDK.on('onUserSigExpired', () => {
    console.warn('[IM] Token 过期')
    ElMessage.warning('登录已过期，请重新登录')
    store.commit('app/setLoginVisible', true)
  })

  SDK.on('onSelfInfoUpdated', async () => {
    console.log('[IM] 用户信息更新')
    await store.dispatch('user/getSelfUserInfo')
  })

  SDK.on('onMsgReceived', (data) => {
    console.log('[IM] 接收到消息:', data)
    store.dispatch('message/handleNewMessages', data)
  })

  SDK.on('onConversationChanged', (data) => {
    console.log('[IM] 会话变更:', data)
    store.dispatch('conversation/updateConversations', data)
  })

  SDK.on('onNewConversation', (data) => {
    console.log('[IM] 新会话:', data)
    store.dispatch('conversation/addConversations', data)
  })

  SDK.on('onTotalUnreadMessageCountChanged', (unreadCount) => {
    console.log('[IM] 未读总数变化:', unreadCount)
    store.commit('conversation/setTotalUnreadCount', unreadCount)
  })

  SDK.on('onGroupInfoChanged', (groupList) => {
    console.log('[IM] 群信息变更:', groupList)
    store.dispatch('group/updateGroupInfo', groupList)
  })

  SDK.on('onGroupMemberAdded', (data) => {
    store.dispatch('group/handleMemberAdded', data)
  })

  SDK.on('onGroupMemberDeleted', (data) => {
    store.dispatch('group/handleMemberDeleted', data)
  })

  SDK.on('onGroupDismissed', (data) => {
    store.dispatch('group/handleGroupDismissed', data)
  })

  SDK.on('onGroupRecycled', (data) => {
    store.dispatch('group/handleGroupRecycled', data)
  })

  SDK.on('onGroupMemberInfoChanged', (data) => {
    store.dispatch('group/handleMemberInfoChanged', data)
  })

  SDK.on('onRecvCustomMessage', (data) => {
    console.log('[IM] 收到自定义消息:', data)
    emitter.emit('custom-message', data)
  })

  SDK.on('onRecvCustomOnlineMessage', (data) => {
    console.log('[IM] 收到在线自定义消息:', data)
    emitter.emit('custom-online-message', data)
  })
}

export const removeIMEvents = () => {
  SDK.offAll()
}
