import { CustomMessageType } from '@/types/im'
import { HeartbeatLevel } from '@/services/im/types'

/**
 * 测试心动等级升降的工具函数
 * 模拟IM消息来触发等级变化
 */

// 心动等级数据映射
const HEARTBEAT_LEVEL_DATA = {
  [HeartbeatLevel.Level1]: { num: 1, name: '初识', startVal: 0 },
  [HeartbeatLevel.Level2]: { num: 2, name: '好感', startVal: 100 },
  [HeartbeatLevel.Level3]: { num: 3, name: '心动', startVal: 300 },
  [HeartbeatLevel.Level4]: { num: 4, name: '暧昧', startVal: 600 },
  [HeartbeatLevel.Level5]: { num: 5, name: '恋人', startVal: 1000 },
  [HeartbeatLevel.Level6]: { num: 6, name: '热恋', startVal: 1500 },
  [HeartbeatLevel.Level7]: { num: 7, name: '深爱', startVal: 2100 },
  [HeartbeatLevel.Level8]: { num: 8, name: '挚爱', startVal: 2800 },
  [HeartbeatLevel.Level9]: { num: 9, name: '永恒', startVal: 3600 },
  [HeartbeatLevel.Level10]: { num: 10, name: '命中注定', startVal: 4500 },
}

interface TestHeartbeatLevelParams {
  aiId: number
  newLevel: HeartbeatLevel
  newHeartbeatVal: number
  isUpgrade?: boolean
  title?: string
}

/**
 * 模拟心动等级变化的IM消息
 */
function simulateHeartbeatLevelChange({
  aiId,
  newLevel,
  newHeartbeatVal,
  isUpgrade = true,
  title,
}: TestHeartbeatLevelParams) {
  const levelData = HEARTBEAT_LEVEL_DATA[newLevel]

  if (!levelData) {
    console.error('无效的心动等级:', newLevel)
    return
  }

  // 构造模拟的IM消息
  const mockMessage = {
    messageClientId: `test_${Date.now()}`,
    messageServerId: `test_server_${Date.now()}`,
    conversationId: `p2p:${aiId}@crushlevel.com`,
    conversationType: 1, // P2P聊天
    senderId: `${aiId}@crushlevel.com`,
    receiverId: `${aiId}@crushlevel.com`, // 这里应该是当前用户ID，但为了测试简化处理
    createTime: Date.now(),
    messageType: 100, // 自定义消息类型
    text: '',
    attachment: {
      raw: JSON.stringify({
        type: isUpgrade
          ? CustomMessageType.HEARTBEAT_LEVEL_UP
          : CustomMessageType.HEARTBEAT_LEVEL_DOWN,
        heartbeatLevel: newLevel,
        heartbeatLevelName: levelData.name,
        heartbeatLevelNum: levelData.num,
        heartbeatVal: newHeartbeatVal,
        title:
          title ||
          (isUpgrade
            ? `恭喜！你们的关系升级到了${levelData.name}`
            : `关系降级到了${levelData.name}`),
      }),
    },
    sendingState: 1,
    messageStatus: 0,
    isSelf: false,
    serverExtension: '',
  }

  // 触发消息处理
  const event = new CustomEvent('nim-message-received', {
    detail: { messages: [mockMessage] },
  })

  window.dispatchEvent(event)

  console.log('🎉 模拟心动等级变化消息已发送:', {
    aiId,
    type: isUpgrade ? '升级' : '降级',
    level: `${levelData.name} (Level ${levelData.num})`,
    heartbeatVal: newHeartbeatVal,
    title:
      title ||
      (isUpgrade ? `恭喜！你们的关系升级到了${levelData.name}` : `关系降级到了${levelData.name}`),
  })
}

/**
 * 测试心动等级升级
 */
function testHeartbeatLevelUpgrade(
  aiId: number,
  targetLevel: HeartbeatLevel,
  heartbeatVal?: number
) {
  const levelData = HEARTBEAT_LEVEL_DATA[targetLevel]
  const testHeartbeatVal = heartbeatVal || levelData.startVal + 50 // 默认比起始值多50

  simulateHeartbeatLevelChange({
    aiId,
    newLevel: targetLevel,
    newHeartbeatVal: testHeartbeatVal,
    isUpgrade: true,
    title: `🎉 恭喜！你们的关系升级到了${levelData.name}！`,
  })
}

/**
 * 测试心动等级降级
 */
function testHeartbeatLevelDowngrade(
  aiId: number,
  targetLevel: HeartbeatLevel,
  heartbeatVal?: number
) {
  const levelData = HEARTBEAT_LEVEL_DATA[targetLevel]
  const testHeartbeatVal = heartbeatVal || levelData.startVal + 20 // 默认比起始值多20

  simulateHeartbeatLevelChange({
    aiId,
    newLevel: targetLevel,
    newHeartbeatVal: testHeartbeatVal,
    isUpgrade: false,
    title: `😔 很遗憾，你们的关系降级到了${levelData.name}...`,
  })
}

/**
 * 快速测试不同等级
 */
function quickTestLevels(aiId: number) {
  const levels = [
    HeartbeatLevel.Level1,
    HeartbeatLevel.Level2,
    HeartbeatLevel.Level3,
    HeartbeatLevel.Level4,
    HeartbeatLevel.Level5,
  ]

  levels.forEach((level, index) => {
    setTimeout(() => {
      if (index % 2 === 0) {
        testHeartbeatLevelUpgrade(aiId, level)
      } else {
        testHeartbeatLevelDowngrade(aiId, level)
      }
    }, index * 2000) // 每2秒触发一次
  })
}

// 将测试方法挂载到window对象上
declare global {
  interface Window {
    testHeartbeatLevel: {
      upgrade: typeof testHeartbeatLevelUpgrade
      downgrade: typeof testHeartbeatLevelDowngrade
      quickTest: typeof quickTestLevels
      simulate: typeof simulateHeartbeatLevelChange
      levels: typeof HeartbeatLevel
    }
  }
}

// 挂载到window
if (typeof window !== 'undefined') {
  window.testHeartbeatLevel = {
    upgrade: testHeartbeatLevelUpgrade,
    downgrade: testHeartbeatLevelDowngrade,
    quickTest: quickTestLevels,
    simulate: simulateHeartbeatLevelChange,
    levels: HeartbeatLevel,
  }

  console.log('🔧 心动等级测试工具已加载到 window.testHeartbeatLevel')
  console.log('使用方法:')
  console.log(
    '- window.testHeartbeatLevel.upgrade(aiId, HeartbeatLevel.Level3) // 测试升级到Level3'
  )
  console.log(
    '- window.testHeartbeatLevel.downgrade(aiId, HeartbeatLevel.Level1) // 测试降级到Level1'
  )
  console.log('- window.testHeartbeatLevel.quickTest(aiId) // 快速测试多个等级变化')
  console.log('- window.testHeartbeatLevel.levels // 查看所有可用等级')
}

export {
  testHeartbeatLevelUpgrade,
  testHeartbeatLevelDowngrade,
  quickTestLevels,
  simulateHeartbeatLevelChange,
  HeartbeatLevel,
}
